From ab9ffd68d7b0845ea67143bece18cd2a32d7be63 Mon Sep 17 00:00:00 2001 From: simonox Date: Mon, 27 Feb 2023 15:43:31 +0100 Subject: [PATCH] commit dist folder as it's used by javascript modules --- .gitignore | 1 - .../influxdb-client/dist/index.browser.js | 12 + .../influxdb-client/dist/index.browser.js.gz | Bin 0 -> 10002 bytes .../influxdb-client/dist/index.browser.js.map | 1 + .../influxdb-client/dist/index.browser.mjs | 6 + .../influxdb-client/dist/index.browser.mjs.gz | Bin 0 -> 9593 bytes .../dist/index.browser.mjs.map | 1 + .../influxdb-client/dist/index.d.ts | 1197 + .../@influxdata/influxdb-client/dist/index.js | 6 + .../influxdb-client/dist/index.js.gz | Bin 0 -> 10858 bytes .../influxdb-client/dist/index.js.map | 1 + .../influxdb-client/dist/index.mjs | 6 + .../influxdb-client/dist/index.mjs.gz | Bin 0 -> 10404 bytes .../influxdb-client/dist/index.mjs.map | 1 + .../influxdb-client/dist/influxdb.js | 6 + .../influxdb-client/dist/influxdb.js.gz | Bin 0 -> 9815 bytes .../influxdb-client/dist/influxdb.js.map | 1 + .../gridstack/dist/gridstack-extra.css | 555 + .../gridstack/dist/gridstack-extra.min.css | 6 + .../gridstack/dist/gridstack-poly.js | 105 + .../gridstack/dist/gridstack-poly.min.js | 3 + .../gridstack/dist/gridstack.all.js | 17 + .../node_modules/gridstack/dist/gridstack.css | 243 + .../gridstack/dist/gridstack.d.ts | 549 + .../gridstack/dist/gridstack.jQueryUI.js | 89 + .../gridstack/dist/gridstack.jQueryUI.min.js | 3 + .../node_modules/gridstack/dist/gridstack.js | 2033 + .../gridstack/dist/gridstack.min.css | 6 + .../gridstack/dist/gridstack.min.js | 9 + .../gridstack/dist/gridstack.min.map | 1 + .../node_modules/gridstack/dist/jquery-ui.js | 4034 ++ .../gridstack/dist/jquery-ui.min.js | 6 + .../node_modules/gridstack/dist/jquery.js | 10598 +++++ .../node_modules/gridstack/dist/jquery.min.js | 2 + .../flow/node_modules/jquery/dist/jquery.js | 10993 +++++ .../node_modules/jquery/dist/jquery.min.js | 2 + .../node_modules/jquery/dist/jquery.min.map | 1 + .../node_modules/jquery/dist/jquery.slim.js | 8894 ++++ .../jquery/dist/jquery.slim.min.js | 2 + .../jquery/dist/jquery.slim.min.map | 1 + .../jquery/external/sizzle/dist/sizzle.js | 2542 ++ .../jquery/external/sizzle/dist/sizzle.min.js | 3 + .../external/sizzle/dist/sizzle.min.map | 1 + .../node-red-dashboard/dist/css/app.min.css | 33721 ++++++++++++++++ .../node-red-dashboard/dist/css/app.min.less | 889 + .../dist/css/gridstack-extra.min.css | 6 + .../dist/dashboard.appcache | 29 + .../dist/fonts/MaterialIcons-Regular.woff | Bin 0 -> 160576 bytes .../dist/fonts/MaterialIcons-Regular.woff2 | Bin 0 -> 125116 bytes .../dist/fonts/fontawesome-webfont.woff | Bin 0 -> 98024 bytes .../dist/fonts/fontawesome-webfont.woff2 | Bin 0 -> 77160 bytes .../dist/fonts/weather-icons-lite.woff | Bin 0 -> 17312 bytes .../dist/fonts/weather-icons-lite.woff2 | Bin 0 -> 14056 bytes .../node-red-dashboard/dist/i18n.js | 4 + .../node-red-dashboard/dist/icon120x120.png | Bin 0 -> 3425 bytes .../node-red-dashboard/dist/icon192x192.png | Bin 0 -> 5697 bytes .../node-red-dashboard/dist/icon64x64.png | Bin 0 -> 1967 bytes .../node-red-dashboard/dist/index.html | 17 + .../node-red-dashboard/dist/js/app.min.js | 608 + .../dist/js/tinycolor-min.js | 4 + .../@tootallnate/once/dist/index.d.ts | 7 + .../@tootallnate/once/dist/index.js | 24 + .../@tootallnate/once/dist/index.js.map | 1 + .../once/dist/overloaded-parameters.d.ts | 231 + .../once/dist/overloaded-parameters.js | 3 + .../once/dist/overloaded-parameters.js.map | 1 + .../@tootallnate/once/dist/types.d.ts | 17 + .../@tootallnate/once/dist/types.js | 3 + .../@tootallnate/once/dist/types.js.map | 1 + .../dist/abort-controller.d.ts | 43 + .../abort-controller/dist/abort-controller.js | 127 + .../dist/abort-controller.js.map | 1 + .../dist/abort-controller.mjs | 118 + .../dist/abort-controller.mjs.map | 1 + .../dist/abort-controller.umd.js | 5 + .../dist/abort-controller.umd.js.map | 1 + .../agent-base/dist/src/index.d.ts | 78 + .../node_modules/agent-base/dist/src/index.js | 203 + .../agent-base/dist/src/index.js.map | 1 + .../agent-base/dist/src/promisify.d.ts | 4 + .../agent-base/dist/src/promisify.js | 18 + .../agent-base/dist/src/promisify.js.map | 1 + .../npm/node_modules/diff/dist/diff.js | 1627 + .../npm/node_modules/diff/dist/diff.min.js | 38 + .../dist/event-target-shim.js | 871 + .../dist/event-target-shim.js.map | 1 + .../dist/event-target-shim.mjs | 862 + .../dist/event-target-shim.mjs.map | 1 + .../dist/event-target-shim.umd.js | 6 + .../dist/event-target-shim.umd.js.map | 1 + .../http-proxy-agent/dist/agent.d.ts | 32 + .../http-proxy-agent/dist/agent.js | 145 + .../http-proxy-agent/dist/agent.js.map | 1 + .../http-proxy-agent/dist/index.d.ts | 21 + .../http-proxy-agent/dist/index.js | 14 + .../http-proxy-agent/dist/index.js.map | 1 + .../https-proxy-agent/dist/agent.d.ts | 30 + .../https-proxy-agent/dist/agent.js | 177 + .../https-proxy-agent/dist/agent.js.map | 1 + .../https-proxy-agent/dist/index.d.ts | 23 + .../https-proxy-agent/dist/index.js | 14 + .../https-proxy-agent/dist/index.js.map | 1 + .../dist/parse-proxy-response.d.ts | 7 + .../dist/parse-proxy-response.js | 66 + .../dist/parse-proxy-response.js.map | 1 + .../minimatch/dist/cjs/index-cjs.d.ts | 35 + .../minimatch/dist/cjs/index-cjs.js | 7 + .../minimatch/dist/cjs/index-cjs.js.map | 1 + .../minimatch/dist/cjs/index.d.ts | 71 + .../node_modules/minimatch/dist/cjs/index.js | 1090 + .../minimatch/dist/cjs/index.js.map | 1 + .../minimatch/dist/cjs/package.json | 3 + .../minimatch/dist/mjs/index.d.ts | 71 + .../node_modules/minimatch/dist/mjs/index.js | 1077 + .../minimatch/dist/mjs/index.js.map | 1 + .../minimatch/dist/mjs/package.json | 3 + .../postcss-selector-parser/dist/index.js | 24 + .../postcss-selector-parser/dist/parser.js | 1243 + .../postcss-selector-parser/dist/processor.js | 206 + .../dist/selectors/attribute.js | 540 + .../dist/selectors/className.js | 69 + .../dist/selectors/combinator.js | 31 + .../dist/selectors/comment.js | 31 + .../dist/selectors/constructors.js | 102 + .../dist/selectors/container.js | 395 + .../dist/selectors/guards.js | 64 + .../dist/selectors/id.js | 37 + .../dist/selectors/index.js | 27 + .../dist/selectors/namespace.js | 101 + .../dist/selectors/nesting.js | 32 + .../dist/selectors/node.js | 239 + .../dist/selectors/pseudo.js | 38 + .../dist/selectors/root.js | 60 + .../dist/selectors/selector.js | 31 + .../dist/selectors/string.js | 31 + .../dist/selectors/tag.js | 31 + .../dist/selectors/types.js | 28 + .../dist/selectors/universal.js | 32 + .../dist/sortAscending.js | 13 + .../dist/tokenTypes.js | 95 + .../postcss-selector-parser/dist/tokenize.js | 271 + .../dist/util/ensureObject.js | 22 + .../dist/util/getProp.js | 24 + .../dist/util/index.js | 22 + .../dist/util/stripComments.js | 27 + .../dist/util/unesc.js | 93 + .../node_modules/sigstore/dist/ca/format.d.ts | 5 + .../node_modules/sigstore/dist/ca/format.js | 14 + .../node_modules/sigstore/dist/ca/index.d.ts | 14 + .../node_modules/sigstore/dist/ca/index.js | 23 + .../sigstore/dist/ca/verify/chain.d.ts | 3 + .../sigstore/dist/ca/verify/chain.js | 64 + .../sigstore/dist/ca/verify/index.d.ts | 2 + .../sigstore/dist/ca/verify/index.js | 21 + .../sigstore/dist/ca/verify/sct.d.ts | 3 + .../sigstore/dist/ca/verify/sct.js | 30 + .../sigstore/dist/ca/verify/signer.d.ts | 3 + .../sigstore/dist/ca/verify/signer.js | 131 + .../node_modules/sigstore/dist/cli/index.d.ts | 1 + .../node_modules/sigstore/dist/cli/index.js | 113 + .../sigstore/dist/client/error.d.ts | 10 + .../sigstore/dist/client/error.js | 21 + .../sigstore/dist/client/fulcio.d.ts | 18 + .../sigstore/dist/client/fulcio.js | 53 + .../sigstore/dist/client/index.d.ts | 2 + .../sigstore/dist/client/index.js | 22 + .../sigstore/dist/client/rekor.d.ts | 45 + .../sigstore/dist/client/rekor.js | 115 + .../npm/node_modules/sigstore/dist/error.d.ts | 13 + .../npm/node_modules/sigstore/dist/error.js | 38 + .../sigstore/dist/identity/ci.d.ts | 11 + .../node_modules/sigstore/dist/identity/ci.js | 65 + .../sigstore/dist/identity/index.d.ts | 25 + .../sigstore/dist/identity/index.js | 46 + .../sigstore/dist/identity/issuer.d.ts | 15 + .../sigstore/dist/identity/issuer.js | 53 + .../sigstore/dist/identity/oauth.d.ts | 19 + .../sigstore/dist/identity/oauth.js | 188 + .../sigstore/dist/identity/provider.d.ts | 3 + .../sigstore/dist/identity/provider.js | 2 + .../npm/node_modules/sigstore/dist/index.d.ts | 1 + .../npm/node_modules/sigstore/dist/index.js | 42 + .../sigstore/dist/merkle/digest.d.ts | 8 + .../sigstore/dist/merkle/digest.js | 48 + .../sigstore/dist/merkle/index.d.ts | 2 + .../sigstore/dist/merkle/index.js | 22 + .../sigstore/dist/merkle/verify.d.ts | 3 + .../sigstore/dist/merkle/verify.js | 78 + .../npm/node_modules/sigstore/dist/sign.d.ts | 23 + .../npm/node_modules/sigstore/dist/sign.js | 73 + .../sigstore/dist/sigstore-utils.d.ts | 7 + .../sigstore/dist/sigstore-utils.js | 58 + .../node_modules/sigstore/dist/sigstore.d.ts | 30 + .../node_modules/sigstore/dist/sigstore.js | 188 + .../sigstore/dist/tlog/format.d.ts | 6 + .../node_modules/sigstore/dist/tlog/format.js | 105 + .../sigstore/dist/tlog/index.d.ts | 21 + .../node_modules/sigstore/dist/tlog/index.js | 67 + .../types/__generated__/hashedrekord.d.ts | 50 + .../tlog/types/__generated__/hashedrekord.js | 8 + .../dist/tlog/types/__generated__/intoto.d.ts | 131 + .../dist/tlog/types/__generated__/intoto.js | 8 + .../sigstore/dist/tlog/types/index.d.ts | 38 + .../sigstore/dist/tlog/types/index.js | 5 + .../sigstore/dist/tlog/verify/body.d.ts | 2 + .../sigstore/dist/tlog/verify/body.js | 113 + .../sigstore/dist/tlog/verify/index.d.ts | 2 + .../sigstore/dist/tlog/verify/index.js | 75 + .../sigstore/dist/tlog/verify/set.d.ts | 2 + .../sigstore/dist/tlog/verify/set.js | 67 + .../node_modules/sigstore/dist/tuf/index.d.ts | 2 + .../node_modules/sigstore/dist/tuf/index.js | 76 + .../sigstore/dist/tuf/trustroot.d.ts | 11 + .../sigstore/dist/tuf/trustroot.js | 163 + .../sigstore/dist/types/signature.d.ts | 16 + .../sigstore/dist/types/signature.js | 15 + .../sigstore/__generated__/envelope.d.ts | 46 + .../types/sigstore/__generated__/envelope.js | 89 + .../google/api/field_behavior.d.ts | 52 + .../google/api/field_behavior.js | 119 + .../google/protobuf/descriptor.d.ts | 939 + .../google/protobuf/descriptor.js | 1308 + .../google/protobuf/timestamp.d.ts | 110 + .../google/protobuf/timestamp.js | 24 + .../__generated__/sigstore_bundle.d.ts | 72 + .../sigstore/__generated__/sigstore_bundle.js | 106 + .../__generated__/sigstore_common.d.ts | 228 + .../sigstore/__generated__/sigstore_common.js | 457 + .../__generated__/sigstore_rekor.d.ts | 129 + .../sigstore/__generated__/sigstore_rekor.js | 167 + .../__generated__/sigstore_trustroot.d.ts | 89 + .../__generated__/sigstore_trustroot.js | 103 + .../__generated__/sigstore_verification.d.ts | 156 + .../__generated__/sigstore_verification.js | 273 + .../sigstore/dist/types/sigstore/index.d.ts | 46 + .../sigstore/dist/types/sigstore/index.js | 144 + .../dist/types/sigstore/serialized.d.ts | 74 + .../dist/types/sigstore/serialized.js | 2 + .../dist/types/sigstore/validate.d.ts | 16 + .../sigstore/dist/types/sigstore/validate.js | 88 + .../sigstore/dist/types/utility.d.ts | 14 + .../sigstore/dist/types/utility.js | 18 + .../sigstore/dist/util/crypto.d.ts | 10 + .../node_modules/sigstore/dist/util/crypto.js | 64 + .../node_modules/sigstore/dist/util/dsse.d.ts | 2 + .../node_modules/sigstore/dist/util/dsse.js | 25 + .../sigstore/dist/util/encoding.d.ts | 6 + .../sigstore/dist/util/encoding.js | 46 + .../sigstore/dist/util/index.d.ts | 8 + .../node_modules/sigstore/dist/util/index.js | 49 + .../node_modules/sigstore/dist/util/json.d.ts | 1 + .../node_modules/sigstore/dist/util/json.js | 61 + .../node_modules/sigstore/dist/util/oidc.d.ts | 1 + .../node_modules/sigstore/dist/util/oidc.js | 54 + .../node_modules/sigstore/dist/util/pem.d.ts | 4 + .../node_modules/sigstore/dist/util/pem.js | 65 + .../sigstore/dist/util/promise.d.ts | 1 + .../sigstore/dist/util/promise.js | 27 + .../sigstore/dist/util/stream.d.ts | 24 + .../node_modules/sigstore/dist/util/stream.js | 116 + .../node_modules/sigstore/dist/util/ua.d.ts | 1 + .../npm/node_modules/sigstore/dist/util/ua.js | 33 + .../node_modules/sigstore/dist/verify.d.ts | 13 + .../npm/node_modules/sigstore/dist/verify.js | 142 + .../sigstore/dist/x509/asn1/dump.d.ts | 2 + .../sigstore/dist/x509/asn1/dump.js | 97 + .../sigstore/dist/x509/asn1/error.d.ts | 4 + .../sigstore/dist/x509/asn1/error.js | 24 + .../sigstore/dist/x509/asn1/length.d.ts | 4 + .../sigstore/dist/x509/asn1/length.js | 63 + .../sigstore/dist/x509/asn1/obj.d.ts | 18 + .../sigstore/dist/x509/asn1/obj.js | 166 + .../sigstore/dist/x509/asn1/parse.d.ts | 7 + .../sigstore/dist/x509/asn1/parse.js | 125 + .../sigstore/dist/x509/asn1/tag.d.ts | 28 + .../sigstore/dist/x509/asn1/tag.js | 86 + .../node_modules/sigstore/dist/x509/cert.d.ts | 48 + .../node_modules/sigstore/dist/x509/cert.js | 241 + .../node_modules/sigstore/dist/x509/ext.d.ts | 41 + .../node_modules/sigstore/dist/x509/ext.js | 157 + .../node_modules/sigstore/dist/x509/sct.d.ts | 26 + .../node_modules/sigstore/dist/x509/sct.js | 101 + .../sigstore/dist/x509/verify.d.ts | 8 + .../node_modules/sigstore/dist/x509/verify.js | 159 + .../socks-proxy-agent/dist/index.d.ts | 33 + .../socks-proxy-agent/dist/index.js | 197 + .../socks-proxy-agent/dist/index.js.map | 1 + .../npm/node_modules/tuf-js/dist/error.d.ts | 30 + .../npm/node_modules/tuf-js/dist/error.js | 62 + .../npm/node_modules/tuf-js/dist/fetcher.d.ts | 19 + .../npm/node_modules/tuf-js/dist/fetcher.js | 81 + .../npm/node_modules/tuf-js/dist/index.d.ts | 3 + .../npm/node_modules/tuf-js/dist/index.js | 9 + .../node_modules/tuf-js/dist/models/base.d.ts | 30 + .../node_modules/tuf-js/dist/models/base.js | 71 + .../tuf-js/dist/models/delegations.d.ts | 32 + .../tuf-js/dist/models/delegations.js | 115 + .../node_modules/tuf-js/dist/models/file.d.ts | 40 + .../node_modules/tuf-js/dist/models/file.js | 183 + .../tuf-js/dist/models/index.d.ts | 5 + .../node_modules/tuf-js/dist/models/index.js | 13 + .../node_modules/tuf-js/dist/models/key.d.ts | 21 + .../node_modules/tuf-js/dist/models/key.js | 109 + .../tuf-js/dist/models/metadata.d.ts | 45 + .../tuf-js/dist/models/metadata.js | 139 + .../node_modules/tuf-js/dist/models/role.d.ts | 103 + .../node_modules/tuf-js/dist/models/role.js | 298 + .../node_modules/tuf-js/dist/models/root.d.ts | 28 + .../node_modules/tuf-js/dist/models/root.js | 107 + .../tuf-js/dist/models/signature.d.ts | 19 + .../tuf-js/dist/models/signature.js | 32 + .../tuf-js/dist/models/snapshot.d.ts | 23 + .../tuf-js/dist/models/snapshot.js | 71 + .../tuf-js/dist/models/targets.d.ts | 19 + .../tuf-js/dist/models/targets.js | 89 + .../tuf-js/dist/models/timestamp.d.ts | 21 + .../tuf-js/dist/models/timestamp.js | 58 + .../npm/node_modules/tuf-js/dist/store.d.ts | 19 + .../npm/node_modules/tuf-js/dist/store.js | 209 + .../npm/node_modules/tuf-js/dist/updater.d.ts | 33 + .../npm/node_modules/tuf-js/dist/updater.js | 306 + .../tuf-js/dist/utils/config.d.ts | 12 + .../node_modules/tuf-js/dist/utils/config.js | 14 + .../node_modules/tuf-js/dist/utils/guard.d.ts | 8 + .../node_modules/tuf-js/dist/utils/guard.js | 39 + .../node_modules/tuf-js/dist/utils/index.d.ts | 5 + .../node_modules/tuf-js/dist/utils/index.js | 31 + .../node_modules/tuf-js/dist/utils/json.d.ts | 2 + .../node_modules/tuf-js/dist/utils/json.js | 62 + .../node_modules/tuf-js/dist/utils/key.d.ts | 9 + .../npm/node_modules/tuf-js/dist/utils/key.js | 143 + .../node_modules/tuf-js/dist/utils/oid.d.ts | 2 + .../npm/node_modules/tuf-js/dist/utils/oid.js | 27 + .../tuf-js/dist/utils/signer.d.ts | 3 + .../node_modules/tuf-js/dist/utils/signer.js | 13 + .../tuf-js/dist/utils/tmpfile.d.ts | 3 + .../node_modules/tuf-js/dist/utils/tmpfile.js | 25 + .../node_modules/tuf-js/dist/utils/types.d.ts | 10 + .../node_modules/tuf-js/dist/utils/types.js | 10 + .../socket.io-adapter/dist/contrib/yeast.d.ts | 23 + .../socket.io-adapter/dist/contrib/yeast.js | 55 + .../socket.io-adapter/dist/index.d.ts | 179 + .../socket.io-adapter/dist/index.js | 394 + .../socket.io/dist/broadcast-operator.d.ts | 283 + .../socket.io/dist/broadcast-operator.js | 437 + .../node_modules/socket.io/dist/client.d.ts | 120 + .../node_modules/socket.io/dist/client.js | 268 + .../node_modules/socket.io/dist/index.d.ts | 538 + .../flow/node_modules/socket.io/dist/index.js | 802 + .../socket.io/dist/namespace.d.ts | 442 + .../node_modules/socket.io/dist/namespace.js | 593 + .../socket.io/dist/parent-namespace.d.ts | 30 + .../socket.io/dist/parent-namespace.js | 82 + .../node_modules/socket.io/dist/socket.d.ts | 669 + .../node_modules/socket.io/dist/socket.js | 983 + .../socket.io/dist/typed-events.d.ts | 148 + .../socket.io/dist/typed-events.js | 81 + .../flow/node_modules/socket.io/dist/uws.d.ts | 3 + .../flow/node_modules/socket.io/dist/uws.js | 135 + 359 files changed, 107503 insertions(+), 1 deletion(-) create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js.gz create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js.map create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.mjs create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.mjs.gz create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.mjs.map create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.d.ts create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.js create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.js.gz create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.js.map create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.mjs create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.mjs.gz create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/index.mjs.map create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js.gz create mode 100644 software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js.map create mode 100644 software/flow/node_modules/gridstack/dist/gridstack-extra.css create mode 100644 software/flow/node_modules/gridstack/dist/gridstack-extra.min.css create mode 100644 software/flow/node_modules/gridstack/dist/gridstack-poly.js create mode 100644 software/flow/node_modules/gridstack/dist/gridstack-poly.min.js create mode 100644 software/flow/node_modules/gridstack/dist/gridstack.all.js create mode 100644 software/flow/node_modules/gridstack/dist/gridstack.css create mode 100644 software/flow/node_modules/gridstack/dist/gridstack.d.ts create mode 100644 software/flow/node_modules/gridstack/dist/gridstack.jQueryUI.js create mode 100644 software/flow/node_modules/gridstack/dist/gridstack.jQueryUI.min.js create mode 100644 software/flow/node_modules/gridstack/dist/gridstack.js create mode 100644 software/flow/node_modules/gridstack/dist/gridstack.min.css create mode 100644 software/flow/node_modules/gridstack/dist/gridstack.min.js create mode 100644 software/flow/node_modules/gridstack/dist/gridstack.min.map create mode 100644 software/flow/node_modules/gridstack/dist/jquery-ui.js create mode 100644 software/flow/node_modules/gridstack/dist/jquery-ui.min.js create mode 100644 software/flow/node_modules/gridstack/dist/jquery.js create mode 100644 software/flow/node_modules/gridstack/dist/jquery.min.js create mode 100644 software/flow/node_modules/jquery/dist/jquery.js create mode 100644 software/flow/node_modules/jquery/dist/jquery.min.js create mode 100644 software/flow/node_modules/jquery/dist/jquery.min.map create mode 100644 software/flow/node_modules/jquery/dist/jquery.slim.js create mode 100644 software/flow/node_modules/jquery/dist/jquery.slim.min.js create mode 100644 software/flow/node_modules/jquery/dist/jquery.slim.min.map create mode 100644 software/flow/node_modules/jquery/external/sizzle/dist/sizzle.js create mode 100644 software/flow/node_modules/jquery/external/sizzle/dist/sizzle.min.js create mode 100644 software/flow/node_modules/jquery/external/sizzle/dist/sizzle.min.map create mode 100644 software/flow/node_modules/node-red-dashboard/dist/css/app.min.css create mode 100644 software/flow/node_modules/node-red-dashboard/dist/css/app.min.less create mode 100644 software/flow/node_modules/node-red-dashboard/dist/css/gridstack-extra.min.css create mode 100644 software/flow/node_modules/node-red-dashboard/dist/dashboard.appcache create mode 100644 software/flow/node_modules/node-red-dashboard/dist/fonts/MaterialIcons-Regular.woff create mode 100644 software/flow/node_modules/node-red-dashboard/dist/fonts/MaterialIcons-Regular.woff2 create mode 100644 software/flow/node_modules/node-red-dashboard/dist/fonts/fontawesome-webfont.woff create mode 100644 software/flow/node_modules/node-red-dashboard/dist/fonts/fontawesome-webfont.woff2 create mode 100644 software/flow/node_modules/node-red-dashboard/dist/fonts/weather-icons-lite.woff create mode 100644 software/flow/node_modules/node-red-dashboard/dist/fonts/weather-icons-lite.woff2 create mode 100644 software/flow/node_modules/node-red-dashboard/dist/i18n.js create mode 100644 software/flow/node_modules/node-red-dashboard/dist/icon120x120.png create mode 100644 software/flow/node_modules/node-red-dashboard/dist/icon192x192.png create mode 100644 software/flow/node_modules/node-red-dashboard/dist/icon64x64.png create mode 100644 software/flow/node_modules/node-red-dashboard/dist/index.html create mode 100644 software/flow/node_modules/node-red-dashboard/dist/js/app.min.js create mode 100644 software/flow/node_modules/node-red-dashboard/dist/js/tinycolor-min.js create mode 100644 software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.js create mode 100644 software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.js.map create mode 100644 software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.js create mode 100644 software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.js.map create mode 100644 software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.js create mode 100644 software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.js.map create mode 100644 software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.js create mode 100644 software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.js.map create mode 100644 software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.mjs create mode 100644 software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.mjs.map create mode 100644 software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.umd.js create mode 100644 software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.umd.js.map create mode 100644 software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.js create mode 100644 software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.js.map create mode 100644 software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.js create mode 100644 software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.js.map create mode 100644 software/flow/node_modules/npm/node_modules/diff/dist/diff.js create mode 100644 software/flow/node_modules/npm/node_modules/diff/dist/diff.min.js create mode 100644 software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.js create mode 100644 software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.js.map create mode 100644 software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.mjs create mode 100644 software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.mjs.map create mode 100644 software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.umd.js create mode 100644 software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.umd.js.map create mode 100644 software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.js create mode 100644 software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.js.map create mode 100644 software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.js create mode 100644 software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.js.map create mode 100644 software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.js create mode 100644 software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.js.map create mode 100644 software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.js create mode 100644 software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.js.map create mode 100644 software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.js create mode 100644 software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.js create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.js.map create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.js create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.js.map create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/package.json create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.js create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.js.map create mode 100644 software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/package.json create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/index.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/parser.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/processor.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/attribute.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/className.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/combinator.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/comment.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/constructors.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/container.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/guards.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/id.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/index.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/namespace.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/nesting.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/node.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/pseudo.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/root.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/selector.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/string.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/tag.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/types.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/universal.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/sortAscending.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/tokenTypes.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/tokenize.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/ensureObject.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/getProp.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/index.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/stripComments.js create mode 100644 software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/unesc.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/format.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/format.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/chain.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/chain.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/sct.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/sct.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/signer.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/signer.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/cli/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/cli/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/client/error.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/client/error.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/client/fulcio.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/client/fulcio.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/client/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/client/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/client/rekor.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/client/rekor.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/error.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/error.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/identity/ci.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/identity/ci.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/identity/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/identity/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/identity/issuer.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/identity/issuer.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/identity/oauth.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/identity/oauth.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/identity/provider.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/identity/provider.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/digest.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/digest.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/verify.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/verify.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/sign.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/sign.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore-utils.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore-utils.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/format.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/format.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/hashedrekord.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/hashedrekord.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/intoto.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/intoto.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/body.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/body.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/set.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/set.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/trustroot.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/trustroot.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/signature.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/signature.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/envelope.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/envelope.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/api/field_behavior.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/api/field_behavior.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/descriptor.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/descriptor.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/timestamp.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/timestamp.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_bundle.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_bundle.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_common.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_common.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_rekor.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_rekor.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_trustroot.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_trustroot.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_verification.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_verification.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/serialized.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/serialized.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/validate.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/validate.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/utility.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/types/utility.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/crypto.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/crypto.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/dsse.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/dsse.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/encoding.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/encoding.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/index.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/json.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/json.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/oidc.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/oidc.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/pem.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/pem.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/promise.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/promise.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/stream.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/stream.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/ua.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/util/ua.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/verify.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/verify.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/dump.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/dump.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/error.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/error.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/length.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/length.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/obj.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/obj.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/parse.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/parse.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/tag.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/tag.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/cert.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/cert.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/ext.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/ext.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/sct.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/sct.js create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/verify.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/sigstore/dist/x509/verify.js create mode 100644 software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.js create mode 100644 software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.js.map create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/error.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/error.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/fetcher.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/fetcher.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/index.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/base.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/base.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/delegations.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/delegations.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/file.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/file.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/index.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/key.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/key.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/metadata.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/metadata.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/role.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/role.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/root.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/root.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/signature.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/signature.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/snapshot.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/snapshot.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/targets.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/targets.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/timestamp.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/models/timestamp.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/store.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/store.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/updater.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/updater.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/config.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/config.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/guard.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/guard.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/index.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/index.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/json.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/json.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/key.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/key.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/oid.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/oid.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/signer.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/signer.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/tmpfile.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/tmpfile.js create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/types.d.ts create mode 100644 software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/types.js create mode 100644 software/flow/node_modules/socket.io-adapter/dist/contrib/yeast.d.ts create mode 100644 software/flow/node_modules/socket.io-adapter/dist/contrib/yeast.js create mode 100644 software/flow/node_modules/socket.io-adapter/dist/index.d.ts create mode 100644 software/flow/node_modules/socket.io-adapter/dist/index.js create mode 100644 software/flow/node_modules/socket.io/dist/broadcast-operator.d.ts create mode 100644 software/flow/node_modules/socket.io/dist/broadcast-operator.js create mode 100644 software/flow/node_modules/socket.io/dist/client.d.ts create mode 100644 software/flow/node_modules/socket.io/dist/client.js create mode 100644 software/flow/node_modules/socket.io/dist/index.d.ts create mode 100644 software/flow/node_modules/socket.io/dist/index.js create mode 100644 software/flow/node_modules/socket.io/dist/namespace.d.ts create mode 100644 software/flow/node_modules/socket.io/dist/namespace.js create mode 100644 software/flow/node_modules/socket.io/dist/parent-namespace.d.ts create mode 100644 software/flow/node_modules/socket.io/dist/parent-namespace.js create mode 100644 software/flow/node_modules/socket.io/dist/socket.d.ts create mode 100644 software/flow/node_modules/socket.io/dist/socket.js create mode 100644 software/flow/node_modules/socket.io/dist/typed-events.d.ts create mode 100644 software/flow/node_modules/socket.io/dist/typed-events.js create mode 100644 software/flow/node_modules/socket.io/dist/uws.d.ts create mode 100644 software/flow/node_modules/socket.io/dist/uws.js diff --git a/.gitignore b/.gitignore index 1a4f782..6f2914d 100644 --- a/.gitignore +++ b/.gitignore @@ -24,7 +24,6 @@ result /flow_backup.json # Mkdocs -dist docs/_* site diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js new file mode 100644 index 0000000..dc51f82 --- /dev/null +++ b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js @@ -0,0 +1,12 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@influxdata/influxdb-client"] = {})); +})(this, (function (exports) { +"use strict";var influxdb=(()=>{var k=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Pe=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},Fe=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of De(e))!Ee.call(r,i)&&i!==t&&k(r,i,{get:()=>e[i],enumerable:!(n=Ae(e,i))||n.enumerable});return r};var Le=r=>Fe(k({},"__esModule",{value:!0}),r);var nt={};Pe(nt,{AbortError:()=>x,DEFAULT_ConnectionOptions:()=>We,DEFAULT_RetryDelayStrategyOptions:()=>Y,DEFAULT_WriteOptions:()=>Z,FLUX_VALUE:()=>D,HttpError:()=>m,IllegalArgumentError:()=>y,InfluxDB:()=>U,LineSplitter:()=>b,Log:()=>p,Point:()=>ue,RequestTimedOutError:()=>v,UNKNOWN_COLUMN:()=>Q,canRetryHttpCall:()=>Be,chunksToLines:()=>R,chunksToLinesIterable:()=>M,consoleLogger:()=>Te,convertTimeToNanos:()=>se,createFluxTableColumn:()=>Ie,createFluxTableMetaData:()=>A,createTextDecoderCombiner:()=>g,currentTime:()=>ne,dateToProtocolTimestamp:()=>ie,escape:()=>w,flux:()=>et,fluxBool:()=>Ze,fluxDateTime:()=>Ge,fluxDuration:()=>Ke,fluxExpression:()=>oe,fluxFloat:()=>qe,fluxInteger:()=>Je,fluxRegExp:()=>Ye,fluxString:()=>je,getRetryDelay:()=>j,isStatusCodeRetriable:()=>pe,linesToRowsIterable:()=>J,linesToTables:()=>V,newFluxTableColumn:()=>S,sanitizeFloat:()=>ae,sanitizeInteger:()=>le,serializeDateTimeAsDate:()=>Me,serializeDateTimeAsNumber:()=>_e,serializeDateTimeAsString:()=>Ve,setLogger:()=>Ne,stringToLines:()=>ze,symbolObservable:()=>X,toFluxValue:()=>H,typeSerializers:()=>C,useProcessHrtime:()=>we});function g(){let r=new TextDecoder("utf-8");return{concat(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n},copy(e,t,n){let i=new Uint8Array(n-t);return i.set(e.subarray(t,n)),i},toUtf8String(e,t,n){return r.decode(e.subarray(t,n))}}}function R(r,e){let t=e!=null?e:g(),n,i=!1,s=!1,o=!1,a;function f(l){let c,d=0;for(n?(c=l.length===0?0:n.length,l=t.concat(n,l)):c=0;c0&&l[c-1]===13?c-1:c;if(i)return;if(o=r.next(t.toUtf8String(l,d,$))===!1,d=c+1,o)break}}else T===34&&(s=!s);c++}if(d{o=!1,f(new Uint8Array(0))});return}u.error(new Error("Unable to pause, useResume is not configured!")),o=!1}a&&(a(),a=void 0)}let u={next(l){if(!i)try{return f(l),!o}catch(c){this.error(c)}return!0},error(l){i||(i=!0,r.error(l))},complete(){i||(n&&r.next(t.toUtf8String(n,0,n.length)),i=!0,r.complete())}};return r.useCancellable&&(u.useCancellable=l=>{r.useCancellable&&r.useCancellable({cancel(){l.cancel(),n=void 0,u.complete()},isCancelled(){return l.isCancelled()}})}),r.useResume&&(u.useResume=l=>{a=l}),u}async function*M(r,e){let t=e!=null?e:g(),n,i=!1;for await(let s of r){let o,a=0;for(n?(o=n.length,s=t.concat(n,s)):o=0;o0&&s[o-1]===13?o-1:o;yield t.toUtf8String(s,a,u),a=o+1}}else f===34&&(i=!i);o++}ar,C={boolean:r=>r===""?null:r==="true",unsignedLong:r=>r===""?null:+r,long:r=>r===""?null:+r,double(r){switch(r){case"":return null;case"+Inf":return Number.POSITIVE_INFINITY;case"-Inf":return Number.NEGATIVE_INFINITY;default:return+r}},string:N,base64Binary:N,duration:r=>r===""?null:r,"dateTime:RFC3339":r=>r===""?null:r},_=class{get(e){var n;let t=e[this.index];return(t===""||t===void 0)&&this.defaultValue&&(t=this.defaultValue),((n=C[this.dataType])!=null?n:N)(t)}},Q=Object.freeze({label:"",dataType:"",group:!1,defaultValue:"",index:Number.MAX_SAFE_INTEGER,get:()=>{}});function S(){return new _}function Ie(r){var t,n;let e=new _;return e.label=String(r.label),e.dataType=r.dataType,e.group=Boolean(r.group),e.defaultValue=(t=r.defaultValue)!=null?t:"",e.index=(n=r.index)!=null?n:0,e}var Ue=[404,408,425,429,500,502,503,504];function pe(r){return Ue.includes(r)}var y=class extends Error{constructor(e){super(e),this.name="IllegalArgumentError",Object.setPrototypeOf(this,y.prototype)}},m=class extends Error{constructor(t,n,i,s,o,a){super();this.statusCode=t;this.statusMessage=n;this.body=i;this.contentType=o;if(Object.setPrototypeOf(this,m.prototype),a)this.message=a;else if(i){if(o!=null&&o.startsWith("application/json"))try{this.json=JSON.parse(i),this.message=this.json.message,this.code=this.json.code}catch(f){}this.message||(this.message=`${t} ${n} : ${i}`)}else this.message=`${t} ${n}`;this.name="HttpError",this.setRetryAfter(s)}setRetryAfter(t){typeof t=="string"?/^[0-9]+$/.test(t)?this._retryAfter=parseInt(t):this._retryAfter=0:this._retryAfter=0}canRetry(){return pe(this.statusCode)}retryAfter(){return this._retryAfter}},$e=["ECONNRESET","ENOTFOUND","ESOCKETTIMEDOUT","ETIMEDOUT","ECONNREFUSED","EHOSTUNREACH","EPIPE"];function Be(r){if(r){if(typeof r.canRetry=="function")return!!r.canRetry();if(r.code&&$e.includes(r.code))return!0}else return!1;return!1}function j(r,e){if(r){let t;return typeof r.retryAfter=="function"?r.retryAfter():(t=0,e&&e>0?t+Math.round(Math.random()*e):t)}else return 0}var v=class extends Error{constructor(){super(),Object.setPrototypeOf(this,v.prototype),this.name="RequestTimedOutError",this.message="Request timed out"}canRetry(){return!0}retryAfter(){return 0}},x=class extends Error{constructor(){super(),this.name="AbortError",Object.setPrototypeOf(this,x.prototype),this.message="Response aborted"}canRetry(){return!0}retryAfter(){return 0}};function Me(){C["dateTime:RFC3339"]=r=>r===""?null:new Date(Date.parse(r))}function _e(){C["dateTime:RFC3339"]=r=>r===""?null:Date.parse(r)}function Ve(){C["dateTime:RFC3339"]=r=>r===""?null:r}var q=class{constructor(e){e.forEach((t,n)=>t.index=n),this.columns=e}column(e,t=!0){for(let n=0;n0&&r.charCodeAt(i-1)===13?i-1:i;e.next(r.substring(n,o)),n=i+1}}else s===34&&(t=!t);i++}ntypeof Symbol=="function"&&Symbol.observable||"@@observable")();var K=class{constructor(e,t){this.isClosed=!1;try{t({next:n=>{e.next(n)},error:n=>{this.isClosed=!0,e.error(n)},complete:()=>{this.isClosed=!0,e.complete()},useCancellable:n=>{this.cancellable=n}})}catch(n){this.isClosed=!0,e.error(n)}}get closed(){return this.isClosed}unsubscribe(){var e;(e=this.cancellable)==null||e.cancel(),this.isClosed=!0}};function G(){}function He(r){let{next:e,error:t,complete:n}=r;return{next:e?e.bind(r):G,error:t?t.bind(r):G,complete:n?n.bind(r):G}}var O=class{constructor(e,t){this.executor=e;this.decorator=t}subscribe(e,t,n){let i=He(typeof e!="object"||e===null?{next:e,error:t,complete:n}:e);return new K(this.decorator(i),this.executor)}[X](){return this}};Symbol.observable;var We={timeout:1e4},Y={retryJitter:200,minRetryDelay:5e3,maxRetryDelay:125e3,exponentialBase:5,randomRetry:!0},Z={batchSize:1e3,maxBatchBytes:5e7,flushInterval:6e4,writeFailed:function(){},writeSuccess:function(){},writeRetrySkipped:function(){},maxRetries:5,maxRetryTime:18e4,maxBufferLines:32e3,retryJitter:200,minRetryDelay:5e3,maxRetryDelay:125e3,exponentialBase:2,gzipThreshold:1e3,randomRetry:!0};function ee(r,e){return function(t){let n="",i=0,s=0;for(;s=0&&(n+=t.substring(i,s),n+=e[o],i=s+1),s++}return i==0?t:(i'"'+t(n)+'"'}var w={measurement:ee(`, +\r `,["\\,","\\ ","\\n","\\r","\\t"]),quoted:ke('"\\',['\\"',"\\\\"]),tag:ee(`, = +\r `,["\\,","\\ ","\\=","\\n","\\r","\\t"])};var xe="000000000";function we(r){return!1}we(!0);var he=Date.now(),te=0;function re(){{let r=Date.now();r!==he?(he=r,te=0):te++;let e=String(te);return String(r)+xe.substr(0,6-e.length)+e}}function ye(){return String(Date.now())+xe.substr(0,3)}function ge(){return String(Date.now())}function be(){return String(Math.floor(Date.now()/1e3))}var ne={s:be,ms:ge,us:ye,ns:re,seconds:be,millis:ge,micros:ye,nanos:re},ie={s:r=>`${Math.floor(r.getTime()/1e3)}`,ms:r=>`${r.getTime()}`,us:r=>`${r.getTime()}000`,ns:r=>`${r.getTime()}000000`};function se(r){return r===void 0?re():typeof r=="string"?r.length>0?r:void 0:r instanceof Date?`${r.getTime()}000000`:String(typeof r=="number"?Math.floor(r):r)}var Te={error(r,e){console.error("ERROR: "+r,e||"")},warn(r,e){console.warn("WARN: "+r,e||"")}},z=Te,p={error(r,e){z.error(r,e)},warn(r,e){z.warn(r,e)}};function Ne(r){let e=z;return z=r,e}var D=Symbol("FLUX_VALUE"),h=class{constructor(e){this.fluxValue=e}toString(){return this.fluxValue}[D](){return this.fluxValue}};function Qe(r){return typeof r=="object"&&typeof r[D]=="function"}function E(r){if(r==null)return"";r=r.toString();let e,t=0;function n(){e===void 0&&(e=r.substring(0,t))}for(;t="0"&&i<="9"||i=="-")){if(i==="."){n=!0;continue}return`float(v: "${t}")`}return n?t:t+".0"}function qe(r){return new h(ae(r))}function le(r){let e=String(r),t=e.startsWith("-"),n=t?e.substring(1):e;if(n.length===0||n.length>19)throw new Error(`not a flux integer: ${e}`);for(let i of n)if(i<"0"||i>"9")throw new Error(`not a flux integer: ${e}`);if(n.length===19){if(t&&n>"9223372036854775808")throw new Error(`flux integer out of bounds: ${e}`);if(!t&&n>"9223372036854775807")throw new Error(`flux integer out of bounds: ${e}`)}return e}function Je(r){return new h(le(r))}function Xe(r){return`time(v: "${E(r)}")`}function Ge(r){return new h(Xe(r))}function Ke(r){return new h(`duration(v: "${E(r)}")`)}function Re(r){return r instanceof RegExp?r.toString():new RegExp(r).toString()}function Ye(r){return new h(Re(r))}function Ze(r){return r==="true"||r==="false"?new h(r):new h((!!r).toString())}function oe(r){return new h(String(r))}function H(r){if(r===void 0)return"";if(r===null)return"null";if(typeof r=="boolean")return r.toString();if(typeof r=="string")return`"${E(r)}"`;if(typeof r=="number")return Number.isSafeInteger(r)?le(r):ae(r);if(typeof r=="object"){if(typeof r[D]=="function")return r[D]();if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return Re(r);if(Array.isArray(r))return`[${r.map(H).join(",")}]`}else if(typeof r=="bigint")return`${r}.0`;return H(r.toString())}function et(r,...e){if(r.length==1&&e.length===0)return oe(r[0]);let t=new Array(r.length+e.length),n=0;for(let i=0;i=9223372036854776e3)throw new Error(`invalid integer value for field '${e}': '${t}'!`);return this.fields[e]=`${Math.floor(n)}i`,this}uintField(e,t){if(typeof t=="number"){if(isNaN(t)||t<0||t>Number.MAX_SAFE_INTEGER)throw new Error(`uint value for field '${e}' out of range: ${t}`);this.fields[e]=`${Math.floor(t)}u`}else{let n=String(t);for(let i=0;i57)throw new Error(`uint value has an unsupported character at pos ${i}: ${t}`)}if(n.length>20||n.length===20&&n.localeCompare("18446744073709551615")>0)throw new Error(`uint value for field '${e}' out of range: ${n}`);this.fields[e]=`${n}u`}return this}floatField(e,t){let n;if(typeof t=="number"?n=t:n=parseFloat(t),!isFinite(n))throw new Error(`invalid float value for field '${e}': ${t}`);return this.fields[e]=String(n),this}stringField(e,t){return t!=null&&(typeof t!="string"&&(t=String(t)),this.fields[e]=w.quoted(t)),this}timestamp(e){return this.time=e,this}toLineProtocol(e){if(!this.name)return;let t="";if(Object.keys(this.fields).sort().forEach(o=>{if(o){let a=this.fields[o];t.length>0&&(t+=","),t+=`${w.tag(o)}=${a}`}}),t.length===0)return;let n="",i=e&&e.defaultTags?{...e.defaultTags,...this.tags}:this.tags;Object.keys(i).sort().forEach(o=>{if(o){let a=i[o];a&&(n+=",",n+=`${w.tag(o)}=${w.tag(a)}`)}});let s=this.time;return e&&e.convertTime?s=e.convertTime(s):s=se(s),`${w.measurement(this.name)}${n} ${t}${s!==void 0?" "+s:""}`}toString(){let e=this.toLineProtocol(void 0);return e||`invalid point: ${JSON.stringify(this,void 0)}`}};var fe=class{constructor(e){this.options={...Y,...e},this.success()}nextDelay(e,t){let n=j(e);if(n&&n>0)return n+Math.round(Math.random()*this.options.retryJitter);if(t&&t>0){if(this.options.randomRetry){let s=Math.max(this.options.minRetryDelay,1),o=s*this.options.exponentialBase;for(let a=1;a=this.options.maxRetryDelay){o=this.options.maxRetryDelay;break}return s+Math.round(Math.random()*(o-s)+Math.random()*this.options.retryJitter)}let i=Math.max(this.options.minRetryDelay,1);for(let s=1;s=this.options.maxRetryDelay){i=this.options.maxRetryDelay;break}return i+Math.round(Math.random()*this.options.retryJitter)}else this.currentDelay?this.currentDelay=Math.min(Math.max(this.currentDelay*this.options.exponentialBase,1)+Math.round(Math.random()*this.options.retryJitter),this.options.maxRetryDelay):this.currentDelay=this.options.minRetryDelay+Math.round(Math.random()*this.options.retryJitter);return this.currentDelay}success(){this.currentDelay=void 0}};function Ce(r){return new fe(r)}function tt(r){let e,t=r,n=r;for(;n.next;)n.next.expires{}){this.maxLines=e;this.retryLines=t;this.onShrink=n;this.size=0;this.closed=!1;this._timeoutHandle=void 0}addLines(e,t,n,i){if(this.closed||!e.length)return;let s=Date.now()+n;if(ithis.maxLines){let u=this.size,l=u*.7;do{let[c,d]=tt(this.first);this.size-=c.lines.length,d?d.next=c.next:(this.first=c.next,this.first&&this.scheduleRetry(this.first.retryTime-Date.now())),c.next=void 0,this.onShrink(c)}while(this.first&&this.size+e.length>l);p.error(`RetryBuffer: ${u-this.size} oldest lines removed to keep buffer size under the limit of ${this.maxLines} lines.`)}let o={lines:e,retryCount:t,retryTime:s,expires:i},a=this.first,f;for(;;){if(!a||a.retryTime>s){o.next=a,f?f.next=o:(this.first=o,this.scheduleRetry(s-Date.now()));break}f=a,a=a.next}this.size+=e.length}removeLines(){if(this.first){let e=this.first;return this.first=this.first.next,e.next=void 0,this.size-=e.lines.length,e}}scheduleRetry(e){this._timeoutHandle&&clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{let t=this.removeLines();t?this.retryLines(t.lines,t.retryCount,t.expires).catch(()=>{}).finally(()=>{this.first&&this.scheduleRetry(this.first.retryTime-Date.now())}):this._timeoutHandle=void 0},Math.max(e,0))}async flush(){let e;for(;e=this.removeLines();)await this.retryLines(e.lines,e.retryCount,e.expires)}close(){return this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this.closed=!0,this.size}};function ce(r){let e=r.length;for(let t=0;t=128&&n<=2047?e++:n>=2048&&n<=65535?n>=55296&&n<=57343?e++:e+=2:e+=3)}return e}var de=class{constructor(e,t,n,i){this.maxChunkRecords=e;this.maxBatchBytes=t;this.flushFn=n;this.scheduleSend=i;this.length=0;this.bytes=-1;this.lines=new Array(e)}add(e){let t=ce(e);this.length===0?this.scheduleSend():this.bytes+t+1>=this.maxBatchBytes&&this.flush().catch(n=>{}),this.lines[this.length]=e,this.length++,this.bytes+=t+1,(this.length>=this.maxChunkRecords||this.bytes>=this.maxBatchBytes)&&this.flush().catch(n=>{})}flush(){let e=this.reset();return e.length>0?this.flushFn(e):Promise.resolve()}reset(){let e=this.lines.slice(0,this.length);return this.length=0,this.bytes=-1,e}},F=class{constructor(e,t,n,i,s){this.transport=e;this.closed=!1;this._timeoutHandle=void 0;this.path=`/api/v2/write?org=${encodeURIComponent(t)}&bucket=${encodeURIComponent(n)}&precision=${i}`,s!=null&&s.consistency&&(this.path+=`&consistency=${encodeURIComponent(s.consistency)}`),this.writeOptions={...Z,...s},this.currentTime=ne[i],this.dateToProtocolTimestamp=ie[i],this.writeOptions.defaultTags&&this.useDefaultTags(this.writeOptions.defaultTags),this.sendOptions={method:"POST",headers:{"content-type":"text/plain; charset=utf-8",...s==null?void 0:s.headers},gzipThreshold:this.writeOptions.gzipThreshold};let o=()=>{this.writeOptions.flushInterval>0&&(this._clearFlushTimeout(),this.closed||(this._timeoutHandle=setTimeout(()=>this.sendBatch(this.writeBuffer.reset(),this.writeOptions.maxRetries).catch(a=>{}),this.writeOptions.flushInterval)))};this.writeBuffer=new de(this.writeOptions.batchSize,this.writeOptions.maxBatchBytes,a=>(this._clearFlushTimeout(),this.sendBatch(a,this.writeOptions.maxRetries)),o),this.sendBatch=this.sendBatch.bind(this),this.retryStrategy=Ce(this.writeOptions),this.retryBuffer=new P(this.writeOptions.maxBufferLines,this.sendBatch,this.writeOptions.writeRetrySkipped)}sendBatch(e,t,n=Date.now()+this.writeOptions.maxRetryTime){let i=this,s=i.writeOptions.maxRetries+1-t;if(!this.closed&&e.length>0){if(n<=Date.now()){let o=new Error("Max retry time exceeded."),a=i.writeOptions.writeFailed.call(i,o,e,s,n);return a||(p.error(`Write to InfluxDB failed (attempt: ${s}).`,o),Promise.reject(o))}return new Promise((o,a)=>{let f,u={responseStarted(l,c){f=c},error(l){let c=i.writeOptions.writeFailed.call(i,l,e,s,n);if(c){c.then(o,a);return}if(l instanceof m&&l.json&&typeof l.json.error=="string"&&l.json.error.includes("hinted handoff queue not empty")){p.warn("Write to InfluxDB returns: "+l.json.error),f=204,u.complete();return}if(!i.closed&&t>0&&(!(l instanceof m)||l.statusCode>=429)){p.warn(`Write to InfluxDB failed (attempt: ${s}).`,l),i.retryBuffer.addLines(e,t-1,i.retryStrategy.nextDelay(l,s),n),a(l);return}p.error("Write to InfluxDB failed.",l),a(l)},complete(){if(f==204||f==null)i.writeOptions.writeSuccess.call(i,e),i.retryStrategy.success(),o();else{let l=`204 HTTP response status code expected, but ${f} returned`,c=new m(f,l,void 0,"0");c.message=l,u.error(c)}}};this.transport.send(this.path,e.join(` +`),this.sendOptions,u)})}else return Promise.resolve()}_clearFlushTimeout(){this._timeoutHandle!==void 0&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0)}writeRecord(e){if(this.closed)throw new Error("writeApi: already closed!");this.writeBuffer.add(e)}writeRecords(e){if(this.closed)throw new Error("writeApi: already closed!");for(let t=0;t{let t=this.retryBuffer.close();t&&p.error(`Retry buffer closed with ${t} items that were not written to InfluxDB!`,null),this.closed=!0})}dispose(){return this._clearFlushTimeout(),this.closed=!0,this.retryBuffer.close()+this.writeBuffer.length}useDefaultTags(e){return this.defaultTags=e,this}convertTime(e){return e===void 0?this.currentTime():typeof e=="string"?e.length>0?e:void 0:e instanceof Date?this.dateToProtocolTimestamp(e):String(typeof e=="number"?Math.floor(e):e)}};function me(r={}){let e=0,t={next:n=>{if(e===0&&r.next&&n!==null&&n!==void 0)return r.next(n)},error:n=>{e===0&&(e=1,r.error&&r.error(n))},complete:()=>{e===0&&(e=2,r.complete&&r.complete())},responseStarted:(n,i)=>{r.responseStarted&&r.responseStarted(n,i)}};return r.useCancellable&&(t.useCancellable=r.useCancellable.bind(r)),r.useResume&&(t.useResume=r.useResume.bind(r)),t}function Oe(r){let e={};return r.headers.forEach((t,n)=>{let i=e[n];i===void 0?e[n]=t:Array.isArray(i)?i.push(t):e[n]=[i,t]}),e}var L=class{constructor(e){this.connectionOptions=e;this.chunkCombiner=g();this.requestDecorator=function(){};this.defaultHeaders={"content-type":"application/json; charset=utf-8",...e.headers},this.connectionOptions.token&&(this.defaultHeaders.Authorization="Token "+this.connectionOptions.token),this.url=String(this.connectionOptions.url),this.url.endsWith("/")&&(this.url=this.url.substring(0,this.url.length-1)),this.url.endsWith("/api/v2")&&(this.url=this.url.substring(0,this.url.length-7),p.warn(`Please remove '/api/v2' context path from InfluxDB base url, using ${this.url} !`))}send(e,t,n,i){let s=me(i),o=!1,a=n.signal,f,u=()=>{},l=u;if(i&&i.useCancellable){let c=new AbortController;a||(a=c.signal,n={...n,signal:a}),a.addEventListener("abort",()=>{l()}),i.useCancellable({cancel(){o=!0,c.abort()},isCancelled(){return o||a.aborted}})}this.fetch(e,t,n).then(async c=>{if(i!=null&&i.responseStarted&&s.responseStarted(Oe(c),c.status),await this.throwOnErrorResponse(c),c.body){let d=c.body.getReader(),T;do{if(f&&await f,o)break;if(T=await d.read(),s.next(T.value)===!1){let $=s.useResume;if(!$){let B="Unable to pause, useResume is not configured!";return await d.cancel(B),Promise.reject(new Error(B))}f=new Promise(B=>{l=()=>{B(),f=void 0,l=u},$(l)})}}while(!T.done)}else if(c.arrayBuffer){let d=await c.arrayBuffer();s.next(new Uint8Array(d))}else{let d=await c.text();s.next(new TextEncoder().encode(d))}}).catch(c=>{o||s.error(c)}).finally(()=>s.complete())}async throwOnErrorResponse(e){if(e.status>=300){let t="";try{if(t=await e.text(),!t){let n=e.headers.get("x-influxdb-error");n&&(t=n)}}catch(n){throw p.warn("Unable to receive error body",n),new m(e.status,e.statusText,void 0,e.headers.get("retry-after"),e.headers.get("content-type"))}throw new m(e.status,e.statusText,t,e.headers.get("retry-after"),e.headers.get("content-type"))}}async*iterate(e,t,n){var s;let i=await this.fetch(e,t,n);if(await this.throwOnErrorResponse(i),i.body){let o=i.body.getReader();for(;;){let{value:a,done:f}=await o.read();if(f)break;if((s=n.signal)!=null&&s.aborted)throw await i.body.cancel(),new x;yield a}}else if(i.arrayBuffer){let o=await i.arrayBuffer();yield new Uint8Array(o)}else{let o=await i.text();yield new TextEncoder().encode(o)}}async request(e,t,n,i){var u,l;let s=await this.fetch(e,t,n),{headers:o}=s,a=o.get("content-type")||"";i&&i(Oe(s),s.status),await this.throwOnErrorResponse(s);let f=(l=(u=n.headers)==null?void 0:u.accept)!=null?l:a;if(f.includes("json"))return await s.json();if(f.includes("text")||f.startsWith("application/csv"))return await s.text()}fetch(e,t,n){let{method:i,headers:s,...o}=n,a=`${this.url}${e}`,f={method:i,body:i==="GET"||i==="HEAD"?void 0:typeof t=="string"?t:JSON.stringify(t),headers:{...this.defaultHeaders,...s},credentials:"omit",...this.connectionOptions.transportOptions,...o};return this.requestDecorator(f,n,a),fetch(a,f)}};var Se={header:!0,delimiter:",",quoteChar:'"',commentPrefix:"#",annotations:["datatype","group","default"]},I=class{constructor(e,t,n){this.transport=e;this.createCSVResponse=t;this.options=typeof n=="string"?{org:n}:n}with(e){return new I(this.transport,this.createCSVResponse,{...this.options,...e})}response(e){let{org:t,type:n,gzip:i,headers:s}=this.options,o=`/api/v2/query?org=${encodeURIComponent(t)}`,a=JSON.stringify(this.decorateRequest({query:e.toString(),dialect:Se,type:n})),f={method:"POST",headers:{"content-type":"application/json; encoding=utf-8","accept-encoding":i?"gzip":"identity",...s}};return this.createCSVResponse(u=>this.transport.send(o,a,f,u),()=>this.transport.iterate(o,a,f))}iterateLines(e){return this.response(e).iterateLines()}iterateRows(e){return this.response(e).iterateRows()}lines(e){return this.response(e).lines()}rows(e){return this.response(e).rows()}queryLines(e,t){return this.response(e).consumeLines(t)}queryRows(e,t){return this.response(e).consumeRows(t)}collectRows(e,t){return this.response(e).collectRows(t)}collectLines(e){return this.response(e).collectLines()}queryRaw(e){let{org:t,type:n,gzip:i,headers:s}=this.options;return this.transport.request(`/api/v2/query?org=${encodeURIComponent(t)}`,JSON.stringify(this.decorateRequest({query:e.toString(),dialect:Se,type:n})),{method:"POST",headers:{accept:"text/csv","accept-encoding":i?"gzip":"identity","content-type":"application/json; encoding=utf-8",...s}})}decorateRequest(e){var t;return typeof this.options.now=="function"&&(e.now=this.options.now()),e.type=(t=this.options.type)!=null?t:"flux",e}},ve=I;function rt(r,e){return e.toObject(r)}var W=class{constructor(e,t,n){this.executor=e;this.iterableResultExecutor=t;this.chunkCombiner=n}iterateLines(){return M(this.iterableResultExecutor())}iterateRows(){return J(M(this.iterableResultExecutor()))}lines(){return new O(this.executor,e=>R(e,this.chunkCombiner))}rows(){return new O(this.executor,e=>R(V({next(t,n){e.next({values:t,tableMeta:n})},error(t){e.error(t)},complete(){e.complete()}}),this.chunkCombiner))}consumeLines(e){this.executor(R(e,this.chunkCombiner))}consumeRows(e){this.executor(R(V(e),this.chunkCombiner))}collectRows(e=rt){let t=[];return new Promise((n,i)=>{this.consumeRows({next(s,o){let a=e.call(this,s,o);a!==void 0&&t.push(a)},error(s){i(s)},complete(){n(t)}})})}collectLines(){let e=[];return new Promise((t,n)=>{this.consumeLines({next(i){e.push(i)},error(i){n(i)},complete(){t(e)}})})}};var U=class{constructor(e){var n;if(typeof e=="string")this._options={url:e};else if(e!==null&&typeof e=="object")this._options=e;else throw new y("No url or configuration specified!");let t=this._options.url;if(typeof t!="string")throw new y("No url specified!");t.endsWith("/")&&(this._options.url=t.substring(0,t.length-1)),this.transport=(n=this._options.transport)!=null?n:new L(this._options),this.processCSVResponse=(i,s)=>new W(i,s,this.transport.chunkCombiner)}getWriteApi(e,t,n="ns",i){return new F(this.transport,e,t,n,i!=null?i:this._options.writeOptions)}getQueryApi(e){return new ve(this.transport,this.processCSVResponse,e)}};return Le(nt);})(); +Object.defineProperty(exports, '__esModule', { value: true });Object.assign(exports, influxdb);})); +//# sourceMappingURL=index.browser.js.map \ No newline at end of file diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js.gz b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js.gz new file mode 100644 index 0000000000000000000000000000000000000000..8bf8cb43d8e317ee6998f1d29471d3f4b90950ac GIT binary patch literal 10002 zcmV+tC+*lDiwFP!000021GRl?Tiiy{=;t@TLTG&kX{Q+vzQm5kg2fnOCpI{Mb6LVM zVx|Wa3uz+t7~?_z{Zv(7r4iUk-m}lM&ZsZd)z#H?>*^+$&hxQIi`)y&v*Iktm^V$v zqA0IJZ}E-iiR&3JrXK$^D@sv$aU6TA#n~TxELOceN0MELyChSj5iio^da6SnhqqUZ_8rFOL0xjx45o6=VJdV*Of1LH7?T` zAWY3(+|q0>x#ShK*fA|;Wg!Zr*5D$koVL{LEsukeaYSuelmQkAz}e&B2PhY80q`S! zEKV5D=a;-p&N3dY4C}CFyRs`Z%CUPo4S27oIVg^O$vFPajZ>y+=7%_1#$hZEs$TGb zhvCW&AB>YM1E^`(>!q-sqSr$_Qi%srkRPW_T!K8_g6_~Iyt&B-wyF+CB^UED_sW{) z`kKdOys^uJ55b~l{`>d5dPA)2Ggy~wE+@vykXq*=Ueu$vJjj6xTW7GqJ7rmvgv2NI zVrO^j-Rq>dF%DN9V&RiUJ5a@NL;d4S;o(kY^ywnIp+?3*X$Ls-H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t{k1yfg#X7(cswIUOH}rgTNU752<*}?M!n303GRaOaK4? literal 0 HcmV?d00001 diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js.map b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js.map new file mode 100644 index 0000000..0285231 --- /dev/null +++ b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/results/chunkCombiner.ts","../src/results/chunksToLines.ts","../src/results/chunksToLinesIterable.ts","../src/results/LineSplitter.ts","../src/results/FluxTableColumn.ts","../src/errors.ts","../src/results/FluxTableMetaData.ts","../src/results/linesToTables.ts","../src/results/linesToRowsIterable.ts","../src/results/stringToLines.ts","../src/observable/symbol.ts","../src/results/ObservableQuery.ts","../src/options.ts","../src/util/escape.ts","../src/util/currentTime.ts","../src/util/logger.ts","../src/query/flux.ts","../src/Point.ts","../src/impl/retryStrategy.ts","../src/impl/RetryBuffer.ts","../src/util/utf8Length.ts","../src/impl/WriteApiImpl.ts","../src/impl/completeCommunicationObserver.ts","../src/impl/browser/FetchTransport.ts","../src/impl/QueryApiImpl.ts","../src/results/AnnotatedCSVResponseImpl.ts","../src/InfluxDB.ts"],"sourcesContent":["/**\n * The `@influxdata/influxdb-client` package provides optimized APIs that write or query InfluxDB v2.\n *\n * @remarks\n * The entry point of this package is the {@link @influxdata/influxdb-client#InfluxDB } class. It is\n * initialized with options that tells how to communicate with InfluxDB. The simple usage pattern is:\n *\n * ```\n * import {InfluxDB} = from('@influxdata/influxdb-client')\n * const influxDB = new InfluxDB({\n * url: \"http://localhost:8086\",\n * token: \"your-api-token\"\n * })\n * ```\n *\n * The influxDB object let you create two essential API instances, {@link @influxdata/influxdb-client#InfluxDB.getWriteApi }\n * and {@link @influxdata/influxdb-client#InfluxDB.getQueryApi }. The {@link @influxdata/influxdb-client#WriteApi}\n * asynchronously writes measurement points on background, in batches to optimize network traffic, and with retries\n * upon failures. The {@link @influxdata/influxdb-client#QueryApi} let you execute a flux query against InfluxDB\n * and offers several ways to stream query results.\n *\n * The influxDB object is also used to create more specialized InfluxDB management API instances in\n * {@link @influxdata/influxdb-client-apis# | @influxdata/influxdb-client-apis} .\n *\n * See also {@link https://github.com/influxdata/influxdb-client-js/tree/master/examples | examples} to know more.\n *\n * @packageDocumentation\n */\nexport * from './results'\nexport * from './options'\nexport * from './errors'\nexport * from './util/escape'\nexport * from './util/currentTime'\nexport * from './util/logger'\nexport * from './query'\nexport * from './transport'\nexport * from './observable'\nexport * from './Point'\nexport {default as InfluxDB} from './InfluxDB'\nexport {default as QueryApi, QueryOptions} from './QueryApi'\nexport {default as WriteApi} from './WriteApi'\n","/**\n * ChunkCombiner is a simplified platform-neutral manipulation of Uint8arrays\n * that allows to process text data on the fly. The implementation can be optimized\n * for the target platform (node vs browser).\n */\nexport interface ChunkCombiner {\n /**\n * Concatenates first and second chunk.\n * @param first - first chunk\n * @param second - second chunk\n * @returns first + second\n */\n concat(first: Uint8Array, second: Uint8Array): Uint8Array\n\n /**\n * Converts chunk into a string.\n * @param chunk - chunk\n * @param start - start index\n * @param end - end index\n * @returns string representation of chunk slice\n */\n toUtf8String(chunk: Uint8Array, start: number, end: number): string\n\n /**\n * Creates a new chunk from the supplied chunk.\n * @param chunk - chunk to copy\n * @param start - start index\n * @param end - end index\n * @returns a copy of a chunk slice\n */\n copy(chunk: Uint8Array, start: number, end: number): Uint8Array\n}\n\n// TextDecoder is available since node v8.3.0 and in all modern browsers\ndeclare class TextDecoder {\n constructor(encoding: string)\n decode(chunk: Uint8Array): string\n}\n\n/**\n * Creates a chunk combiner instance that uses UTF-8\n * TextDecoder to decode Uint8Arrays into strings.\n */\nexport function createTextDecoderCombiner(): ChunkCombiner {\n const decoder = new TextDecoder('utf-8')\n return {\n concat(first: Uint8Array, second: Uint8Array): Uint8Array {\n const retVal = new Uint8Array(first.length + second.length)\n retVal.set(first)\n retVal.set(second, first.length)\n return retVal\n },\n copy(chunk: Uint8Array, start: number, end: number): Uint8Array {\n const retVal = new Uint8Array(end - start)\n retVal.set(chunk.subarray(start, end))\n return retVal\n },\n toUtf8String(chunk: Uint8Array, start: number, end: number): string {\n return decoder.decode(chunk.subarray(start, end))\n },\n }\n}\n","import {ChunkCombiner, createTextDecoderCombiner} from './chunkCombiner'\nimport {CommunicationObserver} from './CommunicationObserver'\nimport {Cancellable} from './Cancellable'\n\n/**\n * ChunksToLines is a transformation that accepts Uint8Array instances\n * and emmits strings representing CSV lines.\n * @param target - target to emmit CSV lines to\n * @param chunkCombiner - chunk combiner\n * @returns communication obrver to accept Uint8Arrays\n */\nexport function chunksToLines(\n target: CommunicationObserver,\n chunkCombiner?: ChunkCombiner\n): CommunicationObserver {\n const chunks = chunkCombiner ?? createTextDecoderCombiner()\n let previous: Uint8Array | undefined\n let finished = false\n let quoted = false\n let paused = false\n let resumeChunks: (() => void) | undefined\n\n function bufferReceived(chunk: Uint8Array): void {\n let index: number\n let start = 0\n if (previous) {\n // inspect the whole remaining data upon empty chunk\n // empty chunk signalizes to restart of receiving\n index = chunk.length === 0 ? 0 : (previous as Uint8Array).length\n chunk = chunks.concat(previous, chunk)\n } else {\n index = 0\n }\n while (index < chunk.length) {\n const c = chunk[index]\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n // do not emmit more lines if the processing is already finished\n if (finished) {\n return\n }\n paused = target.next(chunks.toUtf8String(chunk, start, end)) === false\n start = index + 1\n if (paused) {\n break\n }\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < chunk.length) {\n previous = chunks.copy(chunk, start, chunk.length)\n } else {\n previous = undefined\n }\n if (paused) {\n if (target.useResume) {\n target.useResume(() => {\n paused = false\n bufferReceived(new Uint8Array(0))\n })\n return\n }\n retVal.error(new Error('Unable to pause, useResume is not configured!'))\n paused = false // consume remaining data\n }\n if (resumeChunks) {\n resumeChunks()\n resumeChunks = undefined\n }\n }\n\n const retVal: CommunicationObserver = {\n next(chunk: Uint8Array): boolean {\n if (!finished) {\n try {\n bufferReceived(chunk)\n return !paused\n } catch (e) {\n this.error(e as Error)\n }\n }\n return true\n },\n error(error: Error): void {\n if (!finished) {\n finished = true\n target.error(error)\n }\n },\n complete(): void {\n if (!finished) {\n if (previous) {\n target.next(chunks.toUtf8String(previous, 0, previous.length))\n }\n finished = true\n target.complete()\n }\n },\n }\n if (target.useCancellable) {\n retVal.useCancellable = (cancellable: Cancellable) => {\n target.useCancellable &&\n target.useCancellable({\n cancel(): void {\n cancellable.cancel()\n previous = undefined // do not emit more lines\n retVal.complete()\n },\n isCancelled(): boolean {\n return cancellable.isCancelled()\n },\n })\n }\n }\n if (target.useResume) {\n retVal.useResume = (x: () => void) => {\n resumeChunks = x\n }\n }\n\n return retVal\n}\n","import {ChunkCombiner, createTextDecoderCombiner} from './chunkCombiner'\n\n/**\n * ChunksToLinesIterable is a transformation that accepts\n * an iterable of Uint8Array instances and returns iterable of lines.\n * @param source - iterable of transport buffers\n * @param chunkCombiner - chunk combiner\n * @returns iterable of lines\n */\nexport async function* chunksToLinesIterable(\n source: AsyncIterable,\n chunkCombiner?: ChunkCombiner\n): AsyncIterableIterator {\n const chunks = chunkCombiner ?? createTextDecoderCombiner()\n let previous: Uint8Array | undefined\n let quoted = false\n\n for await (let chunk of source) {\n let index: number\n let start = 0\n if (previous) {\n index = previous.length\n chunk = chunks.concat(previous, chunk)\n } else {\n index = 0\n }\n while (index < chunk.length) {\n const c = chunk[index]\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n yield chunks.toUtf8String(chunk, start, end)\n start = index + 1\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < chunk.length) {\n previous = chunks.copy(chunk, start, chunk.length)\n } else {\n previous = undefined\n }\n }\n if (previous) {\n yield chunks.toUtf8String(previous, 0, previous.length)\n }\n}\n","/**\n * Optimized tokenizer of a single CSV line.\n */\nexport class LineSplitter {\n /** returned value when reused */\n reusedValues: string[]\n /** last length of elements in */\n lastSplitLength: number\n private _reuse = false\n\n /**\n * Reuse returned array between consecutive calls.\n */\n get reuse(): boolean {\n return this._reuse\n }\n set reuse(val: boolean) {\n if (val && !this.reusedValues) {\n this.reusedValues = new Array(10)\n }\n this._reuse = val\n }\n\n /**\n * Sets the reuse flag and returns this.\n */\n withReuse(): LineSplitter {\n this.reuse = true\n return this\n }\n\n /**\n * Splits the supplied line to elements that are separated by\n * comma with values possibly escaped within double quotes (\"value\")\n * @param line - line\n * @returns array of splitted parts\n */\n splitLine(line: string | undefined | null): string[] {\n if (line === null || line === undefined) {\n this.lastSplitLength = 0\n return []\n }\n let quoteCount = 0\n let startIndex = 0\n const values = this._reuse ? this.reusedValues : []\n let count = 0\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (c === ',') {\n if (quoteCount % 2 === 0) {\n const val = this.getValue(line, startIndex, i, quoteCount)\n if (this._reuse) {\n values[count++] = val\n } else {\n values.push(val)\n }\n startIndex = i + 1\n quoteCount = 0\n }\n } else if (c === '\"') {\n quoteCount++\n }\n }\n const val = this.getValue(line, startIndex, line.length, quoteCount)\n if (this._reuse) {\n values[count] = val\n this.lastSplitLength = count + 1\n } else {\n values.push(val)\n this.lastSplitLength = values.length\n }\n\n return values\n }\n\n private getValue(\n line: string,\n start: number,\n end: number,\n quoteCount: number\n ): string {\n if (start === line.length) {\n return ''\n } else if (quoteCount === 0) {\n return line.substring(start, end)\n } else if (quoteCount === 2) {\n return line.substring(start + 1, end - 1)\n } else {\n // quoteCount >= 4\n return line.substring(start + 1, end - 1).replace(/\"\"/gi, '\"')\n }\n }\n}\n","/**\n * Type of query result column, see {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport type ColumnType =\n | 'boolean'\n | 'unsignedLong'\n | 'long'\n | 'double'\n | 'string'\n | 'base64Binary'\n | 'dateTime:RFC3339'\n | 'duration'\n | string\n\n/**\n * FluxTableColumn describes {@link http://bit.ly/flux-spec#table | flux table} column.\n */\nexport interface FluxTableColumn {\n /**\n * Label (e.g., \"_start\", \"_stop\", \"_time\").\n */\n label: string\n\n /**\n * The data type of column (e.g., \"string\", \"long\", \"dateTime:RFC3339\").\n */\n dataType: ColumnType\n\n /**\n * Boolean flag indicating if the column is a part of the table's group key.\n */\n group: boolean\n\n /**\n * Default value to be used for rows whose string value is an empty string.\n */\n defaultValue: string\n\n /**\n * Index of this column in a row array.\n */\n index: number\n\n /**\n * Get returns a JavaScript object of this column in the supplied result row, using default deserializers.\n * @param row - a data row\n * @returns column value\n */\n get: (row: string[]) => any\n}\n\nconst identity = (x: string): any => x\n\n/**\n * A dictionary of serializers of particular types returned by a flux query.\n * See {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport const typeSerializers: Record any> = {\n boolean: (x: string): any => (x === '' ? null : x === 'true'),\n unsignedLong: (x: string): any => (x === '' ? null : +x),\n long: (x: string): any => (x === '' ? null : +x),\n double(x: string): any {\n switch (x) {\n case '':\n return null\n case '+Inf':\n return Number.POSITIVE_INFINITY\n case '-Inf':\n return Number.NEGATIVE_INFINITY\n default:\n return +x\n }\n },\n string: identity,\n base64Binary: identity,\n duration: (x: string): any => (x === '' ? null : x),\n 'dateTime:RFC3339': (x: string): any => (x === '' ? null : x),\n}\n\n/**\n * FluxTableColumn implementation.\n */\nclass FluxTableColumnImpl implements FluxTableColumn {\n label: string\n dataType: ColumnType\n group: boolean\n defaultValue: string\n index: number\n public get(row: string[]): any {\n let val = row[this.index]\n if ((val === '' || val === undefined) && this.defaultValue) {\n val = this.defaultValue\n }\n return (typeSerializers[this.dataType] ?? identity)(val)\n }\n}\nexport const UNKNOWN_COLUMN: FluxTableColumn = Object.freeze({\n label: '',\n dataType: '',\n group: false,\n defaultValue: '',\n index: Number.MAX_SAFE_INTEGER,\n get: () => undefined,\n})\n\n/**\n * Creates a new flux table column.\n * @returns column instance\n */\nexport function newFluxTableColumn(): FluxTableColumn {\n return new FluxTableColumnImpl()\n}\n\n/**\n * Creates a flux table column from a partial FluxTableColumn.\n * @param object - source object\n * @returns column instance\n */\nexport function createFluxTableColumn(\n object: Partial\n): FluxTableColumn {\n const retVal = new FluxTableColumnImpl()\n retVal.label = String(object.label)\n retVal.dataType = object.dataType as ColumnType\n retVal.group = Boolean(object.group)\n retVal.defaultValue = object.defaultValue ?? ''\n retVal.index = object.index ?? 0\n return retVal\n}\n","/**\n * Strategy for calculating retry delays.\n */\nexport interface RetryDelayStrategy {\n /**\n * Returns delay for a next retry\n * @param error - reason for retrying\n * @param failedAttempts - a count of already failed attempts, 1 being the first\n * @returns milliseconds to wait before retrying\n */\n nextDelay(error?: Error, failedAttempts?: number): number\n /** Implementation should reset its state, this is mandatory to call upon success. */\n success(): void\n}\n\n/**\n * Interface for errors to inform that an associated operation can be retried.\n */\nexport interface RetriableDecision {\n /**\n * Informs whether this can be retried.\n */\n canRetry(): boolean\n /**\n * Get the delay in milliseconds to retry the action.\n * @returns 0 to let the implementation decide, miliseconds delay otherwise\n */\n retryAfter(): number\n}\n\nconst retriableStatusCodes = [404, 408, 425, 429, 500, 502, 503, 504]\n/** isStatusCodeRetriable checks whether the supplied HTTP status code is retriable. */\nexport function isStatusCodeRetriable(statusCode: number): boolean {\n return retriableStatusCodes.includes(statusCode)\n}\n\n/** IllegalArgumentError is thrown when illegal argument is supplied. */\nexport class IllegalArgumentError extends Error {\n /* istanbul ignore next */\n constructor(message: string) {\n super(message)\n this.name = 'IllegalArgumentError'\n Object.setPrototypeOf(this, IllegalArgumentError.prototype)\n }\n}\n\n/**\n * A general HTTP error.\n */\nexport class HttpError extends Error implements RetriableDecision {\n private _retryAfter: number\n /** application error code, when available */\n public code: string | undefined\n /** json error response */\n public json: any\n\n /* istanbul ignore next because of super() not being covered*/\n constructor(\n readonly statusCode: number,\n readonly statusMessage: string | undefined,\n readonly body?: string,\n retryAfter?: string | undefined | null,\n readonly contentType?: string | undefined | null,\n message?: string\n ) {\n super()\n Object.setPrototypeOf(this, HttpError.prototype)\n if (message) {\n this.message = message\n } else if (body) {\n if (contentType?.startsWith('application/json')) {\n try {\n this.json = JSON.parse(body)\n this.message = this.json.message\n this.code = this.json.code\n } catch (e) {\n // silently ignore, body string is still available\n }\n }\n if (!this.message) {\n this.message = `${statusCode} ${statusMessage} : ${body}`\n }\n } else {\n this.message = `${statusCode} ${statusMessage}`\n }\n this.name = 'HttpError'\n this.setRetryAfter(retryAfter)\n }\n\n private setRetryAfter(retryAfter?: string | undefined | null): void {\n if (typeof retryAfter === 'string') {\n // try to parse the supplied number as milliseconds\n if (/^[0-9]+$/.test(retryAfter)) {\n this._retryAfter = parseInt(retryAfter)\n } else {\n this._retryAfter = 0\n }\n } else {\n this._retryAfter = 0\n }\n }\n\n canRetry(): boolean {\n return isStatusCodeRetriable(this.statusCode)\n }\n retryAfter(): number {\n return this._retryAfter\n }\n}\n\n//see https://nodejs.org/api/errors.html\nconst RETRY_CODES = [\n 'ECONNRESET',\n 'ENOTFOUND',\n 'ESOCKETTIMEDOUT',\n 'ETIMEDOUT',\n 'ECONNREFUSED',\n 'EHOSTUNREACH',\n 'EPIPE',\n]\n\n/**\n * Tests the error in order to know if an HTTP call can be retried.\n * @param error - error to test\n * @returns true for a retriable error\n */\nexport function canRetryHttpCall(error: any): boolean {\n if (!error) {\n return false\n } else if (typeof (error as any).canRetry === 'function') {\n return !!((error as any).canRetry as () => boolean)()\n } else if ((error as any).code && RETRY_CODES.includes((error as any).code)) {\n return true\n }\n return false\n}\n\n/**\n * Gets retry delay from the supplied error, possibly using random number up to retryJitter.\n */\nexport function getRetryDelay(error?: Error, retryJitter?: number): number {\n if (!error) {\n return 0\n } else {\n let retVal\n if (typeof (error as any).retryAfter === 'function') {\n return ((error as any).retryAfter as () => number)()\n } else {\n retVal = 0\n }\n if (retryJitter && retryJitter > 0) {\n return retVal + Math.round(Math.random() * retryJitter)\n } else {\n return retVal\n }\n }\n}\n\n/** RequestTimedOutError indicates request timeout in the communication with the server */\nexport class RequestTimedOutError extends Error implements RetriableDecision {\n /* istanbul ignore next because of super() not being covered */\n constructor() {\n super()\n Object.setPrototypeOf(this, RequestTimedOutError.prototype)\n this.name = 'RequestTimedOutError'\n this.message = 'Request timed out'\n }\n canRetry(): boolean {\n return true\n }\n retryAfter(): number {\n return 0\n }\n}\n\n/** AbortError indicates that the communication with the server was aborted */\nexport class AbortError extends Error implements RetriableDecision {\n /* istanbul ignore next because of super() not being covered */\n constructor() {\n super()\n this.name = 'AbortError'\n Object.setPrototypeOf(this, AbortError.prototype)\n this.message = 'Response aborted'\n }\n canRetry(): boolean {\n return true\n }\n retryAfter(): number {\n return 0\n }\n}\n","import {\n FluxTableColumn,\n UNKNOWN_COLUMN,\n typeSerializers,\n} from './FluxTableColumn'\nimport {IllegalArgumentError} from '../errors'\n\n/**\n * serializeDateTimeAsDate changes type serializers to return JavaScript Date instances\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsDate(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : new Date(Date.parse(x))\n}\n/**\n * serializeDateTimeAsNumber changes type serializers to return milliseconds since epoch\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsNumber(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : Date.parse(x)\n}\n/**\n * serializeDateTimeAsString changes type serializers to return string values\n * for `dateTime:RFC3339` query result data type. Empty value is converted to null.\n */\nexport function serializeDateTimeAsString(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : x\n}\n\n/**\n * Represents metadata of a {@link http://bit.ly/flux-spec#table | flux table}.\n */\nexport interface FluxTableMetaData {\n /**\n * Table columns.\n */\n columns: Array\n\n /**\n * Gets columns by name\n * @param label - column label\n * @param errorOnMissingColumn - throw error on missing column (by default), return UNKNOWN_COLUMN when false\n * @returns table column\n * @throws IllegalArgumentError if column is not found\n **/\n column(label: string, errorOnMissingColumn?: boolean): FluxTableColumn\n\n /**\n * Creates an object out of the supplied row with the help of column descriptors.\n * @param row - a row with data for each column\n */\n toObject(row: string[]): {[key: string]: any}\n\n /**\n * Gets column values out of the supplied row.\n * @param row - a row with data for each column\n * @param column - column name\n * @returns column value, undefined for unknown column\n */\n get(row: string[], column: string): any\n}\n\n/**\n * FluxTableMetaData Implementation.\n */\nclass FluxTableMetaDataImpl implements FluxTableMetaData {\n columns: Array\n constructor(columns: FluxTableColumn[]) {\n columns.forEach((col, i) => (col.index = i))\n this.columns = columns\n }\n column(label: string, errorOnMissingColumn = true): FluxTableColumn {\n for (let i = 0; i < this.columns.length; i++) {\n const col = this.columns[i]\n if (col.label === label) return col\n }\n if (errorOnMissingColumn) {\n throw new IllegalArgumentError(`Column ${label} not found!`)\n }\n return UNKNOWN_COLUMN\n }\n toObject(row: string[]): {[key: string]: any} {\n const acc: any = {}\n for (let i = 0; i < this.columns.length && i < row.length; i++) {\n const column = this.columns[i]\n acc[column.label] = column.get(row)\n }\n return acc\n }\n get(row: string[], column: string): any {\n return this.column(column, false).get(row)\n }\n}\n\n/**\n * Created FluxTableMetaData from the columns supplied.\n * @param columns - columns\n * @returns - instance\n */\nexport function createFluxTableMetaData(\n columns: FluxTableColumn[]\n): FluxTableMetaData {\n return new FluxTableMetaDataImpl(columns)\n}\n\n/** Wraps values and associated metadata of a query result row */\nexport interface Row {\n values: string[]\n tableMeta: FluxTableMetaData\n}\n","import {CommunicationObserver} from './CommunicationObserver'\nimport {LineSplitter} from './LineSplitter'\nimport {FluxResultObserver} from './FluxResultObserver'\nimport {\n FluxTableColumn,\n ColumnType,\n newFluxTableColumn,\n} from './FluxTableColumn'\nimport {FluxTableMetaData, createFluxTableMetaData} from './FluxTableMetaData'\n\n/**\n * LinesToTables creates a transformation that accepts (flux) annotated CSV lines\n * and emits rows together with table metadata.\n */\nexport function linesToTables(\n consumer: FluxResultObserver\n): CommunicationObserver {\n const splitter = new LineSplitter().withReuse()\n let columns: FluxTableColumn[] | undefined\n let expectMeta = true\n let firstColumnIndex = 0\n let lastMeta: FluxTableMetaData\n const retVal: CommunicationObserver = {\n error(error: Error): void {\n consumer.error(error)\n },\n next(line: string): void | boolean {\n if (line === '') {\n expectMeta = true\n columns = undefined\n } else {\n const values = splitter.splitLine(line)\n const size = splitter.lastSplitLength\n if (expectMeta) {\n // create columns\n if (!columns) {\n columns = new Array(size)\n for (let i = 0; i < size; i++) {\n columns[i] = newFluxTableColumn()\n }\n }\n if (!values[0].startsWith('#')) {\n // fill in column names\n if (values[0] === '') {\n firstColumnIndex = 1\n columns = columns.slice(1)\n } else {\n firstColumnIndex = 0\n }\n for (let i = firstColumnIndex; i < size; i++) {\n columns[i - firstColumnIndex].label = values[i]\n }\n lastMeta = createFluxTableMetaData(columns)\n expectMeta = false\n } else if (values[0] === '#datatype') {\n for (let i = 1; i < size; i++) {\n columns[i].dataType = values[i] as ColumnType\n }\n } else if (values[0] === '#default') {\n for (let i = 1; i < size; i++) {\n columns[i].defaultValue = values[i]\n }\n } else if (values[0] === '#group') {\n for (let i = 1; i < size; i++) {\n columns[i].group = values[i][0] === 't'\n }\n }\n } else {\n return consumer.next(values.slice(firstColumnIndex, size), lastMeta)\n }\n }\n return true\n },\n complete(): void {\n consumer.complete()\n },\n }\n if (consumer.useCancellable) {\n retVal.useCancellable = consumer.useCancellable.bind(consumer)\n }\n if (consumer.useResume) {\n retVal.useResume = consumer.useResume.bind(consumer)\n }\n return retVal\n}\n","import {LineSplitter} from './LineSplitter'\nimport {\n FluxTableColumn,\n ColumnType,\n newFluxTableColumn,\n} from './FluxTableColumn'\nimport {\n FluxTableMetaData,\n createFluxTableMetaData,\n Row,\n} from './FluxTableMetaData'\n\n/**\n * LinesToRowsIterable is a transformation that accepts\n * an iterable of flux annotated CSV lines and returns\n * an iterable of rows (row values and table metadata).\n */\nexport async function* linesToRowsIterable(\n source: AsyncIterable\n): AsyncIterableIterator {\n const splitter = new LineSplitter().withReuse()\n let columns: FluxTableColumn[] | undefined\n let expectMeta = true\n let firstColumnIndex = 0\n let lastMeta: FluxTableMetaData | undefined = undefined\n for await (const line of source) {\n if (line === '') {\n expectMeta = true\n columns = undefined\n } else {\n const values = splitter.splitLine(line)\n const size = splitter.lastSplitLength\n if (expectMeta) {\n // create columns\n if (!columns) {\n columns = new Array(size)\n for (let i = 0; i < size; i++) {\n columns[i] = newFluxTableColumn()\n }\n }\n if (!values[0].startsWith('#')) {\n // fill in column names\n if (values[0] === '') {\n firstColumnIndex = 1\n columns = columns.slice(1)\n } else {\n firstColumnIndex = 0\n }\n for (let i = firstColumnIndex; i < size; i++) {\n columns[i - firstColumnIndex].label = values[i]\n }\n lastMeta = createFluxTableMetaData(columns)\n expectMeta = false\n } else if (values[0] === '#datatype') {\n for (let i = 1; i < size; i++) {\n columns[i].dataType = values[i] as ColumnType\n }\n } else if (values[0] === '#default') {\n for (let i = 1; i < size; i++) {\n columns[i].defaultValue = values[i]\n }\n } else if (values[0] === '#group') {\n for (let i = 1; i < size; i++) {\n columns[i].group = values[i][0] === 't'\n }\n }\n } else {\n yield {\n values: values.slice(firstColumnIndex, size),\n tableMeta:\n lastMeta as unknown as FluxTableMetaData /* never undefined */,\n }\n }\n }\n }\n}\n","import {CommunicationObserver} from './CommunicationObserver'\n\n/**\n * StringToLines is a transformation that emmits strings for each CSV\n * line in the supplied source string.\n * @param source - source string\n * @param target - target to emmit CSV lines to\n * @returns communication obrver to accept Uint8Arrays\n */\nexport function stringToLines(\n source: string,\n target: CommunicationObserver\n): void {\n let quoted = false\n let start = 0\n let index = 0\n\n while (index < source.length) {\n const c = source.charCodeAt(index)\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end =\n index > 0 && source.charCodeAt(index - 1) === 13 ? index - 1 : index\n // do not emmit more lines if the processing is already finished\n target.next(source.substring(start, end))\n start = index + 1\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < index) {\n target.next(source.substring(start, index))\n }\n target.complete()\n}\n","/* Observable interop typing. Taken from https://github.com/ReactiveX/rxjs */\n\n/* Note: This will add Symbol.observable globally for all TypeScript users */\ndeclare global {\n interface SymbolConstructor {\n readonly observable: symbol\n }\n}\n\n/** Symbol.observable or a string \"\\@\\@observable\". Used for interop */\nexport const symbolObservable = (():\n | typeof Symbol.observable\n | '@@observable' =>\n (typeof Symbol === 'function' && Symbol.observable) || '@@observable')()\n","import {\n Observable,\n Observer,\n ObserverComplete,\n ObserverError,\n ObserverNext,\n Subscription,\n symbolObservable,\n} from '../observable'\nimport {CommunicationObserver} from '../results/CommunicationObserver'\nimport {Cancellable} from '../results/Cancellable'\n\n/** APIExecutor executes the API and passes its response to the supplied consumer */\nexport type APIExecutor = (consumer: CommunicationObserver) => void\n\ntype Decorator = (observer: Observer) => Observer\n\nclass QuerySubscription implements Subscription {\n private cancellable?: Cancellable\n private isClosed = false\n\n public constructor(observer: Observer, executor: APIExecutor) {\n try {\n executor({\n next: (value) => {\n observer.next(value)\n },\n error: (e) => {\n this.isClosed = true\n observer.error(e)\n },\n complete: () => {\n this.isClosed = true\n observer.complete()\n },\n useCancellable: (c) => {\n this.cancellable = c\n },\n })\n } catch (e) {\n this.isClosed = true\n observer.error(e)\n }\n }\n\n public get closed(): boolean {\n return this.isClosed\n }\n\n public unsubscribe(): void {\n this.cancellable?.cancel()\n this.isClosed = true\n }\n}\n\nfunction noop(): void {}\n\nfunction completeObserver(observer: Partial>): Observer {\n const {next, error, complete} = observer\n\n return {\n next: next ? next.bind(observer) : noop,\n error: error ? error.bind(observer) : noop,\n complete: complete ? complete.bind(observer) : noop,\n }\n}\n\nexport default class ObservableQuery implements Observable {\n public constructor(\n private readonly executor: APIExecutor,\n private readonly decorator: Decorator\n ) {}\n\n public subscribe(\n observerOrNext?: Partial> | ObserverNext,\n error?: ObserverError,\n complete?: ObserverComplete\n ): Subscription {\n const observer = completeObserver(\n typeof observerOrNext !== 'object' || observerOrNext === null\n ? {next: observerOrNext, error, complete}\n : observerOrNext\n )\n\n return new QuerySubscription(this.decorator(observer), this.executor)\n }\n\n public [symbolObservable](): this {\n return this\n }\n\n // this makes sure we satisfy the interface, while using a possibly polyfilled\n // [symbolObservable] above for the actual implementation\n public declare [Symbol.observable]: () => this\n}\n","import {Transport} from './transport'\nimport WriteApi from './WriteApi'\n\n/**\n * Option for the communication with InfluxDB server.\n */\nexport interface ConnectionOptions {\n /** base URL */\n url: string\n /** authentication token */\n token?: string\n /**\n * socket timeout, 10000 milliseconds by default in node.js\n * @defaultValue 10000\n */\n timeout?: number\n /**\n * TransportOptions supply extra options for the transport layer, they differ between node.js and browser/deno.\n * Node.js transport accepts options specified in {@link https://nodejs.org/api/http.html#http_http_request_options_callback | http.request } or\n * {@link https://nodejs.org/api/https.html#https_https_request_options_callback | https.request }. For example, an `agent` property can be set to\n * {@link https://www.npmjs.com/package/proxy-http-agent | setup HTTP/HTTPS proxy }, {@link https://nodejs.org/api/tls.html#tls_tls_connect_options_callback | rejectUnauthorized }\n * property can disable TLS server certificate verification. Additionally,\n * {@link https://github.com/follow-redirects/follow-redirects | follow-redirects } property can be also specified\n * in order to follow redirects in node.js.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | fetch } is used under the hood in browser/deno.\n * For example,\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | redirect } property can be set to 'error' to abort request if a redirect occurs.\n */\n transportOptions?: {[key: string]: any}\n /**\n * Default HTTP headers to send with every request.\n */\n headers?: Record\n /**\n * Full HTTP web proxy URL including schema, for example http://your-proxy:8080.\n */\n proxyUrl?: string\n}\n\n/** default connection options */\nexport const DEFAULT_ConnectionOptions: Partial = {\n timeout: 10000,\n}\n\n/**\n * Options that configure strategy for retrying failed requests.\n */\nexport interface RetryDelayStrategyOptions {\n /** add `random(retryJitter)` milliseconds delay when retrying HTTP calls */\n retryJitter: number\n /** minimum delay when retrying write (milliseconds) */\n minRetryDelay: number\n /** maximum delay when retrying write (milliseconds) */\n maxRetryDelay: number\n /** base for the exponential retry delay */\n exponentialBase: number\n /**\n * randomRetry indicates whether the next retry delay is deterministic (false) or random (true).\n * The deterministic delay starts with `minRetryDelay * exponentialBase` and it is multiplied\n * by `exponentialBase` until it exceeds `maxRetryDelay`.\n * When random is `true`, the next delay is computed as a random number between next retry attempt (upper)\n * and the lower number in the deterministic sequence. `random(retryJitter)` is added to every returned value.\n */\n randomRetry: boolean\n}\n\n/**\n * Options that configure strategy for retrying failed InfluxDB write operations.\n */\nexport interface WriteRetryOptions extends RetryDelayStrategyOptions {\n /**\n * WriteFailed is called to inform about write errors.\n * @param this - the instance of the API that failed\n * @param error - write error\n * @param lines - failed lines\n * @param attempt - count of already failed attempts to write the lines (1 ... maxRetries+1)\n * @param expires - expiration time for the lines to be retried in millis since epoch\n * @returns a Promise to force the API to use it as a result of the flush operation,\n * void/undefined to continue with default retry mechanism\n */\n writeFailed(\n this: WriteApi,\n error: Error,\n lines: Array,\n attempt: number,\n expires: number\n ): Promise | void\n\n /**\n * WriteSuccess is informed about successfully written lines.\n * @param this - the instance of the API in use\n * @param lines - written lines\n */\n writeSuccess(this: WriteApi, lines: Array): void\n\n /**\n * WriteRetrySkipped is informed about lines that were removed from the retry buffer\n * to keep the size of the retry buffer under the configured limit (maxBufferLines).\n * @param entry - lines that were skipped\n */\n writeRetrySkipped(entry: {lines: Array; expires: number}): void\n\n /** max count of retries after the first write fails */\n maxRetries: number\n /** max time (millis) that can be spent with retries */\n maxRetryTime: number\n /** the maximum size of retry-buffer (in lines) */\n maxBufferLines: number\n}\n\n/**\n * Options used by {@link WriteApi} .\n */\nexport interface WriteOptions extends WriteRetryOptions {\n /** max number of records/lines to send in a batch */\n batchSize: number\n /** delay between data flushes in milliseconds, at most `batch size` records are sent during flush */\n flushInterval: number\n /** default tags, unescaped */\n defaultTags?: Record\n /** HTTP headers that will be sent with every write request */\n headers?: {[key: string]: string}\n /** When specified, write bodies larger than the threshold are gzipped */\n gzipThreshold?: number\n /** max size of a batch in bytes */\n maxBatchBytes: number\n /** InfluxDB Enterprise write consistency as explained in https://docs.influxdata.com/enterprise_influxdb/v1.9/concepts/clustering/#write-consistency */\n consistency?: 'any' | 'one' | 'quorum' | 'all'\n}\n\n/** default RetryDelayStrategyOptions */\nexport const DEFAULT_RetryDelayStrategyOptions = {\n retryJitter: 200,\n minRetryDelay: 5000,\n maxRetryDelay: 125000,\n exponentialBase: 5,\n randomRetry: true,\n}\n\n/** default writeOptions */\nexport const DEFAULT_WriteOptions: WriteOptions = {\n batchSize: 1000,\n maxBatchBytes: 50_000_000, // default max batch size in the cloud\n flushInterval: 60000,\n writeFailed: function () {},\n writeSuccess: function () {},\n writeRetrySkipped: function () {},\n maxRetries: 5,\n maxRetryTime: 180_000,\n maxBufferLines: 32_000,\n // a copy of DEFAULT_RetryDelayStrategyOptions, so that DEFAULT_WriteOptions could be tree-shaken\n retryJitter: 200,\n minRetryDelay: 5000,\n maxRetryDelay: 125000,\n exponentialBase: 2,\n gzipThreshold: 1000,\n randomRetry: true,\n}\n\n/**\n * Options used by {@link InfluxDB} .\n */\nexport interface ClientOptions extends ConnectionOptions {\n /** supplies and overrides default writing options */\n writeOptions?: Partial\n /** specifies custom transport */\n transport?: Transport\n}\n\n/**\n * Timestamp precision used in write operations.\n * See {@link https://docs.influxdata.com/influxdb/latest/api/#operation/PostWrite }\n */\nexport type WritePrecisionType = 'ns' | 'us' | 'ms' | 's'\n","function createEscaper(\n characters: string,\n replacements: string[]\n): (value: string) => string {\n return function (value: string): string {\n let retVal = ''\n let from = 0\n let i = 0\n while (i < value.length) {\n const found = characters.indexOf(value[i])\n if (found >= 0) {\n retVal += value.substring(from, i)\n retVal += replacements[found]\n from = i + 1\n }\n i++\n }\n if (from == 0) {\n return value\n } else if (from < value.length) {\n retVal += value.substring(from, value.length)\n }\n return retVal\n }\n}\nfunction createQuotedEscaper(\n characters: string,\n replacements: string[]\n): (value: string) => string {\n const escaper = createEscaper(characters, replacements)\n return (value: string): string => '\"' + escaper(value) + '\"'\n}\n\n/**\n * Provides functions escape specific parts in InfluxDB line protocol.\n */\nexport const escape = {\n /**\n * Measurement escapes measurement names.\n */\n measurement: createEscaper(', \\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\n', '\\\\r', '\\\\t']),\n /**\n * Quoted escapes quoted values, such as database names.\n */\n quoted: createQuotedEscaper('\"\\\\', ['\\\\\"', '\\\\\\\\']),\n\n /**\n * TagEscaper escapes tag keys, tag values, and field keys.\n */\n tag: createEscaper(', =\\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\=', '\\\\n', '\\\\r', '\\\\t']),\n}\n","declare let process: any\nconst zeroPadding = '000000000'\nlet useHrTime = false\n\nexport function useProcessHrtime(use: boolean): boolean {\n /* istanbul ignore else */\n if (!process.env.BUILD_BROWSER) {\n return (useHrTime = use && process && typeof process.hrtime === 'function')\n } else {\n return false\n }\n}\nuseProcessHrtime(true) // preffer node\n\nlet startHrMillis: number | undefined = undefined\nlet startHrTime: [number, number] | undefined = undefined\nlet lastMillis = Date.now()\nlet stepsInMillis = 0\nfunction nanos(): string {\n if (!process.env.BUILD_BROWSER && useHrTime) {\n const hrTime = process.hrtime() as [number, number]\n let millis = Date.now()\n if (!startHrTime) {\n startHrTime = hrTime\n startHrMillis = millis\n } else {\n hrTime[0] = hrTime[0] - startHrTime[0]\n hrTime[1] = hrTime[1] - startHrTime[1]\n // istanbul ignore next \"cannot mock system clock, manually reviewed\"\n if (hrTime[1] < 0) {\n hrTime[0] -= 1\n hrTime[1] += 1000_000_000\n }\n millis =\n (startHrMillis as number) +\n hrTime[0] * 1000 +\n Math.floor(hrTime[1] / 1000_000)\n }\n const nanos = String(hrTime[1] % 1000_000)\n return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n } else {\n const millis = Date.now()\n if (millis !== lastMillis) {\n lastMillis = millis\n stepsInMillis = 0\n } else {\n stepsInMillis++\n }\n const nanos = String(stepsInMillis)\n return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n }\n}\n\nfunction micros(): string {\n if (!process.env.BUILD_BROWSER && useHrTime) {\n const hrTime = process.hrtime() as [number, number]\n const micros = String(Math.trunc(hrTime[1] / 1000) % 1000)\n return (\n String(Date.now()) + zeroPadding.substr(0, 3 - micros.length) + micros\n )\n } else {\n return String(Date.now()) + zeroPadding.substr(0, 3)\n }\n}\nfunction millis(): string {\n return String(Date.now())\n}\nfunction seconds(): string {\n return String(Math.floor(Date.now() / 1000))\n}\n\n/**\n * Exposes functions that creates strings that represent a timestamp that\n * can be used in the line protocol. Micro and nano timestamps are emulated\n * depending on the js platform in use.\n */\nexport const currentTime = {\n s: seconds as () => string,\n ms: millis as () => string,\n us: micros as () => string,\n ns: nanos as () => string,\n seconds: seconds as () => string,\n millis: millis as () => string,\n micros: micros as () => string,\n nanos: nanos as () => string,\n}\n\n/**\n * dateToProtocolTimestamp provides converters for JavaScript Date to InfluxDB Write Protocol Timestamp. Keys are supported precisions.\n */\nexport const dateToProtocolTimestamp = {\n s: (d: Date): string => `${Math.floor(d.getTime() / 1000)}`,\n ms: (d: Date): string => `${d.getTime()}`,\n us: (d: Date): string => `${d.getTime()}000`,\n ns: (d: Date): string => `${d.getTime()}000000`,\n}\n\n/**\n * convertTimeToNanos converts Point's timestamp to a string.\n * @param value - supported timestamp value\n * @returns line protocol value\n */\nexport function convertTimeToNanos(\n value: string | number | Date | undefined\n): string | undefined {\n if (value === undefined) {\n return nanos()\n } else if (typeof value === 'string') {\n return value.length > 0 ? value : undefined\n } else if (value instanceof Date) {\n return `${value.getTime()}000000`\n } else if (typeof value === 'number') {\n return String(Math.floor(value))\n } else {\n return String(value)\n }\n}\n","/**\n * Logging interface.\n */\nexport interface Logger {\n error(message: string, err?: any): void\n warn(message: string, err?: any): void\n}\n\n/**\n * Logger that logs to console.out\n */\nexport const consoleLogger: Logger = {\n error(message, error) {\n // eslint-disable-next-line no-console\n console.error('ERROR: ' + message, error ? error : '')\n },\n warn(message, error) {\n // eslint-disable-next-line no-console\n console.warn('WARN: ' + message, error ? error : '')\n },\n}\nlet provider: Logger = consoleLogger\n\nexport const Log: Logger = {\n error(message, error) {\n provider.error(message, error)\n },\n warn(message, error) {\n provider.warn(message, error)\n },\n}\n\n/**\n * Sets custom logger.\n * @param logger - logger to use\n * @returns previous logger\n */\nexport function setLogger(logger: Logger): Logger {\n const previous = provider\n provider = logger\n return previous\n}\n","/** Property that offers a function that returns flux-sanitized value of an object. */\nexport const FLUX_VALUE = Symbol('FLUX_VALUE')\n\n/**\n * A flux parameter can print its (sanitized) flux value.\n */\nexport interface FluxParameterLike {\n [FLUX_VALUE](): string\n}\n\n/**\n * Represents a parameterized query.\n */\nexport interface ParameterizedQuery {\n /**\n * Returns flux query with sanitized parameters.\n */\n toString(): string\n}\n\nclass FluxParameter implements FluxParameterLike, ParameterizedQuery {\n constructor(private fluxValue: string) {}\n toString(): string {\n return this.fluxValue\n }\n [FLUX_VALUE](): string {\n return this.fluxValue\n }\n}\n\n/**\n * Checks if the supplied object is FluxParameterLike\n * @param value - any value\n * @returns true if it is\n */\nfunction isFluxParameterLike(value: any): boolean {\n return typeof value === 'object' && typeof value[FLUX_VALUE] === 'function'\n}\n\n/**\n * Escapes content of the supplied string so it can be wrapped into double qoutes\n * to become a [flux string literal](https://docs.influxdata.com/flux/latest/spec/lexical-elements/#string-literals).\n * @param value - string value\n * @returns sanitized string\n */\nfunction sanitizeString(value: any): string {\n if (value === null || value === undefined) return ''\n value = value.toString()\n let retVal: any = undefined\n let i = 0\n function prepareRetVal(): void {\n if (retVal === undefined) {\n retVal = value.substring(0, i)\n }\n }\n for (; i < value.length; i++) {\n const c = value.charAt(i)\n switch (c) {\n case '\\r':\n prepareRetVal()\n retVal += '\\\\r'\n break\n case '\\n':\n prepareRetVal()\n retVal += '\\\\n'\n break\n case '\\t':\n prepareRetVal()\n retVal += '\\\\t'\n break\n case '\"':\n case '\\\\':\n prepareRetVal()\n retVal = retVal + '\\\\' + c\n break\n case '$':\n // escape ${\n if (i + 1 < value.length && value.charAt(i + 1) === '{') {\n prepareRetVal()\n i++\n retVal += '\\\\${'\n break\n }\n // append $\n if (retVal != undefined) {\n retVal += c\n }\n break\n default:\n if (retVal != undefined) {\n retVal += c\n }\n }\n }\n if (retVal !== undefined) {\n return retVal\n }\n return value\n}\n\n/**\n * Creates a flux string literal.\n */\nexport function fluxString(value: any): FluxParameterLike {\n return new FluxParameter(`\"${sanitizeString(value)}\"`)\n}\n\n/**\n * Sanitizes float value to avoid injections.\n * @param value - InfluxDB float literal\n * @returns sanitized float value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeFloat(value: any): string {\n const val = Number(value)\n if (!isFinite(val)) {\n if (typeof value === 'number') {\n return `float(v: \"${val}\")`\n }\n throw new Error(`not a flux float: ${value}`)\n }\n // try to return a flux float literal if possible\n // https://docs.influxdata.com/flux/latest/data-types/basic/float/#float-syntax\n const strVal = val.toString()\n let hasDot = false\n for (const c of strVal) {\n if ((c >= '0' && c <= '9') || c == '-') continue\n if (c === '.') {\n hasDot = true\n continue\n }\n return `float(v: \"${strVal}\")`\n }\n return hasDot ? strVal : strVal + '.0'\n}\n/**\n * Creates a flux float literal.\n */\nexport function fluxFloat(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeFloat(value))\n}\n\n/**\n * Sanitizes integer value to avoid injections.\n * @param value - InfluxDB integer literal\n * @returns sanitized integer value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeInteger(value: any): string {\n // https://docs.influxdata.com/flux/latest/data-types/basic/int/\n // Min value: -9223372036854775808\n // Max value: 9223372036854775807\n // \"9223372036854775807\".length === 19\n const strVal = String(value)\n const negative = strVal.startsWith('-')\n const val = negative ? strVal.substring(1) : strVal\n if (val.length === 0 || val.length > 19) {\n throw new Error(`not a flux integer: ${strVal}`)\n }\n for (const c of val) {\n if (c < '0' || c > '9') throw new Error(`not a flux integer: ${strVal}`)\n }\n if (val.length === 19) {\n if (negative && val > '9223372036854775808') {\n throw new Error(`flux integer out of bounds: ${strVal}`)\n }\n if (!negative && val > '9223372036854775807') {\n throw new Error(`flux integer out of bounds: ${strVal}`)\n }\n }\n return strVal\n}\n\n/**\n * Creates a flux integer literal.\n */\nexport function fluxInteger(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeInteger(value))\n}\n\nfunction sanitizeDateTime(value: any): string {\n return `time(v: \"${sanitizeString(value)}\")`\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDateTime(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeDateTime(value))\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDuration(value: any): FluxParameterLike {\n return new FluxParameter(`duration(v: \"${sanitizeString(value)}\")`)\n}\n\nfunction sanitizeRegExp(value: any): string {\n if (value instanceof RegExp) {\n return value.toString()\n }\n return new RegExp(value).toString()\n}\n\n/**\n * Creates flux regexp literal out of a regular expression. See\n * https://docs.influxdata.com/flux/latest/data-types/basic/regexp/#regular-expression-syntax\n * for details.\n */\nexport function fluxRegExp(value: any): FluxParameterLike {\n // let the server decide if a regexp can be parsed\n return new FluxParameter(sanitizeRegExp(value))\n}\n\n/**\n * Creates flux boolean literal.\n */\nexport function fluxBool(value: any): FluxParameterLike {\n if (value === 'true' || value === 'false') {\n return new FluxParameter(value)\n }\n return new FluxParameter((!!value).toString())\n}\n\n/**\n * Assumes that the supplied value is flux expression or literal that does not need sanitizing.\n *\n * @param value - any value\n * @returns the supplied value as-is\n */\nexport function fluxExpression(value: any): FluxParameterLike {\n return new FluxParameter(String(value))\n}\n\n/**\n * Escapes content of the supplied parameter so that it can be safely embedded into flux query.\n * @param value - parameter value\n * @returns sanitized flux value or an empty string if it cannot be converted\n */\nexport function toFluxValue(value: any): string {\n if (value === undefined) {\n return ''\n } else if (value === null) {\n return 'null'\n } else if (typeof value === 'boolean') {\n return value.toString()\n } else if (typeof value === 'string') {\n return `\"${sanitizeString(value)}\"`\n } else if (typeof value === 'number') {\n if (Number.isSafeInteger(value)) {\n return sanitizeInteger(value)\n }\n return sanitizeFloat(value)\n } else if (typeof value === 'object') {\n if (typeof value[FLUX_VALUE] === 'function') {\n return value[FLUX_VALUE]()\n } else if (value instanceof Date) {\n return value.toISOString()\n } else if (value instanceof RegExp) {\n return sanitizeRegExp(value)\n } else if (Array.isArray(value)) {\n return `[${value.map(toFluxValue).join(',')}]`\n }\n } else if (typeof value === 'bigint') {\n return `${value}.0`\n }\n // use toString value for unrecognized object, symbol\n return toFluxValue(value.toString())\n}\n\n/**\n * Flux is a tagged template that sanitizes supplied parameters\n * to avoid injection attacks in flux.\n */\nexport function flux(\n strings: TemplateStringsArray,\n ...values: any\n): ParameterizedQuery {\n if (strings.length == 1 && values.length === 0) {\n return fluxExpression(strings[0]) // the simplest case\n }\n const parts = new Array(strings.length + values.length)\n let partIndex = 0\n for (let i = 0; i < strings.length; i++) {\n const text = strings[i]\n parts[partIndex++] = text\n if (i < values.length) {\n const val = values[i]\n let sanitized: string\n if (\n text.endsWith('\"') &&\n i + 1 < strings.length &&\n strings[i + 1].startsWith('\"')\n ) {\n // parameter is wrapped into flux double quotes\n sanitized = sanitizeString(val)\n } else {\n sanitized = toFluxValue(val)\n if (sanitized === '') {\n // do not allow to insert empty strings, unless it is FluxParameterLike\n if (!isFluxParameterLike(val)) {\n throw new Error(\n `Unsupported parameter literal '${val}' at index: ${i}, type: ${typeof val}`\n )\n }\n }\n }\n parts[partIndex++] = sanitized\n } else if (i < strings.length - 1) {\n throw new Error('Too few parameters supplied!')\n }\n }\n // return flux expression so that flux can be embedded into another flux as-is\n return fluxExpression(parts.join(''))\n}\n","import {convertTimeToNanos} from './util/currentTime'\nimport {escape} from './util/escape'\n\n/**\n * Settings that control the way of how a {@link Point} is serialized\n * to a protocol line.\n */\nexport interface PointSettings {\n /** default tags to add to every point */\n defaultTags?: {[key: string]: string}\n /** convertTime serializes Point's timestamp to a line protocol value */\n convertTime?: (\n value: string | number | Date | undefined\n ) => string | undefined\n}\n\n/**\n * Point defines values of a single measurement.\n */\nexport class Point {\n private name: string\n private tags: {[key: string]: string} = {}\n /** escaped field values */\n public fields: {[key: string]: string} = {}\n private time: string | number | Date | undefined\n\n /**\n * Create a new Point with specified a measurement name.\n *\n * @param measurementName - the measurement name\n */\n constructor(measurementName?: string) {\n if (measurementName) this.name = measurementName\n }\n\n /**\n * Sets point's measurement.\n *\n * @param name - measurement name\n * @returns this\n */\n public measurement(name: string): Point {\n this.name = name\n return this\n }\n\n /**\n * Adds a tag. The caller has to ensure that both name and value are not empty\n * and do not end with backslash.\n *\n * @param name - tag name\n * @param value - tag value\n * @returns this\n */\n public tag(name: string, value: string): Point {\n this.tags[name] = value\n return this\n }\n\n /**\n * Adds a boolean field.\n *\n * @param field - field name\n * @param value - field value\n * @returns this\n */\n public booleanField(name: string, value: boolean | any): Point {\n this.fields[name] = value ? 'T' : 'F'\n return this\n }\n\n /**\n * Adds an integer field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN or out of int64 range value is supplied\n */\n public intField(name: string, value: number | any): Point {\n let val: number\n if (typeof value === 'number') {\n val = value\n } else {\n val = parseInt(String(value))\n }\n if (isNaN(val) || val <= -9223372036854776e3 || val >= 9223372036854776e3) {\n throw new Error(`invalid integer value for field '${name}': '${value}'!`)\n }\n this.fields[name] = `${Math.floor(val)}i`\n return this\n }\n\n /**\n * Adds an unsigned integer field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN out of range value is supplied\n */\n public uintField(name: string, value: number | any): Point {\n if (typeof value === 'number') {\n if (isNaN(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {\n throw new Error(`uint value for field '${name}' out of range: ${value}`)\n }\n this.fields[name] = `${Math.floor(value as number)}u`\n } else {\n const strVal = String(value)\n for (let i = 0; i < strVal.length; i++) {\n const code = strVal.charCodeAt(i)\n if (code < 48 || code > 57) {\n throw new Error(\n `uint value has an unsupported character at pos ${i}: ${value}`\n )\n }\n }\n if (\n strVal.length > 20 ||\n (strVal.length === 20 &&\n strVal.localeCompare('18446744073709551615') > 0)\n ) {\n throw new Error(\n `uint value for field '${name}' out of range: ${strVal}`\n )\n }\n this.fields[name] = `${strVal}u`\n }\n return this\n }\n\n /**\n * Adds a number field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN/Infinity/-Infinity is supplied\n */\n public floatField(name: string, value: number | any): Point {\n let val: number\n if (typeof value === 'number') {\n val = value\n } else {\n val = parseFloat(value)\n }\n if (!isFinite(val)) {\n throw new Error(`invalid float value for field '${name}': ${value}`)\n }\n\n this.fields[name] = String(val)\n return this\n }\n\n /**\n * Adds a string field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n */\n public stringField(name: string, value: string | any): Point {\n if (value !== null && value !== undefined) {\n if (typeof value !== 'string') value = String(value)\n this.fields[name] = escape.quoted(value)\n }\n return this\n }\n\n /**\n * Sets point timestamp. Timestamp can be specified as a Date (preferred), number, string\n * or an undefined value. An undefined value instructs to assign a local timestamp using\n * the client's clock. An empty string can be used to let the server assign\n * the timestamp. A number value represents time as a count of time units since epoch, the\n * exact time unit then depends on the {@link InfluxDB.getWriteApi | precision} of the API\n * that writes the point.\n *\n * Beware that the current time in nanoseconds can't precisely fit into a JS number,\n * which can hold at most 2^53 integer number. Nanosecond precision numbers are thus supplied as\n * a (base-10) string. An application can also use ES2020 BigInt to represent nanoseconds,\n * BigInt's `toString()` returns the required high-precision string.\n *\n * Note that InfluxDB requires the timestamp to fit into int64 data type.\n *\n * @param value - point time\n * @returns this\n */\n public timestamp(value: Date | number | string | undefined): Point {\n this.time = value\n return this\n }\n\n /**\n * Creates an InfluxDB protocol line out of this instance.\n * @param settings - settings control serialization of a point timestamp and can also add default tags,\n * nanosecond timestamp precision is used when no `settings` or no `settings.convertTime` is supplied.\n * @returns an InfluxDB protocol line out of this instance\n */\n public toLineProtocol(settings?: Partial): string | undefined {\n if (!this.name) return undefined\n let fieldsLine = ''\n Object.keys(this.fields)\n .sort()\n .forEach((x) => {\n if (x) {\n const val = this.fields[x]\n if (fieldsLine.length > 0) fieldsLine += ','\n fieldsLine += `${escape.tag(x)}=${val}`\n }\n })\n if (fieldsLine.length === 0) return undefined // no fields present\n let tagsLine = ''\n const tags =\n settings && settings.defaultTags\n ? {...settings.defaultTags, ...this.tags}\n : this.tags\n Object.keys(tags)\n .sort()\n .forEach((x) => {\n if (x) {\n const val = tags[x]\n if (val) {\n tagsLine += ','\n tagsLine += `${escape.tag(x)}=${escape.tag(val)}`\n }\n }\n })\n let time = this.time\n if (settings && settings.convertTime) {\n time = settings.convertTime(time)\n } else {\n time = convertTimeToNanos(time)\n }\n\n return `${escape.measurement(this.name)}${tagsLine} ${fieldsLine}${\n time !== undefined ? ' ' + time : ''\n }`\n }\n\n toString(): string {\n const line = this.toLineProtocol(undefined)\n return line ? line : `invalid point: ${JSON.stringify(this, undefined)}`\n }\n}\n","import {getRetryDelay, RetryDelayStrategy} from '../errors'\nimport {\n RetryDelayStrategyOptions,\n DEFAULT_RetryDelayStrategyOptions,\n} from '../options'\n\n/**\n * Applies a variant of exponential backoff with initial and max delay and a random\n * jitter delay. It also respects `retry delay` when specified together with an error.\n */\nexport class RetryStrategyImpl implements RetryDelayStrategy {\n options: RetryDelayStrategyOptions\n currentDelay: number | undefined\n\n constructor(options?: Partial) {\n this.options = {...DEFAULT_RetryDelayStrategyOptions, ...options}\n this.success()\n }\n\n nextDelay(error?: Error, failedAttempts?: number): number {\n const delay = getRetryDelay(error)\n if (delay && delay > 0) {\n return delay + Math.round(Math.random() * this.options.retryJitter)\n } else {\n if (failedAttempts && failedAttempts > 0) {\n // compute delay\n if (this.options.randomRetry) {\n // random delay between deterministic delays\n let delay = Math.max(this.options.minRetryDelay, 1)\n let nextDelay = delay * this.options.exponentialBase\n for (let i = 1; i < failedAttempts; i++) {\n delay = nextDelay\n nextDelay = nextDelay * this.options.exponentialBase\n if (nextDelay >= this.options.maxRetryDelay) {\n nextDelay = this.options.maxRetryDelay\n break\n }\n }\n return (\n delay +\n Math.round(\n Math.random() * (nextDelay - delay) +\n Math.random() * this.options.retryJitter\n )\n )\n }\n // deterministric delay otherwise\n let delay = Math.max(this.options.minRetryDelay, 1)\n for (let i = 1; i < failedAttempts; i++) {\n delay = delay * this.options.exponentialBase\n if (delay >= this.options.maxRetryDelay) {\n delay = this.options.maxRetryDelay\n break\n }\n }\n return delay + Math.round(Math.random() * this.options.retryJitter)\n } else if (this.currentDelay) {\n this.currentDelay = Math.min(\n Math.max(this.currentDelay * this.options.exponentialBase, 1) +\n Math.round(Math.random() * this.options.retryJitter),\n this.options.maxRetryDelay\n )\n } else {\n this.currentDelay =\n this.options.minRetryDelay +\n Math.round(Math.random() * this.options.retryJitter)\n }\n return this.currentDelay\n }\n }\n success(): void {\n this.currentDelay = undefined\n }\n}\n\n/**\n * Creates a new instance of retry strategy.\n * @param options - retry options\n * @returns retry strategy implementation\n */\nexport function createRetryDelayStrategy(\n options?: Partial\n): RetryDelayStrategy {\n return new RetryStrategyImpl(options)\n}\n","import {Log} from '../util/logger'\n\ninterface RetryItem {\n lines: string[]\n retryCount: number\n retryTime: number\n expires: number\n next?: RetryItem\n}\n\ntype FindShrinkCandidateResult = [found: RetryItem, parent?: RetryItem]\n\nfunction findShrinkCandidate(first: RetryItem): FindShrinkCandidateResult {\n let parent = undefined\n let found = first\n let currentParent = first\n while (currentParent.next) {\n if (currentParent.next.expires < found.expires) {\n parent = currentParent\n found = currentParent.next\n }\n currentParent = currentParent.next\n }\n return [found, parent]\n}\n\n/**\n * Retries lines up to a limit of max buffer size.\n */\nexport default class RetryBuffer {\n first?: RetryItem\n size = 0\n closed = false\n private _timeoutHandle: any = undefined\n\n constructor(\n private maxLines: number,\n private retryLines: (\n lines: string[],\n retryCountdown: number,\n started: number\n ) => Promise,\n private onShrink: (entry: {\n lines: string[]\n retryCount: number\n expires: number\n }) => void = () => undefined\n ) {}\n\n addLines(\n lines: string[],\n retryCount: number,\n delay: number,\n expires: number\n ): void {\n if (this.closed) return\n if (!lines.length) return\n let retryTime = Date.now() + delay\n if (expires < retryTime) {\n retryTime = expires\n }\n // ensure at most maxLines are in the Buffer\n if (this.first && this.size + lines.length > this.maxLines) {\n const origSize = this.size\n const newSize = origSize * 0.7 // reduce to 70 %\n do {\n // remove \"oldest\" item\n const [found, parent] = findShrinkCandidate(this.first)\n this.size -= found.lines.length\n if (parent) {\n parent.next = found.next\n } else {\n this.first = found.next\n if (this.first) {\n this.scheduleRetry(this.first.retryTime - Date.now())\n }\n }\n found.next = undefined\n this.onShrink(found)\n } while (this.first && this.size + lines.length > newSize)\n Log.error(\n `RetryBuffer: ${\n origSize - this.size\n } oldest lines removed to keep buffer size under the limit of ${\n this.maxLines\n } lines.`\n )\n }\n const toAdd: RetryItem = {\n lines,\n retryCount,\n retryTime,\n expires,\n }\n // insert sorted according to retryTime\n let current: RetryItem | undefined = this.first\n let parent = undefined\n for (;;) {\n if (!current || current.retryTime > retryTime) {\n toAdd.next = current\n if (parent) {\n parent.next = toAdd\n } else {\n this.first = toAdd\n this.scheduleRetry(retryTime - Date.now())\n }\n break\n }\n parent = current\n current = current.next\n }\n this.size += lines.length\n }\n\n removeLines(): RetryItem | undefined {\n if (this.first) {\n const toRetry = this.first\n this.first = this.first.next\n toRetry.next = undefined\n this.size -= toRetry.lines.length\n return toRetry\n }\n return undefined\n }\n\n scheduleRetry(delay: number): void {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle)\n }\n this._timeoutHandle = setTimeout(() => {\n const toRetry = this.removeLines()\n if (toRetry) {\n this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n .catch(() => {\n /* error is already logged, it must be caught */\n })\n .finally(() => {\n // schedule next retry execution\n if (this.first) {\n this.scheduleRetry(this.first.retryTime - Date.now())\n }\n })\n } else {\n this._timeoutHandle = undefined\n }\n }, Math.max(delay, 0))\n }\n\n async flush(): Promise {\n let toRetry\n while ((toRetry = this.removeLines())) {\n await this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n }\n }\n\n close(): number {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle)\n this._timeoutHandle = undefined\n }\n this.closed = true\n return this.size\n }\n}\n","/**\n * Utf8Length returns an expected length of a string when UTF-8 encoded.\n * @param s - input string\n * @returns expected count of bytes\n */\nexport default function utf8Length(s: string): number {\n let retVal = s.length\n // extends the size with code points (https://en.wikipedia.org/wiki/UTF-8#Encoding)\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i)\n /* istanbul ignore else - JS does not count with 4-bytes UNICODE characters at the moment */\n if (code < 0x80) {\n continue\n } else if (code >= 0x80 && code <= 0x7ff) {\n retVal++\n } else if (code >= 0x800 && code <= 0xffff) {\n if (code >= 0xd800 && code <= 0xdfff) {\n // node.js represents unicode characters above 0xffff by two UTF-16 surrogate halves\n // see https://en.wikipedia.org/wiki/UTF-8#Codepage_layout\n retVal++\n } else {\n retVal += 2\n }\n } else {\n // never happens in node.js 14, the situation can vary in the futures or in deno/browsers\n retVal += 3\n }\n }\n return retVal\n}\n","import WriteApi from '../WriteApi'\nimport {\n DEFAULT_WriteOptions,\n WriteOptions,\n WritePrecisionType,\n} from '../options'\nimport {Transport, SendOptions} from '../transport'\nimport {Headers} from '../results'\nimport {Log} from '../util/logger'\nimport {HttpError, RetryDelayStrategy} from '../errors'\nimport {Point} from '../Point'\nimport {currentTime, dateToProtocolTimestamp} from '../util/currentTime'\nimport {createRetryDelayStrategy} from './retryStrategy'\nimport RetryBuffer from './RetryBuffer'\nimport utf8Length from '../util/utf8Length'\n\nclass WriteBuffer {\n length = 0\n bytes = -1\n lines: string[]\n\n constructor(\n private maxChunkRecords: number,\n private maxBatchBytes: number,\n private flushFn: (lines: string[]) => Promise,\n private scheduleSend: () => void\n ) {\n this.lines = new Array(maxChunkRecords)\n }\n\n add(record: string): void {\n const size = utf8Length(record)\n if (this.length === 0) {\n this.scheduleSend()\n } else if (this.bytes + size + 1 >= this.maxBatchBytes) {\n // the new size already exceeds maxBatchBytes, send it\n this.flush().catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n })\n }\n this.lines[this.length] = record\n this.length++\n this.bytes += size + 1\n if (\n this.length >= this.maxChunkRecords ||\n this.bytes >= this.maxBatchBytes\n ) {\n this.flush().catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n })\n }\n }\n flush(): Promise {\n const lines = this.reset()\n if (lines.length > 0) {\n return this.flushFn(lines)\n } else {\n return Promise.resolve()\n }\n }\n reset(): string[] {\n const retVal = this.lines.slice(0, this.length)\n this.length = 0\n this.bytes = -1 // lines are joined with \\n\n return retVal\n }\n}\n\nexport default class WriteApiImpl implements WriteApi {\n public path: string\n\n private writeBuffer: WriteBuffer\n private closed = false\n private writeOptions: WriteOptions\n private sendOptions: SendOptions\n private _timeoutHandle: any = undefined\n private currentTime: () => string\n private dateToProtocolTimestamp: (d: Date) => string\n\n retryBuffer: RetryBuffer\n retryStrategy: RetryDelayStrategy\n\n constructor(\n private transport: Transport,\n org: string,\n bucket: string,\n precision: WritePrecisionType,\n writeOptions?: Partial\n ) {\n this.path = `/api/v2/write?org=${encodeURIComponent(\n org\n )}&bucket=${encodeURIComponent(bucket)}&precision=${precision}`\n if (writeOptions?.consistency) {\n this.path += `&consistency=${encodeURIComponent(\n writeOptions.consistency\n )}`\n }\n this.writeOptions = {\n ...DEFAULT_WriteOptions,\n ...writeOptions,\n }\n this.currentTime = currentTime[precision]\n this.dateToProtocolTimestamp = dateToProtocolTimestamp[precision]\n if (this.writeOptions.defaultTags) {\n this.useDefaultTags(this.writeOptions.defaultTags)\n }\n this.sendOptions = {\n method: 'POST',\n headers: {\n 'content-type': 'text/plain; charset=utf-8',\n ...writeOptions?.headers,\n },\n gzipThreshold: this.writeOptions.gzipThreshold,\n }\n\n const scheduleNextSend = (): void => {\n if (this.writeOptions.flushInterval > 0) {\n this._clearFlushTimeout()\n /* istanbul ignore else manually reviewed, hard to reproduce */\n if (!this.closed) {\n this._timeoutHandle = setTimeout(\n () =>\n this.sendBatch(\n this.writeBuffer.reset(),\n this.writeOptions.maxRetries\n ).catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n }),\n this.writeOptions.flushInterval\n )\n }\n }\n }\n // write buffer\n this.writeBuffer = new WriteBuffer(\n this.writeOptions.batchSize,\n this.writeOptions.maxBatchBytes,\n (lines) => {\n this._clearFlushTimeout()\n return this.sendBatch(lines, this.writeOptions.maxRetries)\n },\n scheduleNextSend\n )\n this.sendBatch = this.sendBatch.bind(this)\n // retry buffer\n this.retryStrategy = createRetryDelayStrategy(this.writeOptions)\n this.retryBuffer = new RetryBuffer(\n this.writeOptions.maxBufferLines,\n this.sendBatch,\n this.writeOptions.writeRetrySkipped\n )\n }\n\n sendBatch(\n lines: string[],\n retryAttempts: number,\n expires: number = Date.now() + this.writeOptions.maxRetryTime\n ): Promise {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self: WriteApiImpl = this\n const failedAttempts = self.writeOptions.maxRetries + 1 - retryAttempts\n if (!this.closed && lines.length > 0) {\n if (expires <= Date.now()) {\n const error = new Error('Max retry time exceeded.')\n const onRetry = self.writeOptions.writeFailed.call(\n self,\n error,\n lines,\n failedAttempts,\n expires\n )\n if (onRetry) {\n return onRetry\n }\n Log.error(\n `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n error\n )\n return Promise.reject(error)\n }\n return new Promise((resolve, reject) => {\n let responseStatusCode: number | undefined\n const callbacks = {\n responseStarted(_headers: Headers, statusCode?: number): void {\n responseStatusCode = statusCode\n },\n error(error: Error): void {\n // call the writeFailed listener and check if we can retry\n const onRetry = self.writeOptions.writeFailed.call(\n self,\n error,\n lines,\n failedAttempts,\n expires\n )\n if (onRetry) {\n onRetry.then(resolve, reject)\n return\n }\n // ignore informational message about the state of InfluxDB\n // enterprise cluster, if present\n if (\n error instanceof HttpError &&\n error.json &&\n typeof error.json.error === 'string' &&\n error.json.error.includes('hinted handoff queue not empty')\n ) {\n Log.warn('Write to InfluxDB returns: ' + error.json.error)\n responseStatusCode = 204\n callbacks.complete()\n return\n }\n // retry if possible\n if (\n !self.closed &&\n retryAttempts > 0 &&\n (!(error instanceof HttpError) ||\n (error as HttpError).statusCode >= 429)\n ) {\n Log.warn(\n `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n error\n )\n self.retryBuffer.addLines(\n lines,\n retryAttempts - 1,\n self.retryStrategy.nextDelay(error, failedAttempts),\n expires\n )\n reject(error)\n return\n }\n Log.error(`Write to InfluxDB failed.`, error)\n reject(error)\n },\n complete(): void {\n // older implementations of transport do not report status code\n if (responseStatusCode == 204 || responseStatusCode == undefined) {\n self.writeOptions.writeSuccess.call(self, lines)\n self.retryStrategy.success()\n resolve()\n } else {\n const message = `204 HTTP response status code expected, but ${responseStatusCode} returned`\n const error = new HttpError(\n responseStatusCode,\n message,\n undefined,\n '0'\n )\n error.message = message\n callbacks.error(error)\n }\n },\n }\n this.transport.send(\n this.path,\n lines.join('\\n'),\n this.sendOptions,\n callbacks\n )\n })\n } else {\n return Promise.resolve()\n }\n }\n\n private _clearFlushTimeout(): void {\n if (this._timeoutHandle !== undefined) {\n clearTimeout(this._timeoutHandle)\n this._timeoutHandle = undefined\n }\n }\n\n writeRecord(record: string): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n this.writeBuffer.add(record)\n }\n writeRecords(records: ArrayLike): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n for (let i = 0; i < records.length; i++) {\n this.writeBuffer.add(records[i])\n }\n }\n writePoint(point: Point): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n const line = point.toLineProtocol(this)\n if (line) this.writeBuffer.add(line)\n }\n writePoints(points: ArrayLike): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n for (let i = 0; i < points.length; i++) {\n const line = points[i].toLineProtocol(this)\n if (line) this.writeBuffer.add(line)\n }\n }\n async flush(withRetryBuffer?: boolean): Promise {\n await this.writeBuffer.flush()\n if (withRetryBuffer) {\n return await this.retryBuffer.flush()\n }\n }\n close(): Promise {\n const retVal = this.writeBuffer.flush().finally(() => {\n const remaining = this.retryBuffer.close()\n if (remaining) {\n Log.error(\n `Retry buffer closed with ${remaining} items that were not written to InfluxDB!`,\n null\n )\n }\n this.closed = true\n })\n return retVal\n }\n dispose(): number {\n this._clearFlushTimeout()\n this.closed = true\n return this.retryBuffer.close() + this.writeBuffer.length\n }\n\n // PointSettings\n defaultTags: {[key: string]: string} | undefined\n useDefaultTags(tags: {[key: string]: string}): WriteApi {\n this.defaultTags = tags\n return this\n }\n convertTime(value: string | number | Date | undefined): string | undefined {\n if (value === undefined) {\n return this.currentTime()\n } else if (typeof value === 'string') {\n return value.length > 0 ? value : undefined\n } else if (value instanceof Date) {\n return this.dateToProtocolTimestamp(value)\n } else if (typeof value === 'number') {\n return String(Math.floor(value))\n } else {\n return String(value)\n }\n }\n}\n","import {CommunicationObserver, Headers} from '../results'\n\ntype CompleteObserver = Omit<\n Required>,\n 'useCancellable' | 'useResume'\n> &\n Pick, 'useResume' | 'useCancellable'>\n\nexport default function completeCommunicationObserver(\n callbacks: Partial> = {}\n): CompleteObserver {\n let state = 0\n const retVal: CompleteObserver = {\n next: (data: any): void | boolean => {\n if (\n state === 0 &&\n callbacks.next &&\n data !== null &&\n data !== undefined\n ) {\n return callbacks.next(data)\n }\n },\n error: (error: Error): void => {\n /* istanbul ignore else propagate error at most once */\n if (state === 0) {\n state = 1\n /* istanbul ignore else safety check */\n if (callbacks.error) callbacks.error(error)\n }\n },\n complete: (): void => {\n if (state === 0) {\n state = 2\n /* istanbul ignore else safety check */\n if (callbacks.complete) callbacks.complete()\n }\n },\n responseStarted: (headers: Headers, statusCode?: number): void => {\n if (callbacks.responseStarted)\n callbacks.responseStarted(headers, statusCode)\n },\n }\n if (callbacks.useCancellable) {\n retVal.useCancellable = callbacks.useCancellable.bind(callbacks)\n }\n if (callbacks.useResume) {\n retVal.useResume = callbacks.useResume.bind(callbacks)\n }\n return retVal\n}\n","import {Transport, SendOptions} from '../../transport'\nimport {ConnectionOptions} from '../../options'\nimport {AbortError, HttpError} from '../../errors'\nimport completeCommunicationObserver from '../completeCommunicationObserver'\nimport {Log} from '../../util/logger'\nimport {\n ChunkCombiner,\n CommunicationObserver,\n createTextDecoderCombiner,\n Headers,\n ResponseStartedFn,\n} from '../../results'\n\nfunction getResponseHeaders(response: Response): Headers {\n const headers: Headers = {}\n response.headers.forEach((value: string, key: string) => {\n const previous = headers[key]\n if (previous === undefined) {\n headers[key] = value\n } else if (Array.isArray(previous)) {\n previous.push(value)\n } else {\n headers[key] = [previous, value]\n }\n })\n return headers\n}\n\n/**\n * Transport layer that use browser fetch.\n */\nexport default class FetchTransport implements Transport {\n chunkCombiner: ChunkCombiner = createTextDecoderCombiner()\n private defaultHeaders: {[key: string]: string}\n private url: string\n constructor(private connectionOptions: ConnectionOptions) {\n this.defaultHeaders = {\n 'content-type': 'application/json; charset=utf-8',\n // 'User-Agent': `influxdb-client-js/${CLIENT_LIB_VERSION}`, // user-agent can hardly be customized https://github.com/influxdata/influxdb-client-js/issues/262\n ...connectionOptions.headers,\n }\n if (this.connectionOptions.token) {\n this.defaultHeaders['Authorization'] =\n 'Token ' + this.connectionOptions.token\n }\n this.url = String(this.connectionOptions.url)\n if (this.url.endsWith('/')) {\n this.url = this.url.substring(0, this.url.length - 1)\n }\n // https://github.com/influxdata/influxdb-client-js/issues/263\n // don't allow /api/v2 suffix to avoid future problems\n if (this.url.endsWith('/api/v2')) {\n this.url = this.url.substring(0, this.url.length - '/api/v2'.length)\n Log.warn(\n `Please remove '/api/v2' context path from InfluxDB base url, using ${this.url} !`\n )\n }\n }\n send(\n path: string,\n body: string,\n options: SendOptions,\n callbacks?: Partial> | undefined\n ): void {\n const observer = completeCommunicationObserver(callbacks)\n let cancelled = false\n let signal = (options as any).signal\n let pausePromise: Promise | undefined\n const resumeQuickly = () => {}\n let resume = resumeQuickly\n if (callbacks && callbacks.useCancellable) {\n const controller = new AbortController()\n if (!signal) {\n signal = controller.signal\n options = {...options, signal}\n }\n // resume data reading so that it can exit on abort signal\n signal.addEventListener('abort', () => {\n resume()\n })\n callbacks.useCancellable({\n cancel() {\n cancelled = true\n controller.abort()\n },\n isCancelled() {\n return cancelled || signal.aborted\n },\n })\n }\n this.fetch(path, body, options)\n .then(async (response) => {\n if (callbacks?.responseStarted) {\n observer.responseStarted(\n getResponseHeaders(response),\n response.status\n )\n }\n await this.throwOnErrorResponse(response)\n if (response.body) {\n const reader = response.body.getReader()\n let chunk: ReadableStreamReadResult\n do {\n if (pausePromise) {\n await pausePromise\n }\n if (cancelled) {\n break\n }\n chunk = await reader.read()\n if (observer.next(chunk.value) === false) {\n const useResume = observer.useResume\n if (!useResume) {\n const msg = 'Unable to pause, useResume is not configured!'\n await reader.cancel(msg)\n return Promise.reject(new Error(msg))\n }\n pausePromise = new Promise((resolve) => {\n resume = () => {\n resolve()\n pausePromise = undefined\n resume = resumeQuickly\n }\n useResume(resume)\n })\n }\n } while (!chunk.done)\n } else if (response.arrayBuffer) {\n const buffer = await response.arrayBuffer()\n observer.next(new Uint8Array(buffer))\n } else {\n const text = await response.text()\n observer.next(new TextEncoder().encode(text))\n }\n })\n .catch((e) => {\n if (!cancelled) {\n observer.error(e)\n }\n })\n .finally(() => observer.complete())\n }\n private async throwOnErrorResponse(response: Response): Promise {\n if (response.status >= 300) {\n let text = ''\n try {\n text = await response.text()\n if (!text) {\n const headerError = response.headers.get('x-influxdb-error')\n if (headerError) {\n text = headerError\n }\n }\n } catch (e) {\n Log.warn('Unable to receive error body', e)\n throw new HttpError(\n response.status,\n response.statusText,\n undefined,\n response.headers.get('retry-after'),\n response.headers.get('content-type')\n )\n }\n throw new HttpError(\n response.status,\n response.statusText,\n text,\n response.headers.get('retry-after'),\n response.headers.get('content-type')\n )\n }\n }\n\n async *iterate(\n path: string,\n body: string,\n options: SendOptions\n ): AsyncIterableIterator {\n const response = await this.fetch(path, body, options)\n await this.throwOnErrorResponse(response)\n if (response.body) {\n const reader = response.body.getReader()\n for (;;) {\n const {value, done} = await reader.read()\n if (done) {\n break\n }\n if (options.signal?.aborted) {\n await response.body.cancel()\n throw new AbortError()\n }\n yield value\n }\n } else if (response.arrayBuffer) {\n const buffer = await response.arrayBuffer()\n yield new Uint8Array(buffer)\n } else {\n const text = await response.text()\n yield new TextEncoder().encode(text)\n }\n }\n\n async request(\n path: string,\n body: any,\n options: SendOptions,\n responseStarted?: ResponseStartedFn\n ): Promise {\n const response = await this.fetch(path, body, options)\n const {headers} = response\n const responseContentType = headers.get('content-type') || ''\n if (responseStarted) {\n responseStarted(getResponseHeaders(response), response.status)\n }\n\n await this.throwOnErrorResponse(response)\n const responseType = options.headers?.accept ?? responseContentType\n if (responseType.includes('json')) {\n return await response.json()\n } else if (\n responseType.includes('text') ||\n responseType.startsWith('application/csv')\n ) {\n return await response.text()\n }\n }\n\n private fetch(\n path: string,\n body: any,\n options: SendOptions\n ): Promise {\n const {method, headers, ...other} = options\n const url = `${this.url}${path}`\n const request: RequestInit = {\n method: method,\n body:\n method === 'GET' || method === 'HEAD'\n ? undefined\n : typeof body === 'string'\n ? body\n : JSON.stringify(body),\n headers: {\n ...this.defaultHeaders,\n ...headers,\n },\n credentials: 'omit' as const,\n // override with custom transport options\n ...this.connectionOptions.transportOptions,\n // allow to specify custom options, such as signal, in SendOptions\n ...other,\n }\n this.requestDecorator(request, options, url)\n return fetch(url, request)\n }\n\n /**\n * RequestDecorator allows to modify requests before sending.\n *\n * The following example shows a function that adds gzip\n * compression of requests using pako.js.\n *\n * ```ts\n * const client = new InfluxDB({url: 'http://a'})\n * client.transport.requestDecorator = function(request, options) {\n * const body = request.body\n * if (\n * typeof body === 'string' &&\n * options.gzipThreshold !== undefined &&\n * body.length > options.gzipThreshold\n * ) {\n * request.headers['content-encoding'] = 'gzip'\n * request.body = pako.gzip(body)\n * }\n * }\n * ```\n */\n public requestDecorator: (\n request: RequestInit,\n options: SendOptions,\n url: string\n ) => void = function () {}\n}\n","import {Observable} from '../observable'\nimport QueryApi, {QueryOptions} from '../QueryApi'\nimport {Transport} from '../transport'\nimport {\n CommunicationObserver,\n FluxResultObserver,\n FluxTableMetaData,\n Row,\n AnnotatedCSVResponse,\n IterableResultExecutor,\n} from '../results'\nimport {ParameterizedQuery} from '../query/flux'\nimport {APIExecutor} from '../results/ObservableQuery'\n\nconst DEFAULT_dialect: any = {\n header: true,\n delimiter: ',',\n quoteChar: '\"',\n commentPrefix: '#',\n annotations: ['datatype', 'group', 'default'],\n}\n\nexport class QueryApiImpl implements QueryApi {\n private options: QueryOptions\n constructor(\n private transport: Transport,\n private createCSVResponse: (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ) => AnnotatedCSVResponse,\n org: string | QueryOptions\n ) {\n this.options = typeof org === 'string' ? {org} : org\n }\n\n with(options: Partial): QueryApi {\n return new QueryApiImpl(this.transport, this.createCSVResponse, {\n ...this.options,\n ...options,\n })\n }\n\n response(query: string | ParameterizedQuery): AnnotatedCSVResponse {\n const {org, type, gzip, headers} = this.options\n const path = `/api/v2/query?org=${encodeURIComponent(org)}`\n const body = JSON.stringify(\n this.decorateRequest({\n query: query.toString(),\n dialect: DEFAULT_dialect,\n type,\n })\n )\n const options = {\n method: 'POST',\n headers: {\n 'content-type': 'application/json; encoding=utf-8',\n 'accept-encoding': gzip ? 'gzip' : 'identity',\n ...headers,\n },\n }\n return this.createCSVResponse(\n (consumer) => this.transport.send(path, body, options, consumer),\n () => this.transport.iterate(path, body, options)\n )\n }\n\n iterateLines(query: string | ParameterizedQuery): AsyncIterable {\n return this.response(query).iterateLines()\n }\n iterateRows(query: string | ParameterizedQuery): AsyncIterable {\n return this.response(query).iterateRows()\n }\n lines(query: string | ParameterizedQuery): Observable {\n return this.response(query).lines()\n }\n\n rows(query: string | ParameterizedQuery): Observable {\n return this.response(query).rows()\n }\n\n queryLines(\n query: string | ParameterizedQuery,\n consumer: CommunicationObserver\n ): void {\n return this.response(query).consumeLines(consumer)\n }\n\n queryRows(\n query: string | ParameterizedQuery,\n consumer: FluxResultObserver\n ): void {\n return this.response(query).consumeRows(consumer)\n }\n\n collectRows(\n query: string | ParameterizedQuery,\n rowMapper?: (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined\n ): Promise> {\n return this.response(query).collectRows(rowMapper)\n }\n\n collectLines(query: string | ParameterizedQuery): Promise> {\n return this.response(query).collectLines()\n }\n\n queryRaw(query: string | ParameterizedQuery): Promise {\n const {org, type, gzip, headers} = this.options\n return this.transport.request(\n `/api/v2/query?org=${encodeURIComponent(org)}`,\n JSON.stringify(\n this.decorateRequest({\n query: query.toString(),\n dialect: DEFAULT_dialect,\n type,\n })\n ),\n {\n method: 'POST',\n headers: {\n accept: 'text/csv',\n 'accept-encoding': gzip ? 'gzip' : 'identity',\n 'content-type': 'application/json; encoding=utf-8',\n ...headers,\n },\n }\n )\n }\n\n private decorateRequest(request: any): any {\n if (typeof this.options.now === 'function') {\n request.now = this.options.now()\n }\n // https://docs.influxdata.com/influxdb/latest/api/#operation/PostQuery requires type\n request.type = this.options.type ?? 'flux'\n return request\n }\n}\n\nexport default QueryApiImpl\n","import {\n CommunicationObserver,\n FluxResultObserver,\n FluxTableMetaData,\n Row,\n linesToTables,\n ChunkCombiner,\n chunksToLines,\n chunksToLinesIterable,\n linesToRowsIterable,\n} from '../results'\nimport {Observable} from '../observable'\nimport {\n AnnotatedCSVResponse,\n IterableResultExecutor,\n} from './AnnotatedCSVResponse'\nimport ObservableQuery, {APIExecutor} from './ObservableQuery'\n\nexport function defaultRowMapping(\n values: string[],\n tableMeta: FluxTableMetaData\n): Record {\n return tableMeta.toObject(values)\n}\n\n/**\n * AnnotatedCsvResponseImpl is an implementation AnnotatedCsvResponse\n * that uses the supplied executor to supply a response data stream.\n */\nexport class AnnotatedCSVResponseImpl implements AnnotatedCSVResponse {\n constructor(\n private executor: APIExecutor,\n private iterableResultExecutor: IterableResultExecutor,\n private chunkCombiner: ChunkCombiner\n ) {}\n iterateLines(): AsyncIterable {\n return chunksToLinesIterable(this.iterableResultExecutor())\n }\n iterateRows(): AsyncIterable {\n return linesToRowsIterable(\n chunksToLinesIterable(this.iterableResultExecutor())\n )\n }\n lines(): Observable {\n return new ObservableQuery(this.executor, (observer) =>\n chunksToLines(observer, this.chunkCombiner)\n )\n }\n\n rows(): Observable {\n return new ObservableQuery(this.executor, (observer) => {\n return chunksToLines(\n linesToTables({\n next(values, tableMeta) {\n observer.next({values, tableMeta})\n },\n error(e) {\n observer.error(e)\n },\n complete() {\n observer.complete()\n },\n }),\n this.chunkCombiner\n )\n })\n }\n\n consumeLines(consumer: CommunicationObserver): void {\n this.executor(chunksToLines(consumer, this.chunkCombiner))\n }\n\n consumeRows(consumer: FluxResultObserver): void {\n this.executor(chunksToLines(linesToTables(consumer), this.chunkCombiner))\n }\n\n collectRows(\n rowMapper: (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined = defaultRowMapping as (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined\n ): Promise> {\n const retVal: Array = []\n return new Promise((resolve, reject) => {\n this.consumeRows({\n next(values: string[], tableMeta: FluxTableMetaData): void {\n const toAdd = rowMapper.call(this, values, tableMeta)\n if (toAdd !== undefined) {\n retVal.push(toAdd)\n }\n },\n error(error: Error): void {\n reject(error)\n },\n complete(): void {\n resolve(retVal)\n },\n })\n })\n }\n\n collectLines(): Promise> {\n const retVal: Array = []\n return new Promise((resolve, reject) => {\n this.consumeLines({\n next(line: string): void {\n retVal.push(line)\n },\n error(error: Error): void {\n reject(error)\n },\n complete(): void {\n resolve(retVal)\n },\n })\n })\n }\n}\n","import WriteApi from './WriteApi'\nimport {ClientOptions, WriteOptions, WritePrecisionType} from './options'\nimport WriteApiImpl from './impl/WriteApiImpl'\nimport {IllegalArgumentError} from './errors'\nimport {Transport} from './transport'\n// replaced by ./impl/browser/FetchTransport in browser builds\nimport TransportImpl from './impl/browser/FetchTransport'\nimport QueryApi, {QueryOptions} from './QueryApi'\nimport QueryApiImpl from './impl/QueryApiImpl'\nimport {\n AnnotatedCSVResponse,\n APIExecutor,\n IterableResultExecutor,\n} from './results'\nimport {AnnotatedCSVResponseImpl} from './results/AnnotatedCSVResponseImpl'\n\n/**\n * InfluxDB entry point that configures communication with InfluxDB server\n * and provide APIs to write and query data.\n */\nexport default class InfluxDB {\n private _options: ClientOptions\n readonly transport: Transport\n readonly processCSVResponse: (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ) => AnnotatedCSVResponse\n\n /**\n * Creates influxdb client options from an options object or url.\n * @param options - client options\n */\n constructor(options: ClientOptions | string) {\n if (typeof options === 'string') {\n this._options = {url: options}\n } else if (options !== null && typeof options === 'object') {\n this._options = options\n } else {\n throw new IllegalArgumentError('No url or configuration specified!')\n }\n const url = this._options.url\n if (typeof url !== 'string')\n throw new IllegalArgumentError('No url specified!')\n if (url.endsWith('/')) this._options.url = url.substring(0, url.length - 1)\n this.transport = this._options.transport ?? new TransportImpl(this._options)\n this.processCSVResponse = (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ): AnnotatedCSVResponse =>\n new AnnotatedCSVResponseImpl(\n executor,\n iterableResultExecutor,\n this.transport.chunkCombiner\n )\n }\n\n /**\n * Creates WriteApi for the supplied organization and bucket. BEWARE that returned instances must be closed\n * in order to flush the remaining data and close already scheduled retry executions.\n *\n * @remarks\n * Use {@link WriteOptions} to customize retry strategy options, data chunking\n * and flushing options. See {@link DEFAULT_WriteOptions} to see the defaults.\n *\n * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/write.mjs | write example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/writeAdvanced.mjs | writeAdvanced example},\n * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example}.\n *\n * @param org - Specifies the destination organization for writes. Takes either the ID or Name interchangeably.\n * @param bucket - The destination bucket for writes.\n * @param precision - Timestamp precision for line items.\n * @param writeOptions - Custom write options.\n * @returns WriteApi instance\n */\n getWriteApi(\n org: string,\n bucket: string,\n precision: WritePrecisionType = 'ns',\n writeOptions?: Partial\n ): WriteApi {\n return new WriteApiImpl(\n this.transport,\n org,\n bucket,\n precision,\n writeOptions ?? this._options.writeOptions\n )\n }\n\n /**\n * Creates QueryApi for the supplied organization .\n *\n * @remarks\n * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/query.ts | query.ts example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/queryWithParams.mjs | queryWithParams.mjs example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/rxjs-query.ts | rxjs-query.ts example},\n * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example},\n *\n * @param org - organization or query options\n * @returns QueryApi instance\n */\n getQueryApi(org: string | QueryOptions): QueryApi {\n return new QueryApiImpl(this.transport, this.processCSVResponse, org)\n }\n}\n"],"mappings":";;;;;scAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,gBAAAE,EAAA,8BAAAC,GAAA,sCAAAC,EAAA,yBAAAC,EAAA,eAAAC,EAAA,cAAAC,EAAA,yBAAAC,EAAA,aAAAC,EAAA,iBAAAC,EAAA,QAAAC,EAAA,UAAAC,GAAA,yBAAAC,EAAA,mBAAAC,EAAA,qBAAAC,GAAA,kBAAAC,EAAA,0BAAAC,EAAA,kBAAAC,GAAA,uBAAAC,GAAA,0BAAAC,GAAA,4BAAAC,EAAA,8BAAAC,EAAA,gBAAAC,GAAA,4BAAAC,GAAA,WAAAC,EAAA,SAAAC,GAAA,aAAAC,GAAA,iBAAAC,GAAA,iBAAAC,GAAA,mBAAAC,GAAA,cAAAC,GAAA,gBAAAC,GAAA,eAAAC,GA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Y5B,YAAYC,EAAiC,CAhC/C,IAAAC,EAiCI,GAAI,OAAOD,GAAY,SACrB,KAAK,SAAW,CAAC,IAAKA,CAAO,UACpBA,IAAY,MAAQ,OAAOA,GAAY,SAChD,KAAK,SAAWA,MAEhB,OAAM,IAAIE,EAAqB,oCAAoC,EAErE,IAAMC,EAAM,KAAK,SAAS,IAC1B,GAAI,OAAOA,GAAQ,SACjB,MAAM,IAAID,EAAqB,mBAAmB,EAChDC,EAAI,SAAS,GAAG,IAAG,KAAK,SAAS,IAAMA,EAAI,UAAU,EAAGA,EAAI,OAAS,CAAC,GAC1E,KAAK,WAAYF,EAAA,KAAK,SAAS,YAAd,KAAAA,EAA2B,IAAIG,EAAc,KAAK,QAAQ,EAC3E,KAAK,mBAAqB,CACxBC,EACAC,IAEA,IAAIC,EACFF,EACAC,EACA,KAAK,UAAU,aACjB,CACJ,CAoBA,YACEE,EACAC,EACAC,EAAgC,KAChCC,EACU,CACV,OAAO,IAAIC,EACT,KAAK,UACLJ,EACAC,EACAC,EACAC,GAAA,KAAAA,EAAgB,KAAK,SAAS,YAChC,CACF,CAcA,YAAYH,EAAsC,CAChD,OAAO,IAAIK,GAAa,KAAK,UAAW,KAAK,mBAAoBL,CAAG,CACtE,CACF","names":["src_exports","__export","AbortError","DEFAULT_ConnectionOptions","DEFAULT_RetryDelayStrategyOptions","DEFAULT_WriteOptions","FLUX_VALUE","HttpError","IllegalArgumentError","InfluxDB","LineSplitter","Log","Point","RequestTimedOutError","UNKNOWN_COLUMN","canRetryHttpCall","chunksToLines","chunksToLinesIterable","consoleLogger","convertTimeToNanos","createFluxTableColumn","createFluxTableMetaData","createTextDecoderCombiner","currentTime","dateToProtocolTimestamp","escape","flux","fluxBool","fluxDateTime","fluxDuration","fluxExpression","fluxFloat","fluxInteger","fluxRegExp","fluxString","getRetryDelay","isStatusCodeRetriable","linesToRowsIterable","linesToTables","newFluxTableColumn","sanitizeFloat","sanitizeInteger","serializeDateTimeAsDate","serializeDateTimeAsNumber","serializeDateTimeAsString","setLogger","stringToLines","symbolObservable","toFluxValue","typeSerializers","useProcessHrtime","createTextDecoderCombiner","decoder","first","second","retVal","chunk","start","end","chunksToLines","target","chunkCombiner","chunks","createTextDecoderCombiner","previous","finished","quoted","paused","resumeChunks","bufferReceived","chunk","index","start","c","end","retVal","e","error","cancellable","x","chunksToLinesIterable","source","chunkCombiner","chunks","createTextDecoderCombiner","previous","quoted","chunk","index","start","c","end","LineSplitter","val","line","quoteCount","startIndex","values","count","i","c","start","end","identity","x","typeSerializers","FluxTableColumnImpl","row","_a","val","UNKNOWN_COLUMN","newFluxTableColumn","createFluxTableColumn","object","_b","retVal","retriableStatusCodes","isStatusCodeRetriable","statusCode","IllegalArgumentError","message","HttpError","statusMessage","body","retryAfter","contentType","e","RETRY_CODES","canRetryHttpCall","error","getRetryDelay","retryJitter","retVal","RequestTimedOutError","AbortError","serializeDateTimeAsDate","typeSerializers","x","serializeDateTimeAsNumber","serializeDateTimeAsString","FluxTableMetaDataImpl","columns","col","i","label","errorOnMissingColumn","IllegalArgumentError","UNKNOWN_COLUMN","row","acc","column","createFluxTableMetaData","linesToTables","consumer","splitter","LineSplitter","columns","expectMeta","firstColumnIndex","lastMeta","retVal","error","line","values","size","i","newFluxTableColumn","createFluxTableMetaData","linesToRowsIterable","source","splitter","LineSplitter","columns","expectMeta","firstColumnIndex","lastMeta","line","values","size","i","newFluxTableColumn","createFluxTableMetaData","stringToLines","source","target","quoted","start","index","c","end","symbolObservable","QuerySubscription","observer","executor","value","e","c","_a","noop","completeObserver","next","error","complete","ObservableQuery","decorator","observerOrNext","symbolObservable","DEFAULT_ConnectionOptions","DEFAULT_RetryDelayStrategyOptions","DEFAULT_WriteOptions","createEscaper","characters","replacements","value","retVal","from","i","found","createQuotedEscaper","escaper","escape","zeroPadding","useProcessHrtime","use","lastMillis","stepsInMillis","nanos","millis","zeroPadding","micros","seconds","currentTime","dateToProtocolTimestamp","d","convertTimeToNanos","value","consoleLogger","message","error","provider","Log","setLogger","logger","previous","FLUX_VALUE","FluxParameter","fluxValue","isFluxParameterLike","value","sanitizeString","retVal","i","prepareRetVal","c","fluxString","sanitizeFloat","val","strVal","hasDot","fluxFloat","sanitizeInteger","negative","fluxInteger","sanitizeDateTime","fluxDateTime","fluxDuration","sanitizeRegExp","fluxRegExp","fluxBool","fluxExpression","toFluxValue","flux","strings","values","parts","partIndex","text","sanitized","Point","measurementName","name","value","val","strVal","code","escape","settings","fieldsLine","x","tagsLine","tags","time","convertTimeToNanos","line","RetryStrategyImpl","options","DEFAULT_RetryDelayStrategyOptions","error","failedAttempts","delay","getRetryDelay","nextDelay","i","createRetryDelayStrategy","findShrinkCandidate","first","parent","found","currentParent","RetryBuffer","maxLines","retryLines","onShrink","lines","retryCount","delay","expires","retryTime","origSize","newSize","Log","toAdd","current","toRetry","utf8Length","s","retVal","i","code","WriteBuffer","maxChunkRecords","maxBatchBytes","flushFn","scheduleSend","record","size","utf8Length","_e","lines","retVal","WriteApiImpl","transport","org","bucket","precision","writeOptions","DEFAULT_WriteOptions","currentTime","dateToProtocolTimestamp","scheduleNextSend","createRetryDelayStrategy","RetryBuffer","retryAttempts","expires","self","failedAttempts","error","onRetry","Log","resolve","reject","responseStatusCode","callbacks","_headers","statusCode","HttpError","message","records","i","point","line","points","withRetryBuffer","remaining","tags","value","completeCommunicationObserver","callbacks","state","retVal","data","error","headers","statusCode","getResponseHeaders","response","headers","value","key","previous","FetchTransport","connectionOptions","createTextDecoderCombiner","Log","path","body","options","callbacks","observer","completeCommunicationObserver","cancelled","signal","pausePromise","resumeQuickly","resume","controller","reader","chunk","useResume","msg","resolve","buffer","text","e","headerError","HttpError","_a","done","AbortError","responseStarted","_b","responseContentType","responseType","method","other","url","request","DEFAULT_dialect","QueryApiImpl","transport","createCSVResponse","org","options","query","type","gzip","headers","path","body","consumer","rowMapper","request","_a","QueryApiImpl_default","defaultRowMapping","values","tableMeta","AnnotatedCSVResponseImpl","executor","iterableResultExecutor","chunkCombiner","chunksToLinesIterable","linesToRowsIterable","ObservableQuery","observer","chunksToLines","linesToTables","e","consumer","rowMapper","retVal","resolve","reject","toAdd","error","line","InfluxDB","options","_a","IllegalArgumentError","url","FetchTransport","executor","iterableResultExecutor","AnnotatedCSVResponseImpl","org","bucket","precision","writeOptions","WriteApiImpl","QueryApiImpl_default"]} \ No newline at end of file diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.mjs b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.mjs new file mode 100644 index 0000000..3a1c375 --- /dev/null +++ b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.mjs @@ -0,0 +1,6 @@ +function b(){let r=new TextDecoder("utf-8");return{concat(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n},copy(e,t,n){let i=new Uint8Array(n-t);return i.set(e.subarray(t,n)),i},toUtf8String(e,t,n){return r.decode(e.subarray(t,n))}}}function C(r,e){let t=e!=null?e:b(),n,i=!1,s=!1,o=!1,a;function f(l){let c,d=0;for(n?(c=l.length===0?0:n.length,l=t.concat(n,l)):c=0;c0&&l[c-1]===13?c-1:c;if(i)return;if(o=r.next(t.toUtf8String(l,d,P))===!1,d=c+1,o)break}}else g===34&&(s=!s);c++}if(d{o=!1,f(new Uint8Array(0))});return}u.error(new Error("Unable to pause, useResume is not configured!")),o=!1}a&&(a(),a=void 0)}let u={next(l){if(!i)try{return f(l),!o}catch(c){this.error(c)}return!0},error(l){i||(i=!0,r.error(l))},complete(){i||(n&&r.next(t.toUtf8String(n,0,n.length)),i=!0,r.complete())}};return r.useCancellable&&(u.useCancellable=l=>{r.useCancellable&&r.useCancellable({cancel(){l.cancel(),n=void 0,u.complete()},isCancelled(){return l.isCancelled()}})}),r.useResume&&(u.useResume=l=>{a=l}),u}async function*z(r,e){let t=e!=null?e:b(),n,i=!1;for await(let s of r){let o,a=0;for(n?(o=n.length,s=t.concat(n,s)):o=0;o0&&s[o-1]===13?o-1:o;yield t.toUtf8String(s,a,u),a=o+1}}else f===34&&(i=!i);o++}ar,O={boolean:r=>r===""?null:r==="true",unsignedLong:r=>r===""?null:+r,long:r=>r===""?null:+r,double(r){switch(r){case"":return null;case"+Inf":return Number.POSITIVE_INFINITY;case"-Inf":return Number.NEGATIVE_INFINITY;default:return+r}},string:H,base64Binary:H,duration:r=>r===""?null:r,"dateTime:RFC3339":r=>r===""?null:r},L=class{get(e){var n;let t=e[this.index];return(t===""||t===void 0)&&this.defaultValue&&(t=this.defaultValue),((n=O[this.dataType])!=null?n:H)(t)}},ee=Object.freeze({label:"",dataType:"",group:!1,defaultValue:"",index:Number.MAX_SAFE_INTEGER,get:()=>{}});function I(){return new L}function We(r){var t,n;let e=new L;return e.label=String(r.label),e.dataType=r.dataType,e.group=Boolean(r.group),e.defaultValue=(t=r.defaultValue)!=null?t:"",e.index=(n=r.index)!=null?n:0,e}var Ce=[404,408,425,429,500,502,503,504];function Oe(r){return Ce.includes(r)}var y=class extends Error{constructor(e){super(e),this.name="IllegalArgumentError",Object.setPrototypeOf(this,y.prototype)}},m=class extends Error{constructor(t,n,i,s,o,a){super();this.statusCode=t;this.statusMessage=n;this.body=i;this.contentType=o;if(Object.setPrototypeOf(this,m.prototype),a)this.message=a;else if(i){if(o!=null&&o.startsWith("application/json"))try{this.json=JSON.parse(i),this.message=this.json.message,this.code=this.json.code}catch(f){}this.message||(this.message=`${t} ${n} : ${i}`)}else this.message=`${t} ${n}`;this.name="HttpError",this.setRetryAfter(s)}setRetryAfter(t){typeof t=="string"?/^[0-9]+$/.test(t)?this._retryAfter=parseInt(t):this._retryAfter=0:this._retryAfter=0}canRetry(){return Oe(this.statusCode)}retryAfter(){return this._retryAfter}},Se=["ECONNRESET","ENOTFOUND","ESOCKETTIMEDOUT","ETIMEDOUT","ECONNREFUSED","EHOSTUNREACH","EPIPE"];function Ne(r){if(r){if(typeof r.canRetry=="function")return!!r.canRetry();if(r.code&&Se.includes(r.code))return!0}else return!1;return!1}function te(r,e){if(r){let t;return typeof r.retryAfter=="function"?r.retryAfter():(t=0,e&&e>0?t+Math.round(Math.random()*e):t)}else return 0}var U=class extends Error{constructor(){super(),Object.setPrototypeOf(this,U.prototype),this.name="RequestTimedOutError",this.message="Request timed out"}canRetry(){return!0}retryAfter(){return 0}},w=class extends Error{constructor(){super(),this.name="AbortError",Object.setPrototypeOf(this,w.prototype),this.message="Response aborted"}canRetry(){return!0}retryAfter(){return 0}};function Xe(){O["dateTime:RFC3339"]=r=>r===""?null:new Date(Date.parse(r))}function Ge(){O["dateTime:RFC3339"]=r=>r===""?null:Date.parse(r)}function Ke(){O["dateTime:RFC3339"]=r=>r===""?null:r}var W=class{constructor(e){e.forEach((t,n)=>t.index=n),this.columns=e}column(e,t=!0){for(let n=0;n0&&r.charCodeAt(i-1)===13?i-1:i;e.next(r.substring(n,o)),n=i+1}}else s===34&&(t=!t);i++}ntypeof Symbol=="function"&&Symbol.observable||"@@observable")();var Q=class{constructor(e,t){this.isClosed=!1;try{t({next:n=>{e.next(n)},error:n=>{this.isClosed=!0,e.error(n)},complete:()=>{this.isClosed=!0,e.complete()},useCancellable:n=>{this.cancellable=n}})}catch(n){this.isClosed=!0,e.error(n)}}get closed(){return this.isClosed}unsubscribe(){var e;(e=this.cancellable)==null||e.cancel(),this.isClosed=!0}};function N(){}function ve(r){let{next:e,error:t,complete:n}=r;return{next:e?e.bind(r):N,error:t?t.bind(r):N,complete:n?n.bind(r):N}}var T=class{constructor(e,t){this.executor=e;this.decorator=t}subscribe(e,t,n){let i=ve(typeof e!="object"||e===null?{next:e,error:t,complete:n}:e);return new Q(this.decorator(i),this.executor)}[ne](){return this}};Symbol.observable;var Nt={timeout:1e4},ie={retryJitter:200,minRetryDelay:5e3,maxRetryDelay:125e3,exponentialBase:5,randomRetry:!0},se={batchSize:1e3,maxBatchBytes:5e7,flushInterval:6e4,writeFailed:function(){},writeSuccess:function(){},writeRetrySkipped:function(){},maxRetries:5,maxRetryTime:18e4,maxBufferLines:32e3,retryJitter:200,minRetryDelay:5e3,maxRetryDelay:125e3,exponentialBase:2,gzipThreshold:1e3,randomRetry:!0};function j(r,e){return function(t){let n="",i=0,s=0;for(;s=0&&(n+=t.substring(i,s),n+=e[o],i=s+1),s++}return i==0?t:(i'"'+t(n)+'"'}var R={measurement:j(`, +\r `,["\\,","\\ ","\\n","\\r","\\t"]),quoted:Ae('"\\',['\\"',"\\\\"]),tag:j(`, = +\r `,["\\,","\\ ","\\=","\\n","\\r","\\t"])};var fe="000000000";function De(r){return!1}De(!0);var oe=Date.now(),q=0;function J(){{let r=Date.now();r!==oe?(oe=r,q=0):q++;let e=String(q);return String(r)+fe.substr(0,6-e.length)+e}}function ae(){return String(Date.now())+fe.substr(0,3)}function le(){return String(Date.now())}function ue(){return String(Math.floor(Date.now()/1e3))}var ce={s:ue,ms:le,us:ae,ns:J,seconds:ue,millis:le,micros:ae,nanos:J},de={s:r=>`${Math.floor(r.getTime()/1e3)}`,ms:r=>`${r.getTime()}`,us:r=>`${r.getTime()}000`,ns:r=>`${r.getTime()}000000`};function me(r){return r===void 0?J():typeof r=="string"?r.length>0?r:void 0:r instanceof Date?`${r.getTime()}000000`:String(typeof r=="number"?Math.floor(r):r)}var Ee={error(r,e){console.error("ERROR: "+r,e||"")},warn(r,e){console.warn("WARN: "+r,e||"")}},B=Ee,p={error(r,e){B.error(r,e)},warn(r,e){B.warn(r,e)}};function Jt(r){let e=B;return B=r,e}var M=Symbol("FLUX_VALUE"),h=class{constructor(e){this.fluxValue=e}toString(){return this.fluxValue}[M](){return this.fluxValue}};function Pe(r){return typeof r=="object"&&typeof r[M]=="function"}function S(r){if(r==null)return"";r=r.toString();let e,t=0;function n(){e===void 0&&(e=r.substring(0,t))}for(;t="0"&&i<="9"||i=="-")){if(i==="."){n=!0;continue}return`float(v: "${t}")`}return n?t:t+".0"}function Kt(r){return new h(he(r))}function ye(r){let e=String(r),t=e.startsWith("-"),n=t?e.substring(1):e;if(n.length===0||n.length>19)throw new Error(`not a flux integer: ${e}`);for(let i of n)if(i<"0"||i>"9")throw new Error(`not a flux integer: ${e}`);if(n.length===19){if(t&&n>"9223372036854775808")throw new Error(`flux integer out of bounds: ${e}`);if(!t&&n>"9223372036854775807")throw new Error(`flux integer out of bounds: ${e}`)}return e}function Yt(r){return new h(ye(r))}function Fe(r){return`time(v: "${S(r)}")`}function Zt(r){return new h(Fe(r))}function er(r){return new h(`duration(v: "${S(r)}")`)}function ge(r){return r instanceof RegExp?r.toString():new RegExp(r).toString()}function tr(r){return new h(ge(r))}function rr(r){return r==="true"||r==="false"?new h(r):new h((!!r).toString())}function pe(r){return new h(String(r))}function X(r){if(r===void 0)return"";if(r===null)return"null";if(typeof r=="boolean")return r.toString();if(typeof r=="string")return`"${S(r)}"`;if(typeof r=="number")return Number.isSafeInteger(r)?ye(r):he(r);if(typeof r=="object"){if(typeof r[M]=="function")return r[M]();if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return ge(r);if(Array.isArray(r))return`[${r.map(X).join(",")}]`}else if(typeof r=="bigint")return`${r}.0`;return X(r.toString())}function nr(r,...e){if(r.length==1&&e.length===0)return pe(r[0]);let t=new Array(r.length+e.length),n=0;for(let i=0;i=9223372036854776e3)throw new Error(`invalid integer value for field '${e}': '${t}'!`);return this.fields[e]=`${Math.floor(n)}i`,this}uintField(e,t){if(typeof t=="number"){if(isNaN(t)||t<0||t>Number.MAX_SAFE_INTEGER)throw new Error(`uint value for field '${e}' out of range: ${t}`);this.fields[e]=`${Math.floor(t)}u`}else{let n=String(t);for(let i=0;i57)throw new Error(`uint value has an unsupported character at pos ${i}: ${t}`)}if(n.length>20||n.length===20&&n.localeCompare("18446744073709551615")>0)throw new Error(`uint value for field '${e}' out of range: ${n}`);this.fields[e]=`${n}u`}return this}floatField(e,t){let n;if(typeof t=="number"?n=t:n=parseFloat(t),!isFinite(n))throw new Error(`invalid float value for field '${e}': ${t}`);return this.fields[e]=String(n),this}stringField(e,t){return t!=null&&(typeof t!="string"&&(t=String(t)),this.fields[e]=R.quoted(t)),this}timestamp(e){return this.time=e,this}toLineProtocol(e){if(!this.name)return;let t="";if(Object.keys(this.fields).sort().forEach(o=>{if(o){let a=this.fields[o];t.length>0&&(t+=","),t+=`${R.tag(o)}=${a}`}}),t.length===0)return;let n="",i=e&&e.defaultTags?{...e.defaultTags,...this.tags}:this.tags;Object.keys(i).sort().forEach(o=>{if(o){let a=i[o];a&&(n+=",",n+=`${R.tag(o)}=${R.tag(a)}`)}});let s=this.time;return e&&e.convertTime?s=e.convertTime(s):s=me(s),`${R.measurement(this.name)}${n} ${t}${s!==void 0?" "+s:""}`}toString(){let e=this.toLineProtocol(void 0);return e||`invalid point: ${JSON.stringify(this,void 0)}`}};var G=class{constructor(e){this.options={...ie,...e},this.success()}nextDelay(e,t){let n=te(e);if(n&&n>0)return n+Math.round(Math.random()*this.options.retryJitter);if(t&&t>0){if(this.options.randomRetry){let s=Math.max(this.options.minRetryDelay,1),o=s*this.options.exponentialBase;for(let a=1;a=this.options.maxRetryDelay){o=this.options.maxRetryDelay;break}return s+Math.round(Math.random()*(o-s)+Math.random()*this.options.retryJitter)}let i=Math.max(this.options.minRetryDelay,1);for(let s=1;s=this.options.maxRetryDelay){i=this.options.maxRetryDelay;break}return i+Math.round(Math.random()*this.options.retryJitter)}else this.currentDelay?this.currentDelay=Math.min(Math.max(this.currentDelay*this.options.exponentialBase,1)+Math.round(Math.random()*this.options.retryJitter),this.options.maxRetryDelay):this.currentDelay=this.options.minRetryDelay+Math.round(Math.random()*this.options.retryJitter);return this.currentDelay}success(){this.currentDelay=void 0}};function xe(r){return new G(r)}function Le(r){let e,t=r,n=r;for(;n.next;)n.next.expires{}){this.maxLines=e;this.retryLines=t;this.onShrink=n;this.size=0;this.closed=!1;this._timeoutHandle=void 0}addLines(e,t,n,i){if(this.closed||!e.length)return;let s=Date.now()+n;if(ithis.maxLines){let u=this.size,l=u*.7;do{let[c,d]=Le(this.first);this.size-=c.lines.length,d?d.next=c.next:(this.first=c.next,this.first&&this.scheduleRetry(this.first.retryTime-Date.now())),c.next=void 0,this.onShrink(c)}while(this.first&&this.size+e.length>l);p.error(`RetryBuffer: ${u-this.size} oldest lines removed to keep buffer size under the limit of ${this.maxLines} lines.`)}let o={lines:e,retryCount:t,retryTime:s,expires:i},a=this.first,f;for(;;){if(!a||a.retryTime>s){o.next=a,f?f.next=o:(this.first=o,this.scheduleRetry(s-Date.now()));break}f=a,a=a.next}this.size+=e.length}removeLines(){if(this.first){let e=this.first;return this.first=this.first.next,e.next=void 0,this.size-=e.lines.length,e}}scheduleRetry(e){this._timeoutHandle&&clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{let t=this.removeLines();t?this.retryLines(t.lines,t.retryCount,t.expires).catch(()=>{}).finally(()=>{this.first&&this.scheduleRetry(this.first.retryTime-Date.now())}):this._timeoutHandle=void 0},Math.max(e,0))}async flush(){let e;for(;e=this.removeLines();)await this.retryLines(e.lines,e.retryCount,e.expires)}close(){return this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this.closed=!0,this.size}};function K(r){let e=r.length;for(let t=0;t=128&&n<=2047?e++:n>=2048&&n<=65535?n>=55296&&n<=57343?e++:e+=2:e+=3)}return e}var Y=class{constructor(e,t,n,i){this.maxChunkRecords=e;this.maxBatchBytes=t;this.flushFn=n;this.scheduleSend=i;this.length=0;this.bytes=-1;this.lines=new Array(e)}add(e){let t=K(e);this.length===0?this.scheduleSend():this.bytes+t+1>=this.maxBatchBytes&&this.flush().catch(n=>{}),this.lines[this.length]=e,this.length++,this.bytes+=t+1,(this.length>=this.maxChunkRecords||this.bytes>=this.maxBatchBytes)&&this.flush().catch(n=>{})}flush(){let e=this.reset();return e.length>0?this.flushFn(e):Promise.resolve()}reset(){let e=this.lines.slice(0,this.length);return this.length=0,this.bytes=-1,e}},A=class{constructor(e,t,n,i,s){this.transport=e;this.closed=!1;this._timeoutHandle=void 0;this.path=`/api/v2/write?org=${encodeURIComponent(t)}&bucket=${encodeURIComponent(n)}&precision=${i}`,s!=null&&s.consistency&&(this.path+=`&consistency=${encodeURIComponent(s.consistency)}`),this.writeOptions={...se,...s},this.currentTime=ce[i],this.dateToProtocolTimestamp=de[i],this.writeOptions.defaultTags&&this.useDefaultTags(this.writeOptions.defaultTags),this.sendOptions={method:"POST",headers:{"content-type":"text/plain; charset=utf-8",...s==null?void 0:s.headers},gzipThreshold:this.writeOptions.gzipThreshold};let o=()=>{this.writeOptions.flushInterval>0&&(this._clearFlushTimeout(),this.closed||(this._timeoutHandle=setTimeout(()=>this.sendBatch(this.writeBuffer.reset(),this.writeOptions.maxRetries).catch(a=>{}),this.writeOptions.flushInterval)))};this.writeBuffer=new Y(this.writeOptions.batchSize,this.writeOptions.maxBatchBytes,a=>(this._clearFlushTimeout(),this.sendBatch(a,this.writeOptions.maxRetries)),o),this.sendBatch=this.sendBatch.bind(this),this.retryStrategy=xe(this.writeOptions),this.retryBuffer=new v(this.writeOptions.maxBufferLines,this.sendBatch,this.writeOptions.writeRetrySkipped)}sendBatch(e,t,n=Date.now()+this.writeOptions.maxRetryTime){let i=this,s=i.writeOptions.maxRetries+1-t;if(!this.closed&&e.length>0){if(n<=Date.now()){let o=new Error("Max retry time exceeded."),a=i.writeOptions.writeFailed.call(i,o,e,s,n);return a||(p.error(`Write to InfluxDB failed (attempt: ${s}).`,o),Promise.reject(o))}return new Promise((o,a)=>{let f,u={responseStarted(l,c){f=c},error(l){let c=i.writeOptions.writeFailed.call(i,l,e,s,n);if(c){c.then(o,a);return}if(l instanceof m&&l.json&&typeof l.json.error=="string"&&l.json.error.includes("hinted handoff queue not empty")){p.warn("Write to InfluxDB returns: "+l.json.error),f=204,u.complete();return}if(!i.closed&&t>0&&(!(l instanceof m)||l.statusCode>=429)){p.warn(`Write to InfluxDB failed (attempt: ${s}).`,l),i.retryBuffer.addLines(e,t-1,i.retryStrategy.nextDelay(l,s),n),a(l);return}p.error("Write to InfluxDB failed.",l),a(l)},complete(){if(f==204||f==null)i.writeOptions.writeSuccess.call(i,e),i.retryStrategy.success(),o();else{let l=`204 HTTP response status code expected, but ${f} returned`,c=new m(f,l,void 0,"0");c.message=l,u.error(c)}}};this.transport.send(this.path,e.join(` +`),this.sendOptions,u)})}else return Promise.resolve()}_clearFlushTimeout(){this._timeoutHandle!==void 0&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0)}writeRecord(e){if(this.closed)throw new Error("writeApi: already closed!");this.writeBuffer.add(e)}writeRecords(e){if(this.closed)throw new Error("writeApi: already closed!");for(let t=0;t{let t=this.retryBuffer.close();t&&p.error(`Retry buffer closed with ${t} items that were not written to InfluxDB!`,null),this.closed=!0})}dispose(){return this._clearFlushTimeout(),this.closed=!0,this.retryBuffer.close()+this.writeBuffer.length}useDefaultTags(e){return this.defaultTags=e,this}convertTime(e){return e===void 0?this.currentTime():typeof e=="string"?e.length>0?e:void 0:e instanceof Date?this.dateToProtocolTimestamp(e):String(typeof e=="number"?Math.floor(e):e)}};function Z(r={}){let e=0,t={next:n=>{if(e===0&&r.next&&n!==null&&n!==void 0)return r.next(n)},error:n=>{e===0&&(e=1,r.error&&r.error(n))},complete:()=>{e===0&&(e=2,r.complete&&r.complete())},responseStarted:(n,i)=>{r.responseStarted&&r.responseStarted(n,i)}};return r.useCancellable&&(t.useCancellable=r.useCancellable.bind(r)),r.useResume&&(t.useResume=r.useResume.bind(r)),t}function we(r){let e={};return r.headers.forEach((t,n)=>{let i=e[n];i===void 0?e[n]=t:Array.isArray(i)?i.push(t):e[n]=[i,t]}),e}var D=class{constructor(e){this.connectionOptions=e;this.chunkCombiner=b();this.requestDecorator=function(){};this.defaultHeaders={"content-type":"application/json; charset=utf-8",...e.headers},this.connectionOptions.token&&(this.defaultHeaders.Authorization="Token "+this.connectionOptions.token),this.url=String(this.connectionOptions.url),this.url.endsWith("/")&&(this.url=this.url.substring(0,this.url.length-1)),this.url.endsWith("/api/v2")&&(this.url=this.url.substring(0,this.url.length-7),p.warn(`Please remove '/api/v2' context path from InfluxDB base url, using ${this.url} !`))}send(e,t,n,i){let s=Z(i),o=!1,a=n.signal,f,u=()=>{},l=u;if(i&&i.useCancellable){let c=new AbortController;a||(a=c.signal,n={...n,signal:a}),a.addEventListener("abort",()=>{l()}),i.useCancellable({cancel(){o=!0,c.abort()},isCancelled(){return o||a.aborted}})}this.fetch(e,t,n).then(async c=>{if(i!=null&&i.responseStarted&&s.responseStarted(we(c),c.status),await this.throwOnErrorResponse(c),c.body){let d=c.body.getReader(),g;do{if(f&&await f,o)break;if(g=await d.read(),s.next(g.value)===!1){let P=s.useResume;if(!P){let F="Unable to pause, useResume is not configured!";return await d.cancel(F),Promise.reject(new Error(F))}f=new Promise(F=>{l=()=>{F(),f=void 0,l=u},P(l)})}}while(!g.done)}else if(c.arrayBuffer){let d=await c.arrayBuffer();s.next(new Uint8Array(d))}else{let d=await c.text();s.next(new TextEncoder().encode(d))}}).catch(c=>{o||s.error(c)}).finally(()=>s.complete())}async throwOnErrorResponse(e){if(e.status>=300){let t="";try{if(t=await e.text(),!t){let n=e.headers.get("x-influxdb-error");n&&(t=n)}}catch(n){throw p.warn("Unable to receive error body",n),new m(e.status,e.statusText,void 0,e.headers.get("retry-after"),e.headers.get("content-type"))}throw new m(e.status,e.statusText,t,e.headers.get("retry-after"),e.headers.get("content-type"))}}async*iterate(e,t,n){var s;let i=await this.fetch(e,t,n);if(await this.throwOnErrorResponse(i),i.body){let o=i.body.getReader();for(;;){let{value:a,done:f}=await o.read();if(f)break;if((s=n.signal)!=null&&s.aborted)throw await i.body.cancel(),new w;yield a}}else if(i.arrayBuffer){let o=await i.arrayBuffer();yield new Uint8Array(o)}else{let o=await i.text();yield new TextEncoder().encode(o)}}async request(e,t,n,i){var u,l;let s=await this.fetch(e,t,n),{headers:o}=s,a=o.get("content-type")||"";i&&i(we(s),s.status),await this.throwOnErrorResponse(s);let f=(l=(u=n.headers)==null?void 0:u.accept)!=null?l:a;if(f.includes("json"))return await s.json();if(f.includes("text")||f.startsWith("application/csv"))return await s.text()}fetch(e,t,n){let{method:i,headers:s,...o}=n,a=`${this.url}${e}`,f={method:i,body:i==="GET"||i==="HEAD"?void 0:typeof t=="string"?t:JSON.stringify(t),headers:{...this.defaultHeaders,...s},credentials:"omit",...this.connectionOptions.transportOptions,...o};return this.requestDecorator(f,n,a),fetch(a,f)}};var Te={header:!0,delimiter:",",quoteChar:'"',commentPrefix:"#",annotations:["datatype","group","default"]},E=class{constructor(e,t,n){this.transport=e;this.createCSVResponse=t;this.options=typeof n=="string"?{org:n}:n}with(e){return new E(this.transport,this.createCSVResponse,{...this.options,...e})}response(e){let{org:t,type:n,gzip:i,headers:s}=this.options,o=`/api/v2/query?org=${encodeURIComponent(t)}`,a=JSON.stringify(this.decorateRequest({query:e.toString(),dialect:Te,type:n})),f={method:"POST",headers:{"content-type":"application/json; encoding=utf-8","accept-encoding":i?"gzip":"identity",...s}};return this.createCSVResponse(u=>this.transport.send(o,a,f,u),()=>this.transport.iterate(o,a,f))}iterateLines(e){return this.response(e).iterateLines()}iterateRows(e){return this.response(e).iterateRows()}lines(e){return this.response(e).lines()}rows(e){return this.response(e).rows()}queryLines(e,t){return this.response(e).consumeLines(t)}queryRows(e,t){return this.response(e).consumeRows(t)}collectRows(e,t){return this.response(e).collectRows(t)}collectLines(e){return this.response(e).collectLines()}queryRaw(e){let{org:t,type:n,gzip:i,headers:s}=this.options;return this.transport.request(`/api/v2/query?org=${encodeURIComponent(t)}`,JSON.stringify(this.decorateRequest({query:e.toString(),dialect:Te,type:n})),{method:"POST",headers:{accept:"text/csv","accept-encoding":i?"gzip":"identity","content-type":"application/json; encoding=utf-8",...s}})}decorateRequest(e){var t;return typeof this.options.now=="function"&&(e.now=this.options.now()),e.type=(t=this.options.type)!=null?t:"flux",e}},Re=E;function Ie(r,e){return e.toObject(r)}var _=class{constructor(e,t,n){this.executor=e;this.iterableResultExecutor=t;this.chunkCombiner=n}iterateLines(){return z(this.iterableResultExecutor())}iterateRows(){return re(z(this.iterableResultExecutor()))}lines(){return new T(this.executor,e=>C(e,this.chunkCombiner))}rows(){return new T(this.executor,e=>C(k({next(t,n){e.next({values:t,tableMeta:n})},error(t){e.error(t)},complete(){e.complete()}}),this.chunkCombiner))}consumeLines(e){this.executor(C(e,this.chunkCombiner))}consumeRows(e){this.executor(C(k(e),this.chunkCombiner))}collectRows(e=Ie){let t=[];return new Promise((n,i)=>{this.consumeRows({next(s,o){let a=e.call(this,s,o);a!==void 0&&t.push(a)},error(s){i(s)},complete(){n(t)}})})}collectLines(){let e=[];return new Promise((t,n)=>{this.consumeLines({next(i){e.push(i)},error(i){n(i)},complete(){t(e)}})})}};var V=class{constructor(e){var n;if(typeof e=="string")this._options={url:e};else if(e!==null&&typeof e=="object")this._options=e;else throw new y("No url or configuration specified!");let t=this._options.url;if(typeof t!="string")throw new y("No url specified!");t.endsWith("/")&&(this._options.url=t.substring(0,t.length-1)),this.transport=(n=this._options.transport)!=null?n:new D(this._options),this.processCSVResponse=(i,s)=>new _(i,s,this.transport.chunkCombiner)}getWriteApi(e,t,n="ns",i){return new A(this.transport,e,t,n,i!=null?i:this._options.writeOptions)}getQueryApi(e){return new Re(this.transport,this.processCSVResponse,e)}};export{w as AbortError,Nt as DEFAULT_ConnectionOptions,ie as DEFAULT_RetryDelayStrategyOptions,se as DEFAULT_WriteOptions,M as FLUX_VALUE,m as HttpError,y as IllegalArgumentError,V as InfluxDB,x as LineSplitter,p as Log,be as Point,U as RequestTimedOutError,ee as UNKNOWN_COLUMN,Ne as canRetryHttpCall,C as chunksToLines,z as chunksToLinesIterable,Ee as consoleLogger,me as convertTimeToNanos,We as createFluxTableColumn,$ as createFluxTableMetaData,b as createTextDecoderCombiner,ce as currentTime,de as dateToProtocolTimestamp,R as escape,nr as flux,rr as fluxBool,Zt as fluxDateTime,er as fluxDuration,pe as fluxExpression,Kt as fluxFloat,Yt as fluxInteger,tr as fluxRegExp,Gt as fluxString,te as getRetryDelay,Oe as isStatusCodeRetriable,re as linesToRowsIterable,k as linesToTables,I as newFluxTableColumn,he as sanitizeFloat,ye as sanitizeInteger,Xe as serializeDateTimeAsDate,Ge as serializeDateTimeAsNumber,Ke as serializeDateTimeAsString,Jt as setLogger,pt as stringToLines,ne as symbolObservable,X as toFluxValue,O as typeSerializers,De as useProcessHrtime}; +//# sourceMappingURL=index.browser.mjs.map \ No newline at end of file diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.mjs.gz b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.browser.mjs.gz new file mode 100644 index 0000000000000000000000000000000000000000..6772a3c0799787b7fedf434529bf59ff0e2dcfd6 GIT binary patch literal 9593 zcmV-$(MYRPkG^crJSuj^MX;qWm#m4NuEt&>2oGkkBoY}Pcr#zt0>}YpAS-=oy&{9 z)IUtuUN#UMdIn7WkjylNl8R08`89%NnF5@&0cUH{f=U#qfhf;ns>E&qODZPw_j2~^ zP!>scZouhI#b8R4TIyF-)yz<0+btb((G#~-VTr-Juz%#BB@t3J$F1fxm6UjewOMRJ_cBw*PPlqn6uEc%ou z)7}ukA-=_+6#RgT@)GFkeE5D4Z7ztAGrzUgLs%5E*i|{;MS%o`Haqmod!NN;DeuX= zH;(}z>shG1MD(&8)*;Vk$$44u>52!Ofx}cW%q50}j5UHmg>)>V1(7FJ)J+0eTpO0b zWo0XQ1?x1q@F&4SUL-=JGYKlyYGqh4RfHgJZhT;qAu9%^EI{VIoWoe$R}He&)$TRP z*pL|>L4H<%>fXSrBg@S&=j}L~@H9nYz}(7KQIrCKm)o^V{KbSmPzDUlPi9xKbjGh( zB6Lqa_3h3|2aV#Yg4JWrQXAaV7oinLDYPl8SX^h5p4mtL`twWM54Tn?{v0Q;V9-eP z@>#D?9dcM$yY=$O?ls}=H354qhi3V6(cEjZNF3+1*JjRMOH^eU<+#_Nh23lLE6hjN z2~VfJ)+!1Xvl7`X@2~5NRv)RKixnTEOb9P$iX2e~QzR3qWY8j0CpY zzd*i#xnuI`b0RMeI)>CZ4XJr0=4m3|BpHni3&0~{fxztn)02nPP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P*6m%ZN6%MQDc~d%_%feXK;jn zqn4u)8ek82r&+u_DfP4tUL7gq0vv78tDkLVdlCy??(A;8e{=NPcH3iN33u!3yC3Fw z-n0{qb|0KMu(w!Kzth7m@!LMk&aUyZ>pgz<6V>RLFuTGp+=ldaCRp)H5rR-}DYJVWRj3PqMT zduEuCO%&Yv$Pau%EVO{Wt`Z7Lt0KfqieAD1(kk0(`C?=~wr{_Ngophc;P; zGP7tU3aTT$ew3q9v1|0vsUW%v_8N;|E45eQf`EuPOJwq=y5`HS8)aq!KdVv>qo+`8 zNVFyJ7yJIUT6KGz{dilwp8O9|)l1D%bM;M?hAT4#gI>ehw+}b6pRrWtyXMs@woe5h jun)~}g,\n chunkCombiner?: ChunkCombiner\n): CommunicationObserver {\n const chunks = chunkCombiner ?? createTextDecoderCombiner()\n let previous: Uint8Array | undefined\n let finished = false\n let quoted = false\n let paused = false\n let resumeChunks: (() => void) | undefined\n\n function bufferReceived(chunk: Uint8Array): void {\n let index: number\n let start = 0\n if (previous) {\n // inspect the whole remaining data upon empty chunk\n // empty chunk signalizes to restart of receiving\n index = chunk.length === 0 ? 0 : (previous as Uint8Array).length\n chunk = chunks.concat(previous, chunk)\n } else {\n index = 0\n }\n while (index < chunk.length) {\n const c = chunk[index]\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n // do not emmit more lines if the processing is already finished\n if (finished) {\n return\n }\n paused = target.next(chunks.toUtf8String(chunk, start, end)) === false\n start = index + 1\n if (paused) {\n break\n }\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < chunk.length) {\n previous = chunks.copy(chunk, start, chunk.length)\n } else {\n previous = undefined\n }\n if (paused) {\n if (target.useResume) {\n target.useResume(() => {\n paused = false\n bufferReceived(new Uint8Array(0))\n })\n return\n }\n retVal.error(new Error('Unable to pause, useResume is not configured!'))\n paused = false // consume remaining data\n }\n if (resumeChunks) {\n resumeChunks()\n resumeChunks = undefined\n }\n }\n\n const retVal: CommunicationObserver = {\n next(chunk: Uint8Array): boolean {\n if (!finished) {\n try {\n bufferReceived(chunk)\n return !paused\n } catch (e) {\n this.error(e as Error)\n }\n }\n return true\n },\n error(error: Error): void {\n if (!finished) {\n finished = true\n target.error(error)\n }\n },\n complete(): void {\n if (!finished) {\n if (previous) {\n target.next(chunks.toUtf8String(previous, 0, previous.length))\n }\n finished = true\n target.complete()\n }\n },\n }\n if (target.useCancellable) {\n retVal.useCancellable = (cancellable: Cancellable) => {\n target.useCancellable &&\n target.useCancellable({\n cancel(): void {\n cancellable.cancel()\n previous = undefined // do not emit more lines\n retVal.complete()\n },\n isCancelled(): boolean {\n return cancellable.isCancelled()\n },\n })\n }\n }\n if (target.useResume) {\n retVal.useResume = (x: () => void) => {\n resumeChunks = x\n }\n }\n\n return retVal\n}\n","import {ChunkCombiner, createTextDecoderCombiner} from './chunkCombiner'\n\n/**\n * ChunksToLinesIterable is a transformation that accepts\n * an iterable of Uint8Array instances and returns iterable of lines.\n * @param source - iterable of transport buffers\n * @param chunkCombiner - chunk combiner\n * @returns iterable of lines\n */\nexport async function* chunksToLinesIterable(\n source: AsyncIterable,\n chunkCombiner?: ChunkCombiner\n): AsyncIterableIterator {\n const chunks = chunkCombiner ?? createTextDecoderCombiner()\n let previous: Uint8Array | undefined\n let quoted = false\n\n for await (let chunk of source) {\n let index: number\n let start = 0\n if (previous) {\n index = previous.length\n chunk = chunks.concat(previous, chunk)\n } else {\n index = 0\n }\n while (index < chunk.length) {\n const c = chunk[index]\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n yield chunks.toUtf8String(chunk, start, end)\n start = index + 1\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < chunk.length) {\n previous = chunks.copy(chunk, start, chunk.length)\n } else {\n previous = undefined\n }\n }\n if (previous) {\n yield chunks.toUtf8String(previous, 0, previous.length)\n }\n}\n","/**\n * Optimized tokenizer of a single CSV line.\n */\nexport class LineSplitter {\n /** returned value when reused */\n reusedValues: string[]\n /** last length of elements in */\n lastSplitLength: number\n private _reuse = false\n\n /**\n * Reuse returned array between consecutive calls.\n */\n get reuse(): boolean {\n return this._reuse\n }\n set reuse(val: boolean) {\n if (val && !this.reusedValues) {\n this.reusedValues = new Array(10)\n }\n this._reuse = val\n }\n\n /**\n * Sets the reuse flag and returns this.\n */\n withReuse(): LineSplitter {\n this.reuse = true\n return this\n }\n\n /**\n * Splits the supplied line to elements that are separated by\n * comma with values possibly escaped within double quotes (\"value\")\n * @param line - line\n * @returns array of splitted parts\n */\n splitLine(line: string | undefined | null): string[] {\n if (line === null || line === undefined) {\n this.lastSplitLength = 0\n return []\n }\n let quoteCount = 0\n let startIndex = 0\n const values = this._reuse ? this.reusedValues : []\n let count = 0\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (c === ',') {\n if (quoteCount % 2 === 0) {\n const val = this.getValue(line, startIndex, i, quoteCount)\n if (this._reuse) {\n values[count++] = val\n } else {\n values.push(val)\n }\n startIndex = i + 1\n quoteCount = 0\n }\n } else if (c === '\"') {\n quoteCount++\n }\n }\n const val = this.getValue(line, startIndex, line.length, quoteCount)\n if (this._reuse) {\n values[count] = val\n this.lastSplitLength = count + 1\n } else {\n values.push(val)\n this.lastSplitLength = values.length\n }\n\n return values\n }\n\n private getValue(\n line: string,\n start: number,\n end: number,\n quoteCount: number\n ): string {\n if (start === line.length) {\n return ''\n } else if (quoteCount === 0) {\n return line.substring(start, end)\n } else if (quoteCount === 2) {\n return line.substring(start + 1, end - 1)\n } else {\n // quoteCount >= 4\n return line.substring(start + 1, end - 1).replace(/\"\"/gi, '\"')\n }\n }\n}\n","/**\n * Type of query result column, see {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport type ColumnType =\n | 'boolean'\n | 'unsignedLong'\n | 'long'\n | 'double'\n | 'string'\n | 'base64Binary'\n | 'dateTime:RFC3339'\n | 'duration'\n | string\n\n/**\n * FluxTableColumn describes {@link http://bit.ly/flux-spec#table | flux table} column.\n */\nexport interface FluxTableColumn {\n /**\n * Label (e.g., \"_start\", \"_stop\", \"_time\").\n */\n label: string\n\n /**\n * The data type of column (e.g., \"string\", \"long\", \"dateTime:RFC3339\").\n */\n dataType: ColumnType\n\n /**\n * Boolean flag indicating if the column is a part of the table's group key.\n */\n group: boolean\n\n /**\n * Default value to be used for rows whose string value is an empty string.\n */\n defaultValue: string\n\n /**\n * Index of this column in a row array.\n */\n index: number\n\n /**\n * Get returns a JavaScript object of this column in the supplied result row, using default deserializers.\n * @param row - a data row\n * @returns column value\n */\n get: (row: string[]) => any\n}\n\nconst identity = (x: string): any => x\n\n/**\n * A dictionary of serializers of particular types returned by a flux query.\n * See {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport const typeSerializers: Record any> = {\n boolean: (x: string): any => (x === '' ? null : x === 'true'),\n unsignedLong: (x: string): any => (x === '' ? null : +x),\n long: (x: string): any => (x === '' ? null : +x),\n double(x: string): any {\n switch (x) {\n case '':\n return null\n case '+Inf':\n return Number.POSITIVE_INFINITY\n case '-Inf':\n return Number.NEGATIVE_INFINITY\n default:\n return +x\n }\n },\n string: identity,\n base64Binary: identity,\n duration: (x: string): any => (x === '' ? null : x),\n 'dateTime:RFC3339': (x: string): any => (x === '' ? null : x),\n}\n\n/**\n * FluxTableColumn implementation.\n */\nclass FluxTableColumnImpl implements FluxTableColumn {\n label: string\n dataType: ColumnType\n group: boolean\n defaultValue: string\n index: number\n public get(row: string[]): any {\n let val = row[this.index]\n if ((val === '' || val === undefined) && this.defaultValue) {\n val = this.defaultValue\n }\n return (typeSerializers[this.dataType] ?? identity)(val)\n }\n}\nexport const UNKNOWN_COLUMN: FluxTableColumn = Object.freeze({\n label: '',\n dataType: '',\n group: false,\n defaultValue: '',\n index: Number.MAX_SAFE_INTEGER,\n get: () => undefined,\n})\n\n/**\n * Creates a new flux table column.\n * @returns column instance\n */\nexport function newFluxTableColumn(): FluxTableColumn {\n return new FluxTableColumnImpl()\n}\n\n/**\n * Creates a flux table column from a partial FluxTableColumn.\n * @param object - source object\n * @returns column instance\n */\nexport function createFluxTableColumn(\n object: Partial\n): FluxTableColumn {\n const retVal = new FluxTableColumnImpl()\n retVal.label = String(object.label)\n retVal.dataType = object.dataType as ColumnType\n retVal.group = Boolean(object.group)\n retVal.defaultValue = object.defaultValue ?? ''\n retVal.index = object.index ?? 0\n return retVal\n}\n","/**\n * Strategy for calculating retry delays.\n */\nexport interface RetryDelayStrategy {\n /**\n * Returns delay for a next retry\n * @param error - reason for retrying\n * @param failedAttempts - a count of already failed attempts, 1 being the first\n * @returns milliseconds to wait before retrying\n */\n nextDelay(error?: Error, failedAttempts?: number): number\n /** Implementation should reset its state, this is mandatory to call upon success. */\n success(): void\n}\n\n/**\n * Interface for errors to inform that an associated operation can be retried.\n */\nexport interface RetriableDecision {\n /**\n * Informs whether this can be retried.\n */\n canRetry(): boolean\n /**\n * Get the delay in milliseconds to retry the action.\n * @returns 0 to let the implementation decide, miliseconds delay otherwise\n */\n retryAfter(): number\n}\n\nconst retriableStatusCodes = [404, 408, 425, 429, 500, 502, 503, 504]\n/** isStatusCodeRetriable checks whether the supplied HTTP status code is retriable. */\nexport function isStatusCodeRetriable(statusCode: number): boolean {\n return retriableStatusCodes.includes(statusCode)\n}\n\n/** IllegalArgumentError is thrown when illegal argument is supplied. */\nexport class IllegalArgumentError extends Error {\n /* istanbul ignore next */\n constructor(message: string) {\n super(message)\n this.name = 'IllegalArgumentError'\n Object.setPrototypeOf(this, IllegalArgumentError.prototype)\n }\n}\n\n/**\n * A general HTTP error.\n */\nexport class HttpError extends Error implements RetriableDecision {\n private _retryAfter: number\n /** application error code, when available */\n public code: string | undefined\n /** json error response */\n public json: any\n\n /* istanbul ignore next because of super() not being covered*/\n constructor(\n readonly statusCode: number,\n readonly statusMessage: string | undefined,\n readonly body?: string,\n retryAfter?: string | undefined | null,\n readonly contentType?: string | undefined | null,\n message?: string\n ) {\n super()\n Object.setPrototypeOf(this, HttpError.prototype)\n if (message) {\n this.message = message\n } else if (body) {\n if (contentType?.startsWith('application/json')) {\n try {\n this.json = JSON.parse(body)\n this.message = this.json.message\n this.code = this.json.code\n } catch (e) {\n // silently ignore, body string is still available\n }\n }\n if (!this.message) {\n this.message = `${statusCode} ${statusMessage} : ${body}`\n }\n } else {\n this.message = `${statusCode} ${statusMessage}`\n }\n this.name = 'HttpError'\n this.setRetryAfter(retryAfter)\n }\n\n private setRetryAfter(retryAfter?: string | undefined | null): void {\n if (typeof retryAfter === 'string') {\n // try to parse the supplied number as milliseconds\n if (/^[0-9]+$/.test(retryAfter)) {\n this._retryAfter = parseInt(retryAfter)\n } else {\n this._retryAfter = 0\n }\n } else {\n this._retryAfter = 0\n }\n }\n\n canRetry(): boolean {\n return isStatusCodeRetriable(this.statusCode)\n }\n retryAfter(): number {\n return this._retryAfter\n }\n}\n\n//see https://nodejs.org/api/errors.html\nconst RETRY_CODES = [\n 'ECONNRESET',\n 'ENOTFOUND',\n 'ESOCKETTIMEDOUT',\n 'ETIMEDOUT',\n 'ECONNREFUSED',\n 'EHOSTUNREACH',\n 'EPIPE',\n]\n\n/**\n * Tests the error in order to know if an HTTP call can be retried.\n * @param error - error to test\n * @returns true for a retriable error\n */\nexport function canRetryHttpCall(error: any): boolean {\n if (!error) {\n return false\n } else if (typeof (error as any).canRetry === 'function') {\n return !!((error as any).canRetry as () => boolean)()\n } else if ((error as any).code && RETRY_CODES.includes((error as any).code)) {\n return true\n }\n return false\n}\n\n/**\n * Gets retry delay from the supplied error, possibly using random number up to retryJitter.\n */\nexport function getRetryDelay(error?: Error, retryJitter?: number): number {\n if (!error) {\n return 0\n } else {\n let retVal\n if (typeof (error as any).retryAfter === 'function') {\n return ((error as any).retryAfter as () => number)()\n } else {\n retVal = 0\n }\n if (retryJitter && retryJitter > 0) {\n return retVal + Math.round(Math.random() * retryJitter)\n } else {\n return retVal\n }\n }\n}\n\n/** RequestTimedOutError indicates request timeout in the communication with the server */\nexport class RequestTimedOutError extends Error implements RetriableDecision {\n /* istanbul ignore next because of super() not being covered */\n constructor() {\n super()\n Object.setPrototypeOf(this, RequestTimedOutError.prototype)\n this.name = 'RequestTimedOutError'\n this.message = 'Request timed out'\n }\n canRetry(): boolean {\n return true\n }\n retryAfter(): number {\n return 0\n }\n}\n\n/** AbortError indicates that the communication with the server was aborted */\nexport class AbortError extends Error implements RetriableDecision {\n /* istanbul ignore next because of super() not being covered */\n constructor() {\n super()\n this.name = 'AbortError'\n Object.setPrototypeOf(this, AbortError.prototype)\n this.message = 'Response aborted'\n }\n canRetry(): boolean {\n return true\n }\n retryAfter(): number {\n return 0\n }\n}\n","import {\n FluxTableColumn,\n UNKNOWN_COLUMN,\n typeSerializers,\n} from './FluxTableColumn'\nimport {IllegalArgumentError} from '../errors'\n\n/**\n * serializeDateTimeAsDate changes type serializers to return JavaScript Date instances\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsDate(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : new Date(Date.parse(x))\n}\n/**\n * serializeDateTimeAsNumber changes type serializers to return milliseconds since epoch\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsNumber(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : Date.parse(x)\n}\n/**\n * serializeDateTimeAsString changes type serializers to return string values\n * for `dateTime:RFC3339` query result data type. Empty value is converted to null.\n */\nexport function serializeDateTimeAsString(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : x\n}\n\n/**\n * Represents metadata of a {@link http://bit.ly/flux-spec#table | flux table}.\n */\nexport interface FluxTableMetaData {\n /**\n * Table columns.\n */\n columns: Array\n\n /**\n * Gets columns by name\n * @param label - column label\n * @param errorOnMissingColumn - throw error on missing column (by default), return UNKNOWN_COLUMN when false\n * @returns table column\n * @throws IllegalArgumentError if column is not found\n **/\n column(label: string, errorOnMissingColumn?: boolean): FluxTableColumn\n\n /**\n * Creates an object out of the supplied row with the help of column descriptors.\n * @param row - a row with data for each column\n */\n toObject(row: string[]): {[key: string]: any}\n\n /**\n * Gets column values out of the supplied row.\n * @param row - a row with data for each column\n * @param column - column name\n * @returns column value, undefined for unknown column\n */\n get(row: string[], column: string): any\n}\n\n/**\n * FluxTableMetaData Implementation.\n */\nclass FluxTableMetaDataImpl implements FluxTableMetaData {\n columns: Array\n constructor(columns: FluxTableColumn[]) {\n columns.forEach((col, i) => (col.index = i))\n this.columns = columns\n }\n column(label: string, errorOnMissingColumn = true): FluxTableColumn {\n for (let i = 0; i < this.columns.length; i++) {\n const col = this.columns[i]\n if (col.label === label) return col\n }\n if (errorOnMissingColumn) {\n throw new IllegalArgumentError(`Column ${label} not found!`)\n }\n return UNKNOWN_COLUMN\n }\n toObject(row: string[]): {[key: string]: any} {\n const acc: any = {}\n for (let i = 0; i < this.columns.length && i < row.length; i++) {\n const column = this.columns[i]\n acc[column.label] = column.get(row)\n }\n return acc\n }\n get(row: string[], column: string): any {\n return this.column(column, false).get(row)\n }\n}\n\n/**\n * Created FluxTableMetaData from the columns supplied.\n * @param columns - columns\n * @returns - instance\n */\nexport function createFluxTableMetaData(\n columns: FluxTableColumn[]\n): FluxTableMetaData {\n return new FluxTableMetaDataImpl(columns)\n}\n\n/** Wraps values and associated metadata of a query result row */\nexport interface Row {\n values: string[]\n tableMeta: FluxTableMetaData\n}\n","import {CommunicationObserver} from './CommunicationObserver'\nimport {LineSplitter} from './LineSplitter'\nimport {FluxResultObserver} from './FluxResultObserver'\nimport {\n FluxTableColumn,\n ColumnType,\n newFluxTableColumn,\n} from './FluxTableColumn'\nimport {FluxTableMetaData, createFluxTableMetaData} from './FluxTableMetaData'\n\n/**\n * LinesToTables creates a transformation that accepts (flux) annotated CSV lines\n * and emits rows together with table metadata.\n */\nexport function linesToTables(\n consumer: FluxResultObserver\n): CommunicationObserver {\n const splitter = new LineSplitter().withReuse()\n let columns: FluxTableColumn[] | undefined\n let expectMeta = true\n let firstColumnIndex = 0\n let lastMeta: FluxTableMetaData\n const retVal: CommunicationObserver = {\n error(error: Error): void {\n consumer.error(error)\n },\n next(line: string): void | boolean {\n if (line === '') {\n expectMeta = true\n columns = undefined\n } else {\n const values = splitter.splitLine(line)\n const size = splitter.lastSplitLength\n if (expectMeta) {\n // create columns\n if (!columns) {\n columns = new Array(size)\n for (let i = 0; i < size; i++) {\n columns[i] = newFluxTableColumn()\n }\n }\n if (!values[0].startsWith('#')) {\n // fill in column names\n if (values[0] === '') {\n firstColumnIndex = 1\n columns = columns.slice(1)\n } else {\n firstColumnIndex = 0\n }\n for (let i = firstColumnIndex; i < size; i++) {\n columns[i - firstColumnIndex].label = values[i]\n }\n lastMeta = createFluxTableMetaData(columns)\n expectMeta = false\n } else if (values[0] === '#datatype') {\n for (let i = 1; i < size; i++) {\n columns[i].dataType = values[i] as ColumnType\n }\n } else if (values[0] === '#default') {\n for (let i = 1; i < size; i++) {\n columns[i].defaultValue = values[i]\n }\n } else if (values[0] === '#group') {\n for (let i = 1; i < size; i++) {\n columns[i].group = values[i][0] === 't'\n }\n }\n } else {\n return consumer.next(values.slice(firstColumnIndex, size), lastMeta)\n }\n }\n return true\n },\n complete(): void {\n consumer.complete()\n },\n }\n if (consumer.useCancellable) {\n retVal.useCancellable = consumer.useCancellable.bind(consumer)\n }\n if (consumer.useResume) {\n retVal.useResume = consumer.useResume.bind(consumer)\n }\n return retVal\n}\n","import {LineSplitter} from './LineSplitter'\nimport {\n FluxTableColumn,\n ColumnType,\n newFluxTableColumn,\n} from './FluxTableColumn'\nimport {\n FluxTableMetaData,\n createFluxTableMetaData,\n Row,\n} from './FluxTableMetaData'\n\n/**\n * LinesToRowsIterable is a transformation that accepts\n * an iterable of flux annotated CSV lines and returns\n * an iterable of rows (row values and table metadata).\n */\nexport async function* linesToRowsIterable(\n source: AsyncIterable\n): AsyncIterableIterator {\n const splitter = new LineSplitter().withReuse()\n let columns: FluxTableColumn[] | undefined\n let expectMeta = true\n let firstColumnIndex = 0\n let lastMeta: FluxTableMetaData | undefined = undefined\n for await (const line of source) {\n if (line === '') {\n expectMeta = true\n columns = undefined\n } else {\n const values = splitter.splitLine(line)\n const size = splitter.lastSplitLength\n if (expectMeta) {\n // create columns\n if (!columns) {\n columns = new Array(size)\n for (let i = 0; i < size; i++) {\n columns[i] = newFluxTableColumn()\n }\n }\n if (!values[0].startsWith('#')) {\n // fill in column names\n if (values[0] === '') {\n firstColumnIndex = 1\n columns = columns.slice(1)\n } else {\n firstColumnIndex = 0\n }\n for (let i = firstColumnIndex; i < size; i++) {\n columns[i - firstColumnIndex].label = values[i]\n }\n lastMeta = createFluxTableMetaData(columns)\n expectMeta = false\n } else if (values[0] === '#datatype') {\n for (let i = 1; i < size; i++) {\n columns[i].dataType = values[i] as ColumnType\n }\n } else if (values[0] === '#default') {\n for (let i = 1; i < size; i++) {\n columns[i].defaultValue = values[i]\n }\n } else if (values[0] === '#group') {\n for (let i = 1; i < size; i++) {\n columns[i].group = values[i][0] === 't'\n }\n }\n } else {\n yield {\n values: values.slice(firstColumnIndex, size),\n tableMeta:\n lastMeta as unknown as FluxTableMetaData /* never undefined */,\n }\n }\n }\n }\n}\n","import {CommunicationObserver} from './CommunicationObserver'\n\n/**\n * StringToLines is a transformation that emmits strings for each CSV\n * line in the supplied source string.\n * @param source - source string\n * @param target - target to emmit CSV lines to\n * @returns communication obrver to accept Uint8Arrays\n */\nexport function stringToLines(\n source: string,\n target: CommunicationObserver\n): void {\n let quoted = false\n let start = 0\n let index = 0\n\n while (index < source.length) {\n const c = source.charCodeAt(index)\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end =\n index > 0 && source.charCodeAt(index - 1) === 13 ? index - 1 : index\n // do not emmit more lines if the processing is already finished\n target.next(source.substring(start, end))\n start = index + 1\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < index) {\n target.next(source.substring(start, index))\n }\n target.complete()\n}\n","/* Observable interop typing. Taken from https://github.com/ReactiveX/rxjs */\n\n/* Note: This will add Symbol.observable globally for all TypeScript users */\ndeclare global {\n interface SymbolConstructor {\n readonly observable: symbol\n }\n}\n\n/** Symbol.observable or a string \"\\@\\@observable\". Used for interop */\nexport const symbolObservable = (():\n | typeof Symbol.observable\n | '@@observable' =>\n (typeof Symbol === 'function' && Symbol.observable) || '@@observable')()\n","import {\n Observable,\n Observer,\n ObserverComplete,\n ObserverError,\n ObserverNext,\n Subscription,\n symbolObservable,\n} from '../observable'\nimport {CommunicationObserver} from '../results/CommunicationObserver'\nimport {Cancellable} from '../results/Cancellable'\n\n/** APIExecutor executes the API and passes its response to the supplied consumer */\nexport type APIExecutor = (consumer: CommunicationObserver) => void\n\ntype Decorator = (observer: Observer) => Observer\n\nclass QuerySubscription implements Subscription {\n private cancellable?: Cancellable\n private isClosed = false\n\n public constructor(observer: Observer, executor: APIExecutor) {\n try {\n executor({\n next: (value) => {\n observer.next(value)\n },\n error: (e) => {\n this.isClosed = true\n observer.error(e)\n },\n complete: () => {\n this.isClosed = true\n observer.complete()\n },\n useCancellable: (c) => {\n this.cancellable = c\n },\n })\n } catch (e) {\n this.isClosed = true\n observer.error(e)\n }\n }\n\n public get closed(): boolean {\n return this.isClosed\n }\n\n public unsubscribe(): void {\n this.cancellable?.cancel()\n this.isClosed = true\n }\n}\n\nfunction noop(): void {}\n\nfunction completeObserver(observer: Partial>): Observer {\n const {next, error, complete} = observer\n\n return {\n next: next ? next.bind(observer) : noop,\n error: error ? error.bind(observer) : noop,\n complete: complete ? complete.bind(observer) : noop,\n }\n}\n\nexport default class ObservableQuery implements Observable {\n public constructor(\n private readonly executor: APIExecutor,\n private readonly decorator: Decorator\n ) {}\n\n public subscribe(\n observerOrNext?: Partial> | ObserverNext,\n error?: ObserverError,\n complete?: ObserverComplete\n ): Subscription {\n const observer = completeObserver(\n typeof observerOrNext !== 'object' || observerOrNext === null\n ? {next: observerOrNext, error, complete}\n : observerOrNext\n )\n\n return new QuerySubscription(this.decorator(observer), this.executor)\n }\n\n public [symbolObservable](): this {\n return this\n }\n\n // this makes sure we satisfy the interface, while using a possibly polyfilled\n // [symbolObservable] above for the actual implementation\n public declare [Symbol.observable]: () => this\n}\n","import {Transport} from './transport'\nimport WriteApi from './WriteApi'\n\n/**\n * Option for the communication with InfluxDB server.\n */\nexport interface ConnectionOptions {\n /** base URL */\n url: string\n /** authentication token */\n token?: string\n /**\n * socket timeout, 10000 milliseconds by default in node.js\n * @defaultValue 10000\n */\n timeout?: number\n /**\n * TransportOptions supply extra options for the transport layer, they differ between node.js and browser/deno.\n * Node.js transport accepts options specified in {@link https://nodejs.org/api/http.html#http_http_request_options_callback | http.request } or\n * {@link https://nodejs.org/api/https.html#https_https_request_options_callback | https.request }. For example, an `agent` property can be set to\n * {@link https://www.npmjs.com/package/proxy-http-agent | setup HTTP/HTTPS proxy }, {@link https://nodejs.org/api/tls.html#tls_tls_connect_options_callback | rejectUnauthorized }\n * property can disable TLS server certificate verification. Additionally,\n * {@link https://github.com/follow-redirects/follow-redirects | follow-redirects } property can be also specified\n * in order to follow redirects in node.js.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | fetch } is used under the hood in browser/deno.\n * For example,\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | redirect } property can be set to 'error' to abort request if a redirect occurs.\n */\n transportOptions?: {[key: string]: any}\n /**\n * Default HTTP headers to send with every request.\n */\n headers?: Record\n /**\n * Full HTTP web proxy URL including schema, for example http://your-proxy:8080.\n */\n proxyUrl?: string\n}\n\n/** default connection options */\nexport const DEFAULT_ConnectionOptions: Partial = {\n timeout: 10000,\n}\n\n/**\n * Options that configure strategy for retrying failed requests.\n */\nexport interface RetryDelayStrategyOptions {\n /** add `random(retryJitter)` milliseconds delay when retrying HTTP calls */\n retryJitter: number\n /** minimum delay when retrying write (milliseconds) */\n minRetryDelay: number\n /** maximum delay when retrying write (milliseconds) */\n maxRetryDelay: number\n /** base for the exponential retry delay */\n exponentialBase: number\n /**\n * randomRetry indicates whether the next retry delay is deterministic (false) or random (true).\n * The deterministic delay starts with `minRetryDelay * exponentialBase` and it is multiplied\n * by `exponentialBase` until it exceeds `maxRetryDelay`.\n * When random is `true`, the next delay is computed as a random number between next retry attempt (upper)\n * and the lower number in the deterministic sequence. `random(retryJitter)` is added to every returned value.\n */\n randomRetry: boolean\n}\n\n/**\n * Options that configure strategy for retrying failed InfluxDB write operations.\n */\nexport interface WriteRetryOptions extends RetryDelayStrategyOptions {\n /**\n * WriteFailed is called to inform about write errors.\n * @param this - the instance of the API that failed\n * @param error - write error\n * @param lines - failed lines\n * @param attempt - count of already failed attempts to write the lines (1 ... maxRetries+1)\n * @param expires - expiration time for the lines to be retried in millis since epoch\n * @returns a Promise to force the API to use it as a result of the flush operation,\n * void/undefined to continue with default retry mechanism\n */\n writeFailed(\n this: WriteApi,\n error: Error,\n lines: Array,\n attempt: number,\n expires: number\n ): Promise | void\n\n /**\n * WriteSuccess is informed about successfully written lines.\n * @param this - the instance of the API in use\n * @param lines - written lines\n */\n writeSuccess(this: WriteApi, lines: Array): void\n\n /**\n * WriteRetrySkipped is informed about lines that were removed from the retry buffer\n * to keep the size of the retry buffer under the configured limit (maxBufferLines).\n * @param entry - lines that were skipped\n */\n writeRetrySkipped(entry: {lines: Array; expires: number}): void\n\n /** max count of retries after the first write fails */\n maxRetries: number\n /** max time (millis) that can be spent with retries */\n maxRetryTime: number\n /** the maximum size of retry-buffer (in lines) */\n maxBufferLines: number\n}\n\n/**\n * Options used by {@link WriteApi} .\n */\nexport interface WriteOptions extends WriteRetryOptions {\n /** max number of records/lines to send in a batch */\n batchSize: number\n /** delay between data flushes in milliseconds, at most `batch size` records are sent during flush */\n flushInterval: number\n /** default tags, unescaped */\n defaultTags?: Record\n /** HTTP headers that will be sent with every write request */\n headers?: {[key: string]: string}\n /** When specified, write bodies larger than the threshold are gzipped */\n gzipThreshold?: number\n /** max size of a batch in bytes */\n maxBatchBytes: number\n /** InfluxDB Enterprise write consistency as explained in https://docs.influxdata.com/enterprise_influxdb/v1.9/concepts/clustering/#write-consistency */\n consistency?: 'any' | 'one' | 'quorum' | 'all'\n}\n\n/** default RetryDelayStrategyOptions */\nexport const DEFAULT_RetryDelayStrategyOptions = {\n retryJitter: 200,\n minRetryDelay: 5000,\n maxRetryDelay: 125000,\n exponentialBase: 5,\n randomRetry: true,\n}\n\n/** default writeOptions */\nexport const DEFAULT_WriteOptions: WriteOptions = {\n batchSize: 1000,\n maxBatchBytes: 50_000_000, // default max batch size in the cloud\n flushInterval: 60000,\n writeFailed: function () {},\n writeSuccess: function () {},\n writeRetrySkipped: function () {},\n maxRetries: 5,\n maxRetryTime: 180_000,\n maxBufferLines: 32_000,\n // a copy of DEFAULT_RetryDelayStrategyOptions, so that DEFAULT_WriteOptions could be tree-shaken\n retryJitter: 200,\n minRetryDelay: 5000,\n maxRetryDelay: 125000,\n exponentialBase: 2,\n gzipThreshold: 1000,\n randomRetry: true,\n}\n\n/**\n * Options used by {@link InfluxDB} .\n */\nexport interface ClientOptions extends ConnectionOptions {\n /** supplies and overrides default writing options */\n writeOptions?: Partial\n /** specifies custom transport */\n transport?: Transport\n}\n\n/**\n * Timestamp precision used in write operations.\n * See {@link https://docs.influxdata.com/influxdb/latest/api/#operation/PostWrite }\n */\nexport type WritePrecisionType = 'ns' | 'us' | 'ms' | 's'\n","function createEscaper(\n characters: string,\n replacements: string[]\n): (value: string) => string {\n return function (value: string): string {\n let retVal = ''\n let from = 0\n let i = 0\n while (i < value.length) {\n const found = characters.indexOf(value[i])\n if (found >= 0) {\n retVal += value.substring(from, i)\n retVal += replacements[found]\n from = i + 1\n }\n i++\n }\n if (from == 0) {\n return value\n } else if (from < value.length) {\n retVal += value.substring(from, value.length)\n }\n return retVal\n }\n}\nfunction createQuotedEscaper(\n characters: string,\n replacements: string[]\n): (value: string) => string {\n const escaper = createEscaper(characters, replacements)\n return (value: string): string => '\"' + escaper(value) + '\"'\n}\n\n/**\n * Provides functions escape specific parts in InfluxDB line protocol.\n */\nexport const escape = {\n /**\n * Measurement escapes measurement names.\n */\n measurement: createEscaper(', \\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\n', '\\\\r', '\\\\t']),\n /**\n * Quoted escapes quoted values, such as database names.\n */\n quoted: createQuotedEscaper('\"\\\\', ['\\\\\"', '\\\\\\\\']),\n\n /**\n * TagEscaper escapes tag keys, tag values, and field keys.\n */\n tag: createEscaper(', =\\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\=', '\\\\n', '\\\\r', '\\\\t']),\n}\n","declare let process: any\nconst zeroPadding = '000000000'\nlet useHrTime = false\n\nexport function useProcessHrtime(use: boolean): boolean {\n /* istanbul ignore else */\n if (!process.env.BUILD_BROWSER) {\n return (useHrTime = use && process && typeof process.hrtime === 'function')\n } else {\n return false\n }\n}\nuseProcessHrtime(true) // preffer node\n\nlet startHrMillis: number | undefined = undefined\nlet startHrTime: [number, number] | undefined = undefined\nlet lastMillis = Date.now()\nlet stepsInMillis = 0\nfunction nanos(): string {\n if (!process.env.BUILD_BROWSER && useHrTime) {\n const hrTime = process.hrtime() as [number, number]\n let millis = Date.now()\n if (!startHrTime) {\n startHrTime = hrTime\n startHrMillis = millis\n } else {\n hrTime[0] = hrTime[0] - startHrTime[0]\n hrTime[1] = hrTime[1] - startHrTime[1]\n // istanbul ignore next \"cannot mock system clock, manually reviewed\"\n if (hrTime[1] < 0) {\n hrTime[0] -= 1\n hrTime[1] += 1000_000_000\n }\n millis =\n (startHrMillis as number) +\n hrTime[0] * 1000 +\n Math.floor(hrTime[1] / 1000_000)\n }\n const nanos = String(hrTime[1] % 1000_000)\n return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n } else {\n const millis = Date.now()\n if (millis !== lastMillis) {\n lastMillis = millis\n stepsInMillis = 0\n } else {\n stepsInMillis++\n }\n const nanos = String(stepsInMillis)\n return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n }\n}\n\nfunction micros(): string {\n if (!process.env.BUILD_BROWSER && useHrTime) {\n const hrTime = process.hrtime() as [number, number]\n const micros = String(Math.trunc(hrTime[1] / 1000) % 1000)\n return (\n String(Date.now()) + zeroPadding.substr(0, 3 - micros.length) + micros\n )\n } else {\n return String(Date.now()) + zeroPadding.substr(0, 3)\n }\n}\nfunction millis(): string {\n return String(Date.now())\n}\nfunction seconds(): string {\n return String(Math.floor(Date.now() / 1000))\n}\n\n/**\n * Exposes functions that creates strings that represent a timestamp that\n * can be used in the line protocol. Micro and nano timestamps are emulated\n * depending on the js platform in use.\n */\nexport const currentTime = {\n s: seconds as () => string,\n ms: millis as () => string,\n us: micros as () => string,\n ns: nanos as () => string,\n seconds: seconds as () => string,\n millis: millis as () => string,\n micros: micros as () => string,\n nanos: nanos as () => string,\n}\n\n/**\n * dateToProtocolTimestamp provides converters for JavaScript Date to InfluxDB Write Protocol Timestamp. Keys are supported precisions.\n */\nexport const dateToProtocolTimestamp = {\n s: (d: Date): string => `${Math.floor(d.getTime() / 1000)}`,\n ms: (d: Date): string => `${d.getTime()}`,\n us: (d: Date): string => `${d.getTime()}000`,\n ns: (d: Date): string => `${d.getTime()}000000`,\n}\n\n/**\n * convertTimeToNanos converts Point's timestamp to a string.\n * @param value - supported timestamp value\n * @returns line protocol value\n */\nexport function convertTimeToNanos(\n value: string | number | Date | undefined\n): string | undefined {\n if (value === undefined) {\n return nanos()\n } else if (typeof value === 'string') {\n return value.length > 0 ? value : undefined\n } else if (value instanceof Date) {\n return `${value.getTime()}000000`\n } else if (typeof value === 'number') {\n return String(Math.floor(value))\n } else {\n return String(value)\n }\n}\n","/**\n * Logging interface.\n */\nexport interface Logger {\n error(message: string, err?: any): void\n warn(message: string, err?: any): void\n}\n\n/**\n * Logger that logs to console.out\n */\nexport const consoleLogger: Logger = {\n error(message, error) {\n // eslint-disable-next-line no-console\n console.error('ERROR: ' + message, error ? error : '')\n },\n warn(message, error) {\n // eslint-disable-next-line no-console\n console.warn('WARN: ' + message, error ? error : '')\n },\n}\nlet provider: Logger = consoleLogger\n\nexport const Log: Logger = {\n error(message, error) {\n provider.error(message, error)\n },\n warn(message, error) {\n provider.warn(message, error)\n },\n}\n\n/**\n * Sets custom logger.\n * @param logger - logger to use\n * @returns previous logger\n */\nexport function setLogger(logger: Logger): Logger {\n const previous = provider\n provider = logger\n return previous\n}\n","/** Property that offers a function that returns flux-sanitized value of an object. */\nexport const FLUX_VALUE = Symbol('FLUX_VALUE')\n\n/**\n * A flux parameter can print its (sanitized) flux value.\n */\nexport interface FluxParameterLike {\n [FLUX_VALUE](): string\n}\n\n/**\n * Represents a parameterized query.\n */\nexport interface ParameterizedQuery {\n /**\n * Returns flux query with sanitized parameters.\n */\n toString(): string\n}\n\nclass FluxParameter implements FluxParameterLike, ParameterizedQuery {\n constructor(private fluxValue: string) {}\n toString(): string {\n return this.fluxValue\n }\n [FLUX_VALUE](): string {\n return this.fluxValue\n }\n}\n\n/**\n * Checks if the supplied object is FluxParameterLike\n * @param value - any value\n * @returns true if it is\n */\nfunction isFluxParameterLike(value: any): boolean {\n return typeof value === 'object' && typeof value[FLUX_VALUE] === 'function'\n}\n\n/**\n * Escapes content of the supplied string so it can be wrapped into double qoutes\n * to become a [flux string literal](https://docs.influxdata.com/flux/latest/spec/lexical-elements/#string-literals).\n * @param value - string value\n * @returns sanitized string\n */\nfunction sanitizeString(value: any): string {\n if (value === null || value === undefined) return ''\n value = value.toString()\n let retVal: any = undefined\n let i = 0\n function prepareRetVal(): void {\n if (retVal === undefined) {\n retVal = value.substring(0, i)\n }\n }\n for (; i < value.length; i++) {\n const c = value.charAt(i)\n switch (c) {\n case '\\r':\n prepareRetVal()\n retVal += '\\\\r'\n break\n case '\\n':\n prepareRetVal()\n retVal += '\\\\n'\n break\n case '\\t':\n prepareRetVal()\n retVal += '\\\\t'\n break\n case '\"':\n case '\\\\':\n prepareRetVal()\n retVal = retVal + '\\\\' + c\n break\n case '$':\n // escape ${\n if (i + 1 < value.length && value.charAt(i + 1) === '{') {\n prepareRetVal()\n i++\n retVal += '\\\\${'\n break\n }\n // append $\n if (retVal != undefined) {\n retVal += c\n }\n break\n default:\n if (retVal != undefined) {\n retVal += c\n }\n }\n }\n if (retVal !== undefined) {\n return retVal\n }\n return value\n}\n\n/**\n * Creates a flux string literal.\n */\nexport function fluxString(value: any): FluxParameterLike {\n return new FluxParameter(`\"${sanitizeString(value)}\"`)\n}\n\n/**\n * Sanitizes float value to avoid injections.\n * @param value - InfluxDB float literal\n * @returns sanitized float value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeFloat(value: any): string {\n const val = Number(value)\n if (!isFinite(val)) {\n if (typeof value === 'number') {\n return `float(v: \"${val}\")`\n }\n throw new Error(`not a flux float: ${value}`)\n }\n // try to return a flux float literal if possible\n // https://docs.influxdata.com/flux/latest/data-types/basic/float/#float-syntax\n const strVal = val.toString()\n let hasDot = false\n for (const c of strVal) {\n if ((c >= '0' && c <= '9') || c == '-') continue\n if (c === '.') {\n hasDot = true\n continue\n }\n return `float(v: \"${strVal}\")`\n }\n return hasDot ? strVal : strVal + '.0'\n}\n/**\n * Creates a flux float literal.\n */\nexport function fluxFloat(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeFloat(value))\n}\n\n/**\n * Sanitizes integer value to avoid injections.\n * @param value - InfluxDB integer literal\n * @returns sanitized integer value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeInteger(value: any): string {\n // https://docs.influxdata.com/flux/latest/data-types/basic/int/\n // Min value: -9223372036854775808\n // Max value: 9223372036854775807\n // \"9223372036854775807\".length === 19\n const strVal = String(value)\n const negative = strVal.startsWith('-')\n const val = negative ? strVal.substring(1) : strVal\n if (val.length === 0 || val.length > 19) {\n throw new Error(`not a flux integer: ${strVal}`)\n }\n for (const c of val) {\n if (c < '0' || c > '9') throw new Error(`not a flux integer: ${strVal}`)\n }\n if (val.length === 19) {\n if (negative && val > '9223372036854775808') {\n throw new Error(`flux integer out of bounds: ${strVal}`)\n }\n if (!negative && val > '9223372036854775807') {\n throw new Error(`flux integer out of bounds: ${strVal}`)\n }\n }\n return strVal\n}\n\n/**\n * Creates a flux integer literal.\n */\nexport function fluxInteger(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeInteger(value))\n}\n\nfunction sanitizeDateTime(value: any): string {\n return `time(v: \"${sanitizeString(value)}\")`\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDateTime(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeDateTime(value))\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDuration(value: any): FluxParameterLike {\n return new FluxParameter(`duration(v: \"${sanitizeString(value)}\")`)\n}\n\nfunction sanitizeRegExp(value: any): string {\n if (value instanceof RegExp) {\n return value.toString()\n }\n return new RegExp(value).toString()\n}\n\n/**\n * Creates flux regexp literal out of a regular expression. See\n * https://docs.influxdata.com/flux/latest/data-types/basic/regexp/#regular-expression-syntax\n * for details.\n */\nexport function fluxRegExp(value: any): FluxParameterLike {\n // let the server decide if a regexp can be parsed\n return new FluxParameter(sanitizeRegExp(value))\n}\n\n/**\n * Creates flux boolean literal.\n */\nexport function fluxBool(value: any): FluxParameterLike {\n if (value === 'true' || value === 'false') {\n return new FluxParameter(value)\n }\n return new FluxParameter((!!value).toString())\n}\n\n/**\n * Assumes that the supplied value is flux expression or literal that does not need sanitizing.\n *\n * @param value - any value\n * @returns the supplied value as-is\n */\nexport function fluxExpression(value: any): FluxParameterLike {\n return new FluxParameter(String(value))\n}\n\n/**\n * Escapes content of the supplied parameter so that it can be safely embedded into flux query.\n * @param value - parameter value\n * @returns sanitized flux value or an empty string if it cannot be converted\n */\nexport function toFluxValue(value: any): string {\n if (value === undefined) {\n return ''\n } else if (value === null) {\n return 'null'\n } else if (typeof value === 'boolean') {\n return value.toString()\n } else if (typeof value === 'string') {\n return `\"${sanitizeString(value)}\"`\n } else if (typeof value === 'number') {\n if (Number.isSafeInteger(value)) {\n return sanitizeInteger(value)\n }\n return sanitizeFloat(value)\n } else if (typeof value === 'object') {\n if (typeof value[FLUX_VALUE] === 'function') {\n return value[FLUX_VALUE]()\n } else if (value instanceof Date) {\n return value.toISOString()\n } else if (value instanceof RegExp) {\n return sanitizeRegExp(value)\n } else if (Array.isArray(value)) {\n return `[${value.map(toFluxValue).join(',')}]`\n }\n } else if (typeof value === 'bigint') {\n return `${value}.0`\n }\n // use toString value for unrecognized object, symbol\n return toFluxValue(value.toString())\n}\n\n/**\n * Flux is a tagged template that sanitizes supplied parameters\n * to avoid injection attacks in flux.\n */\nexport function flux(\n strings: TemplateStringsArray,\n ...values: any\n): ParameterizedQuery {\n if (strings.length == 1 && values.length === 0) {\n return fluxExpression(strings[0]) // the simplest case\n }\n const parts = new Array(strings.length + values.length)\n let partIndex = 0\n for (let i = 0; i < strings.length; i++) {\n const text = strings[i]\n parts[partIndex++] = text\n if (i < values.length) {\n const val = values[i]\n let sanitized: string\n if (\n text.endsWith('\"') &&\n i + 1 < strings.length &&\n strings[i + 1].startsWith('\"')\n ) {\n // parameter is wrapped into flux double quotes\n sanitized = sanitizeString(val)\n } else {\n sanitized = toFluxValue(val)\n if (sanitized === '') {\n // do not allow to insert empty strings, unless it is FluxParameterLike\n if (!isFluxParameterLike(val)) {\n throw new Error(\n `Unsupported parameter literal '${val}' at index: ${i}, type: ${typeof val}`\n )\n }\n }\n }\n parts[partIndex++] = sanitized\n } else if (i < strings.length - 1) {\n throw new Error('Too few parameters supplied!')\n }\n }\n // return flux expression so that flux can be embedded into another flux as-is\n return fluxExpression(parts.join(''))\n}\n","import {convertTimeToNanos} from './util/currentTime'\nimport {escape} from './util/escape'\n\n/**\n * Settings that control the way of how a {@link Point} is serialized\n * to a protocol line.\n */\nexport interface PointSettings {\n /** default tags to add to every point */\n defaultTags?: {[key: string]: string}\n /** convertTime serializes Point's timestamp to a line protocol value */\n convertTime?: (\n value: string | number | Date | undefined\n ) => string | undefined\n}\n\n/**\n * Point defines values of a single measurement.\n */\nexport class Point {\n private name: string\n private tags: {[key: string]: string} = {}\n /** escaped field values */\n public fields: {[key: string]: string} = {}\n private time: string | number | Date | undefined\n\n /**\n * Create a new Point with specified a measurement name.\n *\n * @param measurementName - the measurement name\n */\n constructor(measurementName?: string) {\n if (measurementName) this.name = measurementName\n }\n\n /**\n * Sets point's measurement.\n *\n * @param name - measurement name\n * @returns this\n */\n public measurement(name: string): Point {\n this.name = name\n return this\n }\n\n /**\n * Adds a tag. The caller has to ensure that both name and value are not empty\n * and do not end with backslash.\n *\n * @param name - tag name\n * @param value - tag value\n * @returns this\n */\n public tag(name: string, value: string): Point {\n this.tags[name] = value\n return this\n }\n\n /**\n * Adds a boolean field.\n *\n * @param field - field name\n * @param value - field value\n * @returns this\n */\n public booleanField(name: string, value: boolean | any): Point {\n this.fields[name] = value ? 'T' : 'F'\n return this\n }\n\n /**\n * Adds an integer field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN or out of int64 range value is supplied\n */\n public intField(name: string, value: number | any): Point {\n let val: number\n if (typeof value === 'number') {\n val = value\n } else {\n val = parseInt(String(value))\n }\n if (isNaN(val) || val <= -9223372036854776e3 || val >= 9223372036854776e3) {\n throw new Error(`invalid integer value for field '${name}': '${value}'!`)\n }\n this.fields[name] = `${Math.floor(val)}i`\n return this\n }\n\n /**\n * Adds an unsigned integer field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN out of range value is supplied\n */\n public uintField(name: string, value: number | any): Point {\n if (typeof value === 'number') {\n if (isNaN(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {\n throw new Error(`uint value for field '${name}' out of range: ${value}`)\n }\n this.fields[name] = `${Math.floor(value as number)}u`\n } else {\n const strVal = String(value)\n for (let i = 0; i < strVal.length; i++) {\n const code = strVal.charCodeAt(i)\n if (code < 48 || code > 57) {\n throw new Error(\n `uint value has an unsupported character at pos ${i}: ${value}`\n )\n }\n }\n if (\n strVal.length > 20 ||\n (strVal.length === 20 &&\n strVal.localeCompare('18446744073709551615') > 0)\n ) {\n throw new Error(\n `uint value for field '${name}' out of range: ${strVal}`\n )\n }\n this.fields[name] = `${strVal}u`\n }\n return this\n }\n\n /**\n * Adds a number field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN/Infinity/-Infinity is supplied\n */\n public floatField(name: string, value: number | any): Point {\n let val: number\n if (typeof value === 'number') {\n val = value\n } else {\n val = parseFloat(value)\n }\n if (!isFinite(val)) {\n throw new Error(`invalid float value for field '${name}': ${value}`)\n }\n\n this.fields[name] = String(val)\n return this\n }\n\n /**\n * Adds a string field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n */\n public stringField(name: string, value: string | any): Point {\n if (value !== null && value !== undefined) {\n if (typeof value !== 'string') value = String(value)\n this.fields[name] = escape.quoted(value)\n }\n return this\n }\n\n /**\n * Sets point timestamp. Timestamp can be specified as a Date (preferred), number, string\n * or an undefined value. An undefined value instructs to assign a local timestamp using\n * the client's clock. An empty string can be used to let the server assign\n * the timestamp. A number value represents time as a count of time units since epoch, the\n * exact time unit then depends on the {@link InfluxDB.getWriteApi | precision} of the API\n * that writes the point.\n *\n * Beware that the current time in nanoseconds can't precisely fit into a JS number,\n * which can hold at most 2^53 integer number. Nanosecond precision numbers are thus supplied as\n * a (base-10) string. An application can also use ES2020 BigInt to represent nanoseconds,\n * BigInt's `toString()` returns the required high-precision string.\n *\n * Note that InfluxDB requires the timestamp to fit into int64 data type.\n *\n * @param value - point time\n * @returns this\n */\n public timestamp(value: Date | number | string | undefined): Point {\n this.time = value\n return this\n }\n\n /**\n * Creates an InfluxDB protocol line out of this instance.\n * @param settings - settings control serialization of a point timestamp and can also add default tags,\n * nanosecond timestamp precision is used when no `settings` or no `settings.convertTime` is supplied.\n * @returns an InfluxDB protocol line out of this instance\n */\n public toLineProtocol(settings?: Partial): string | undefined {\n if (!this.name) return undefined\n let fieldsLine = ''\n Object.keys(this.fields)\n .sort()\n .forEach((x) => {\n if (x) {\n const val = this.fields[x]\n if (fieldsLine.length > 0) fieldsLine += ','\n fieldsLine += `${escape.tag(x)}=${val}`\n }\n })\n if (fieldsLine.length === 0) return undefined // no fields present\n let tagsLine = ''\n const tags =\n settings && settings.defaultTags\n ? {...settings.defaultTags, ...this.tags}\n : this.tags\n Object.keys(tags)\n .sort()\n .forEach((x) => {\n if (x) {\n const val = tags[x]\n if (val) {\n tagsLine += ','\n tagsLine += `${escape.tag(x)}=${escape.tag(val)}`\n }\n }\n })\n let time = this.time\n if (settings && settings.convertTime) {\n time = settings.convertTime(time)\n } else {\n time = convertTimeToNanos(time)\n }\n\n return `${escape.measurement(this.name)}${tagsLine} ${fieldsLine}${\n time !== undefined ? ' ' + time : ''\n }`\n }\n\n toString(): string {\n const line = this.toLineProtocol(undefined)\n return line ? line : `invalid point: ${JSON.stringify(this, undefined)}`\n }\n}\n","import {getRetryDelay, RetryDelayStrategy} from '../errors'\nimport {\n RetryDelayStrategyOptions,\n DEFAULT_RetryDelayStrategyOptions,\n} from '../options'\n\n/**\n * Applies a variant of exponential backoff with initial and max delay and a random\n * jitter delay. It also respects `retry delay` when specified together with an error.\n */\nexport class RetryStrategyImpl implements RetryDelayStrategy {\n options: RetryDelayStrategyOptions\n currentDelay: number | undefined\n\n constructor(options?: Partial) {\n this.options = {...DEFAULT_RetryDelayStrategyOptions, ...options}\n this.success()\n }\n\n nextDelay(error?: Error, failedAttempts?: number): number {\n const delay = getRetryDelay(error)\n if (delay && delay > 0) {\n return delay + Math.round(Math.random() * this.options.retryJitter)\n } else {\n if (failedAttempts && failedAttempts > 0) {\n // compute delay\n if (this.options.randomRetry) {\n // random delay between deterministic delays\n let delay = Math.max(this.options.minRetryDelay, 1)\n let nextDelay = delay * this.options.exponentialBase\n for (let i = 1; i < failedAttempts; i++) {\n delay = nextDelay\n nextDelay = nextDelay * this.options.exponentialBase\n if (nextDelay >= this.options.maxRetryDelay) {\n nextDelay = this.options.maxRetryDelay\n break\n }\n }\n return (\n delay +\n Math.round(\n Math.random() * (nextDelay - delay) +\n Math.random() * this.options.retryJitter\n )\n )\n }\n // deterministric delay otherwise\n let delay = Math.max(this.options.minRetryDelay, 1)\n for (let i = 1; i < failedAttempts; i++) {\n delay = delay * this.options.exponentialBase\n if (delay >= this.options.maxRetryDelay) {\n delay = this.options.maxRetryDelay\n break\n }\n }\n return delay + Math.round(Math.random() * this.options.retryJitter)\n } else if (this.currentDelay) {\n this.currentDelay = Math.min(\n Math.max(this.currentDelay * this.options.exponentialBase, 1) +\n Math.round(Math.random() * this.options.retryJitter),\n this.options.maxRetryDelay\n )\n } else {\n this.currentDelay =\n this.options.minRetryDelay +\n Math.round(Math.random() * this.options.retryJitter)\n }\n return this.currentDelay\n }\n }\n success(): void {\n this.currentDelay = undefined\n }\n}\n\n/**\n * Creates a new instance of retry strategy.\n * @param options - retry options\n * @returns retry strategy implementation\n */\nexport function createRetryDelayStrategy(\n options?: Partial\n): RetryDelayStrategy {\n return new RetryStrategyImpl(options)\n}\n","import {Log} from '../util/logger'\n\ninterface RetryItem {\n lines: string[]\n retryCount: number\n retryTime: number\n expires: number\n next?: RetryItem\n}\n\ntype FindShrinkCandidateResult = [found: RetryItem, parent?: RetryItem]\n\nfunction findShrinkCandidate(first: RetryItem): FindShrinkCandidateResult {\n let parent = undefined\n let found = first\n let currentParent = first\n while (currentParent.next) {\n if (currentParent.next.expires < found.expires) {\n parent = currentParent\n found = currentParent.next\n }\n currentParent = currentParent.next\n }\n return [found, parent]\n}\n\n/**\n * Retries lines up to a limit of max buffer size.\n */\nexport default class RetryBuffer {\n first?: RetryItem\n size = 0\n closed = false\n private _timeoutHandle: any = undefined\n\n constructor(\n private maxLines: number,\n private retryLines: (\n lines: string[],\n retryCountdown: number,\n started: number\n ) => Promise,\n private onShrink: (entry: {\n lines: string[]\n retryCount: number\n expires: number\n }) => void = () => undefined\n ) {}\n\n addLines(\n lines: string[],\n retryCount: number,\n delay: number,\n expires: number\n ): void {\n if (this.closed) return\n if (!lines.length) return\n let retryTime = Date.now() + delay\n if (expires < retryTime) {\n retryTime = expires\n }\n // ensure at most maxLines are in the Buffer\n if (this.first && this.size + lines.length > this.maxLines) {\n const origSize = this.size\n const newSize = origSize * 0.7 // reduce to 70 %\n do {\n // remove \"oldest\" item\n const [found, parent] = findShrinkCandidate(this.first)\n this.size -= found.lines.length\n if (parent) {\n parent.next = found.next\n } else {\n this.first = found.next\n if (this.first) {\n this.scheduleRetry(this.first.retryTime - Date.now())\n }\n }\n found.next = undefined\n this.onShrink(found)\n } while (this.first && this.size + lines.length > newSize)\n Log.error(\n `RetryBuffer: ${\n origSize - this.size\n } oldest lines removed to keep buffer size under the limit of ${\n this.maxLines\n } lines.`\n )\n }\n const toAdd: RetryItem = {\n lines,\n retryCount,\n retryTime,\n expires,\n }\n // insert sorted according to retryTime\n let current: RetryItem | undefined = this.first\n let parent = undefined\n for (;;) {\n if (!current || current.retryTime > retryTime) {\n toAdd.next = current\n if (parent) {\n parent.next = toAdd\n } else {\n this.first = toAdd\n this.scheduleRetry(retryTime - Date.now())\n }\n break\n }\n parent = current\n current = current.next\n }\n this.size += lines.length\n }\n\n removeLines(): RetryItem | undefined {\n if (this.first) {\n const toRetry = this.first\n this.first = this.first.next\n toRetry.next = undefined\n this.size -= toRetry.lines.length\n return toRetry\n }\n return undefined\n }\n\n scheduleRetry(delay: number): void {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle)\n }\n this._timeoutHandle = setTimeout(() => {\n const toRetry = this.removeLines()\n if (toRetry) {\n this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n .catch(() => {\n /* error is already logged, it must be caught */\n })\n .finally(() => {\n // schedule next retry execution\n if (this.first) {\n this.scheduleRetry(this.first.retryTime - Date.now())\n }\n })\n } else {\n this._timeoutHandle = undefined\n }\n }, Math.max(delay, 0))\n }\n\n async flush(): Promise {\n let toRetry\n while ((toRetry = this.removeLines())) {\n await this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n }\n }\n\n close(): number {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle)\n this._timeoutHandle = undefined\n }\n this.closed = true\n return this.size\n }\n}\n","/**\n * Utf8Length returns an expected length of a string when UTF-8 encoded.\n * @param s - input string\n * @returns expected count of bytes\n */\nexport default function utf8Length(s: string): number {\n let retVal = s.length\n // extends the size with code points (https://en.wikipedia.org/wiki/UTF-8#Encoding)\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i)\n /* istanbul ignore else - JS does not count with 4-bytes UNICODE characters at the moment */\n if (code < 0x80) {\n continue\n } else if (code >= 0x80 && code <= 0x7ff) {\n retVal++\n } else if (code >= 0x800 && code <= 0xffff) {\n if (code >= 0xd800 && code <= 0xdfff) {\n // node.js represents unicode characters above 0xffff by two UTF-16 surrogate halves\n // see https://en.wikipedia.org/wiki/UTF-8#Codepage_layout\n retVal++\n } else {\n retVal += 2\n }\n } else {\n // never happens in node.js 14, the situation can vary in the futures or in deno/browsers\n retVal += 3\n }\n }\n return retVal\n}\n","import WriteApi from '../WriteApi'\nimport {\n DEFAULT_WriteOptions,\n WriteOptions,\n WritePrecisionType,\n} from '../options'\nimport {Transport, SendOptions} from '../transport'\nimport {Headers} from '../results'\nimport {Log} from '../util/logger'\nimport {HttpError, RetryDelayStrategy} from '../errors'\nimport {Point} from '../Point'\nimport {currentTime, dateToProtocolTimestamp} from '../util/currentTime'\nimport {createRetryDelayStrategy} from './retryStrategy'\nimport RetryBuffer from './RetryBuffer'\nimport utf8Length from '../util/utf8Length'\n\nclass WriteBuffer {\n length = 0\n bytes = -1\n lines: string[]\n\n constructor(\n private maxChunkRecords: number,\n private maxBatchBytes: number,\n private flushFn: (lines: string[]) => Promise,\n private scheduleSend: () => void\n ) {\n this.lines = new Array(maxChunkRecords)\n }\n\n add(record: string): void {\n const size = utf8Length(record)\n if (this.length === 0) {\n this.scheduleSend()\n } else if (this.bytes + size + 1 >= this.maxBatchBytes) {\n // the new size already exceeds maxBatchBytes, send it\n this.flush().catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n })\n }\n this.lines[this.length] = record\n this.length++\n this.bytes += size + 1\n if (\n this.length >= this.maxChunkRecords ||\n this.bytes >= this.maxBatchBytes\n ) {\n this.flush().catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n })\n }\n }\n flush(): Promise {\n const lines = this.reset()\n if (lines.length > 0) {\n return this.flushFn(lines)\n } else {\n return Promise.resolve()\n }\n }\n reset(): string[] {\n const retVal = this.lines.slice(0, this.length)\n this.length = 0\n this.bytes = -1 // lines are joined with \\n\n return retVal\n }\n}\n\nexport default class WriteApiImpl implements WriteApi {\n public path: string\n\n private writeBuffer: WriteBuffer\n private closed = false\n private writeOptions: WriteOptions\n private sendOptions: SendOptions\n private _timeoutHandle: any = undefined\n private currentTime: () => string\n private dateToProtocolTimestamp: (d: Date) => string\n\n retryBuffer: RetryBuffer\n retryStrategy: RetryDelayStrategy\n\n constructor(\n private transport: Transport,\n org: string,\n bucket: string,\n precision: WritePrecisionType,\n writeOptions?: Partial\n ) {\n this.path = `/api/v2/write?org=${encodeURIComponent(\n org\n )}&bucket=${encodeURIComponent(bucket)}&precision=${precision}`\n if (writeOptions?.consistency) {\n this.path += `&consistency=${encodeURIComponent(\n writeOptions.consistency\n )}`\n }\n this.writeOptions = {\n ...DEFAULT_WriteOptions,\n ...writeOptions,\n }\n this.currentTime = currentTime[precision]\n this.dateToProtocolTimestamp = dateToProtocolTimestamp[precision]\n if (this.writeOptions.defaultTags) {\n this.useDefaultTags(this.writeOptions.defaultTags)\n }\n this.sendOptions = {\n method: 'POST',\n headers: {\n 'content-type': 'text/plain; charset=utf-8',\n ...writeOptions?.headers,\n },\n gzipThreshold: this.writeOptions.gzipThreshold,\n }\n\n const scheduleNextSend = (): void => {\n if (this.writeOptions.flushInterval > 0) {\n this._clearFlushTimeout()\n /* istanbul ignore else manually reviewed, hard to reproduce */\n if (!this.closed) {\n this._timeoutHandle = setTimeout(\n () =>\n this.sendBatch(\n this.writeBuffer.reset(),\n this.writeOptions.maxRetries\n ).catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n }),\n this.writeOptions.flushInterval\n )\n }\n }\n }\n // write buffer\n this.writeBuffer = new WriteBuffer(\n this.writeOptions.batchSize,\n this.writeOptions.maxBatchBytes,\n (lines) => {\n this._clearFlushTimeout()\n return this.sendBatch(lines, this.writeOptions.maxRetries)\n },\n scheduleNextSend\n )\n this.sendBatch = this.sendBatch.bind(this)\n // retry buffer\n this.retryStrategy = createRetryDelayStrategy(this.writeOptions)\n this.retryBuffer = new RetryBuffer(\n this.writeOptions.maxBufferLines,\n this.sendBatch,\n this.writeOptions.writeRetrySkipped\n )\n }\n\n sendBatch(\n lines: string[],\n retryAttempts: number,\n expires: number = Date.now() + this.writeOptions.maxRetryTime\n ): Promise {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self: WriteApiImpl = this\n const failedAttempts = self.writeOptions.maxRetries + 1 - retryAttempts\n if (!this.closed && lines.length > 0) {\n if (expires <= Date.now()) {\n const error = new Error('Max retry time exceeded.')\n const onRetry = self.writeOptions.writeFailed.call(\n self,\n error,\n lines,\n failedAttempts,\n expires\n )\n if (onRetry) {\n return onRetry\n }\n Log.error(\n `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n error\n )\n return Promise.reject(error)\n }\n return new Promise((resolve, reject) => {\n let responseStatusCode: number | undefined\n const callbacks = {\n responseStarted(_headers: Headers, statusCode?: number): void {\n responseStatusCode = statusCode\n },\n error(error: Error): void {\n // call the writeFailed listener and check if we can retry\n const onRetry = self.writeOptions.writeFailed.call(\n self,\n error,\n lines,\n failedAttempts,\n expires\n )\n if (onRetry) {\n onRetry.then(resolve, reject)\n return\n }\n // ignore informational message about the state of InfluxDB\n // enterprise cluster, if present\n if (\n error instanceof HttpError &&\n error.json &&\n typeof error.json.error === 'string' &&\n error.json.error.includes('hinted handoff queue not empty')\n ) {\n Log.warn('Write to InfluxDB returns: ' + error.json.error)\n responseStatusCode = 204\n callbacks.complete()\n return\n }\n // retry if possible\n if (\n !self.closed &&\n retryAttempts > 0 &&\n (!(error instanceof HttpError) ||\n (error as HttpError).statusCode >= 429)\n ) {\n Log.warn(\n `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n error\n )\n self.retryBuffer.addLines(\n lines,\n retryAttempts - 1,\n self.retryStrategy.nextDelay(error, failedAttempts),\n expires\n )\n reject(error)\n return\n }\n Log.error(`Write to InfluxDB failed.`, error)\n reject(error)\n },\n complete(): void {\n // older implementations of transport do not report status code\n if (responseStatusCode == 204 || responseStatusCode == undefined) {\n self.writeOptions.writeSuccess.call(self, lines)\n self.retryStrategy.success()\n resolve()\n } else {\n const message = `204 HTTP response status code expected, but ${responseStatusCode} returned`\n const error = new HttpError(\n responseStatusCode,\n message,\n undefined,\n '0'\n )\n error.message = message\n callbacks.error(error)\n }\n },\n }\n this.transport.send(\n this.path,\n lines.join('\\n'),\n this.sendOptions,\n callbacks\n )\n })\n } else {\n return Promise.resolve()\n }\n }\n\n private _clearFlushTimeout(): void {\n if (this._timeoutHandle !== undefined) {\n clearTimeout(this._timeoutHandle)\n this._timeoutHandle = undefined\n }\n }\n\n writeRecord(record: string): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n this.writeBuffer.add(record)\n }\n writeRecords(records: ArrayLike): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n for (let i = 0; i < records.length; i++) {\n this.writeBuffer.add(records[i])\n }\n }\n writePoint(point: Point): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n const line = point.toLineProtocol(this)\n if (line) this.writeBuffer.add(line)\n }\n writePoints(points: ArrayLike): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n for (let i = 0; i < points.length; i++) {\n const line = points[i].toLineProtocol(this)\n if (line) this.writeBuffer.add(line)\n }\n }\n async flush(withRetryBuffer?: boolean): Promise {\n await this.writeBuffer.flush()\n if (withRetryBuffer) {\n return await this.retryBuffer.flush()\n }\n }\n close(): Promise {\n const retVal = this.writeBuffer.flush().finally(() => {\n const remaining = this.retryBuffer.close()\n if (remaining) {\n Log.error(\n `Retry buffer closed with ${remaining} items that were not written to InfluxDB!`,\n null\n )\n }\n this.closed = true\n })\n return retVal\n }\n dispose(): number {\n this._clearFlushTimeout()\n this.closed = true\n return this.retryBuffer.close() + this.writeBuffer.length\n }\n\n // PointSettings\n defaultTags: {[key: string]: string} | undefined\n useDefaultTags(tags: {[key: string]: string}): WriteApi {\n this.defaultTags = tags\n return this\n }\n convertTime(value: string | number | Date | undefined): string | undefined {\n if (value === undefined) {\n return this.currentTime()\n } else if (typeof value === 'string') {\n return value.length > 0 ? value : undefined\n } else if (value instanceof Date) {\n return this.dateToProtocolTimestamp(value)\n } else if (typeof value === 'number') {\n return String(Math.floor(value))\n } else {\n return String(value)\n }\n }\n}\n","import {CommunicationObserver, Headers} from '../results'\n\ntype CompleteObserver = Omit<\n Required>,\n 'useCancellable' | 'useResume'\n> &\n Pick, 'useResume' | 'useCancellable'>\n\nexport default function completeCommunicationObserver(\n callbacks: Partial> = {}\n): CompleteObserver {\n let state = 0\n const retVal: CompleteObserver = {\n next: (data: any): void | boolean => {\n if (\n state === 0 &&\n callbacks.next &&\n data !== null &&\n data !== undefined\n ) {\n return callbacks.next(data)\n }\n },\n error: (error: Error): void => {\n /* istanbul ignore else propagate error at most once */\n if (state === 0) {\n state = 1\n /* istanbul ignore else safety check */\n if (callbacks.error) callbacks.error(error)\n }\n },\n complete: (): void => {\n if (state === 0) {\n state = 2\n /* istanbul ignore else safety check */\n if (callbacks.complete) callbacks.complete()\n }\n },\n responseStarted: (headers: Headers, statusCode?: number): void => {\n if (callbacks.responseStarted)\n callbacks.responseStarted(headers, statusCode)\n },\n }\n if (callbacks.useCancellable) {\n retVal.useCancellable = callbacks.useCancellable.bind(callbacks)\n }\n if (callbacks.useResume) {\n retVal.useResume = callbacks.useResume.bind(callbacks)\n }\n return retVal\n}\n","import {Transport, SendOptions} from '../../transport'\nimport {ConnectionOptions} from '../../options'\nimport {AbortError, HttpError} from '../../errors'\nimport completeCommunicationObserver from '../completeCommunicationObserver'\nimport {Log} from '../../util/logger'\nimport {\n ChunkCombiner,\n CommunicationObserver,\n createTextDecoderCombiner,\n Headers,\n ResponseStartedFn,\n} from '../../results'\n\nfunction getResponseHeaders(response: Response): Headers {\n const headers: Headers = {}\n response.headers.forEach((value: string, key: string) => {\n const previous = headers[key]\n if (previous === undefined) {\n headers[key] = value\n } else if (Array.isArray(previous)) {\n previous.push(value)\n } else {\n headers[key] = [previous, value]\n }\n })\n return headers\n}\n\n/**\n * Transport layer that use browser fetch.\n */\nexport default class FetchTransport implements Transport {\n chunkCombiner: ChunkCombiner = createTextDecoderCombiner()\n private defaultHeaders: {[key: string]: string}\n private url: string\n constructor(private connectionOptions: ConnectionOptions) {\n this.defaultHeaders = {\n 'content-type': 'application/json; charset=utf-8',\n // 'User-Agent': `influxdb-client-js/${CLIENT_LIB_VERSION}`, // user-agent can hardly be customized https://github.com/influxdata/influxdb-client-js/issues/262\n ...connectionOptions.headers,\n }\n if (this.connectionOptions.token) {\n this.defaultHeaders['Authorization'] =\n 'Token ' + this.connectionOptions.token\n }\n this.url = String(this.connectionOptions.url)\n if (this.url.endsWith('/')) {\n this.url = this.url.substring(0, this.url.length - 1)\n }\n // https://github.com/influxdata/influxdb-client-js/issues/263\n // don't allow /api/v2 suffix to avoid future problems\n if (this.url.endsWith('/api/v2')) {\n this.url = this.url.substring(0, this.url.length - '/api/v2'.length)\n Log.warn(\n `Please remove '/api/v2' context path from InfluxDB base url, using ${this.url} !`\n )\n }\n }\n send(\n path: string,\n body: string,\n options: SendOptions,\n callbacks?: Partial> | undefined\n ): void {\n const observer = completeCommunicationObserver(callbacks)\n let cancelled = false\n let signal = (options as any).signal\n let pausePromise: Promise | undefined\n const resumeQuickly = () => {}\n let resume = resumeQuickly\n if (callbacks && callbacks.useCancellable) {\n const controller = new AbortController()\n if (!signal) {\n signal = controller.signal\n options = {...options, signal}\n }\n // resume data reading so that it can exit on abort signal\n signal.addEventListener('abort', () => {\n resume()\n })\n callbacks.useCancellable({\n cancel() {\n cancelled = true\n controller.abort()\n },\n isCancelled() {\n return cancelled || signal.aborted\n },\n })\n }\n this.fetch(path, body, options)\n .then(async (response) => {\n if (callbacks?.responseStarted) {\n observer.responseStarted(\n getResponseHeaders(response),\n response.status\n )\n }\n await this.throwOnErrorResponse(response)\n if (response.body) {\n const reader = response.body.getReader()\n let chunk: ReadableStreamReadResult\n do {\n if (pausePromise) {\n await pausePromise\n }\n if (cancelled) {\n break\n }\n chunk = await reader.read()\n if (observer.next(chunk.value) === false) {\n const useResume = observer.useResume\n if (!useResume) {\n const msg = 'Unable to pause, useResume is not configured!'\n await reader.cancel(msg)\n return Promise.reject(new Error(msg))\n }\n pausePromise = new Promise((resolve) => {\n resume = () => {\n resolve()\n pausePromise = undefined\n resume = resumeQuickly\n }\n useResume(resume)\n })\n }\n } while (!chunk.done)\n } else if (response.arrayBuffer) {\n const buffer = await response.arrayBuffer()\n observer.next(new Uint8Array(buffer))\n } else {\n const text = await response.text()\n observer.next(new TextEncoder().encode(text))\n }\n })\n .catch((e) => {\n if (!cancelled) {\n observer.error(e)\n }\n })\n .finally(() => observer.complete())\n }\n private async throwOnErrorResponse(response: Response): Promise {\n if (response.status >= 300) {\n let text = ''\n try {\n text = await response.text()\n if (!text) {\n const headerError = response.headers.get('x-influxdb-error')\n if (headerError) {\n text = headerError\n }\n }\n } catch (e) {\n Log.warn('Unable to receive error body', e)\n throw new HttpError(\n response.status,\n response.statusText,\n undefined,\n response.headers.get('retry-after'),\n response.headers.get('content-type')\n )\n }\n throw new HttpError(\n response.status,\n response.statusText,\n text,\n response.headers.get('retry-after'),\n response.headers.get('content-type')\n )\n }\n }\n\n async *iterate(\n path: string,\n body: string,\n options: SendOptions\n ): AsyncIterableIterator {\n const response = await this.fetch(path, body, options)\n await this.throwOnErrorResponse(response)\n if (response.body) {\n const reader = response.body.getReader()\n for (;;) {\n const {value, done} = await reader.read()\n if (done) {\n break\n }\n if (options.signal?.aborted) {\n await response.body.cancel()\n throw new AbortError()\n }\n yield value\n }\n } else if (response.arrayBuffer) {\n const buffer = await response.arrayBuffer()\n yield new Uint8Array(buffer)\n } else {\n const text = await response.text()\n yield new TextEncoder().encode(text)\n }\n }\n\n async request(\n path: string,\n body: any,\n options: SendOptions,\n responseStarted?: ResponseStartedFn\n ): Promise {\n const response = await this.fetch(path, body, options)\n const {headers} = response\n const responseContentType = headers.get('content-type') || ''\n if (responseStarted) {\n responseStarted(getResponseHeaders(response), response.status)\n }\n\n await this.throwOnErrorResponse(response)\n const responseType = options.headers?.accept ?? responseContentType\n if (responseType.includes('json')) {\n return await response.json()\n } else if (\n responseType.includes('text') ||\n responseType.startsWith('application/csv')\n ) {\n return await response.text()\n }\n }\n\n private fetch(\n path: string,\n body: any,\n options: SendOptions\n ): Promise {\n const {method, headers, ...other} = options\n const url = `${this.url}${path}`\n const request: RequestInit = {\n method: method,\n body:\n method === 'GET' || method === 'HEAD'\n ? undefined\n : typeof body === 'string'\n ? body\n : JSON.stringify(body),\n headers: {\n ...this.defaultHeaders,\n ...headers,\n },\n credentials: 'omit' as const,\n // override with custom transport options\n ...this.connectionOptions.transportOptions,\n // allow to specify custom options, such as signal, in SendOptions\n ...other,\n }\n this.requestDecorator(request, options, url)\n return fetch(url, request)\n }\n\n /**\n * RequestDecorator allows to modify requests before sending.\n *\n * The following example shows a function that adds gzip\n * compression of requests using pako.js.\n *\n * ```ts\n * const client = new InfluxDB({url: 'http://a'})\n * client.transport.requestDecorator = function(request, options) {\n * const body = request.body\n * if (\n * typeof body === 'string' &&\n * options.gzipThreshold !== undefined &&\n * body.length > options.gzipThreshold\n * ) {\n * request.headers['content-encoding'] = 'gzip'\n * request.body = pako.gzip(body)\n * }\n * }\n * ```\n */\n public requestDecorator: (\n request: RequestInit,\n options: SendOptions,\n url: string\n ) => void = function () {}\n}\n","import {Observable} from '../observable'\nimport QueryApi, {QueryOptions} from '../QueryApi'\nimport {Transport} from '../transport'\nimport {\n CommunicationObserver,\n FluxResultObserver,\n FluxTableMetaData,\n Row,\n AnnotatedCSVResponse,\n IterableResultExecutor,\n} from '../results'\nimport {ParameterizedQuery} from '../query/flux'\nimport {APIExecutor} from '../results/ObservableQuery'\n\nconst DEFAULT_dialect: any = {\n header: true,\n delimiter: ',',\n quoteChar: '\"',\n commentPrefix: '#',\n annotations: ['datatype', 'group', 'default'],\n}\n\nexport class QueryApiImpl implements QueryApi {\n private options: QueryOptions\n constructor(\n private transport: Transport,\n private createCSVResponse: (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ) => AnnotatedCSVResponse,\n org: string | QueryOptions\n ) {\n this.options = typeof org === 'string' ? {org} : org\n }\n\n with(options: Partial): QueryApi {\n return new QueryApiImpl(this.transport, this.createCSVResponse, {\n ...this.options,\n ...options,\n })\n }\n\n response(query: string | ParameterizedQuery): AnnotatedCSVResponse {\n const {org, type, gzip, headers} = this.options\n const path = `/api/v2/query?org=${encodeURIComponent(org)}`\n const body = JSON.stringify(\n this.decorateRequest({\n query: query.toString(),\n dialect: DEFAULT_dialect,\n type,\n })\n )\n const options = {\n method: 'POST',\n headers: {\n 'content-type': 'application/json; encoding=utf-8',\n 'accept-encoding': gzip ? 'gzip' : 'identity',\n ...headers,\n },\n }\n return this.createCSVResponse(\n (consumer) => this.transport.send(path, body, options, consumer),\n () => this.transport.iterate(path, body, options)\n )\n }\n\n iterateLines(query: string | ParameterizedQuery): AsyncIterable {\n return this.response(query).iterateLines()\n }\n iterateRows(query: string | ParameterizedQuery): AsyncIterable {\n return this.response(query).iterateRows()\n }\n lines(query: string | ParameterizedQuery): Observable {\n return this.response(query).lines()\n }\n\n rows(query: string | ParameterizedQuery): Observable {\n return this.response(query).rows()\n }\n\n queryLines(\n query: string | ParameterizedQuery,\n consumer: CommunicationObserver\n ): void {\n return this.response(query).consumeLines(consumer)\n }\n\n queryRows(\n query: string | ParameterizedQuery,\n consumer: FluxResultObserver\n ): void {\n return this.response(query).consumeRows(consumer)\n }\n\n collectRows(\n query: string | ParameterizedQuery,\n rowMapper?: (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined\n ): Promise> {\n return this.response(query).collectRows(rowMapper)\n }\n\n collectLines(query: string | ParameterizedQuery): Promise> {\n return this.response(query).collectLines()\n }\n\n queryRaw(query: string | ParameterizedQuery): Promise {\n const {org, type, gzip, headers} = this.options\n return this.transport.request(\n `/api/v2/query?org=${encodeURIComponent(org)}`,\n JSON.stringify(\n this.decorateRequest({\n query: query.toString(),\n dialect: DEFAULT_dialect,\n type,\n })\n ),\n {\n method: 'POST',\n headers: {\n accept: 'text/csv',\n 'accept-encoding': gzip ? 'gzip' : 'identity',\n 'content-type': 'application/json; encoding=utf-8',\n ...headers,\n },\n }\n )\n }\n\n private decorateRequest(request: any): any {\n if (typeof this.options.now === 'function') {\n request.now = this.options.now()\n }\n // https://docs.influxdata.com/influxdb/latest/api/#operation/PostQuery requires type\n request.type = this.options.type ?? 'flux'\n return request\n }\n}\n\nexport default QueryApiImpl\n","import {\n CommunicationObserver,\n FluxResultObserver,\n FluxTableMetaData,\n Row,\n linesToTables,\n ChunkCombiner,\n chunksToLines,\n chunksToLinesIterable,\n linesToRowsIterable,\n} from '../results'\nimport {Observable} from '../observable'\nimport {\n AnnotatedCSVResponse,\n IterableResultExecutor,\n} from './AnnotatedCSVResponse'\nimport ObservableQuery, {APIExecutor} from './ObservableQuery'\n\nexport function defaultRowMapping(\n values: string[],\n tableMeta: FluxTableMetaData\n): Record {\n return tableMeta.toObject(values)\n}\n\n/**\n * AnnotatedCsvResponseImpl is an implementation AnnotatedCsvResponse\n * that uses the supplied executor to supply a response data stream.\n */\nexport class AnnotatedCSVResponseImpl implements AnnotatedCSVResponse {\n constructor(\n private executor: APIExecutor,\n private iterableResultExecutor: IterableResultExecutor,\n private chunkCombiner: ChunkCombiner\n ) {}\n iterateLines(): AsyncIterable {\n return chunksToLinesIterable(this.iterableResultExecutor())\n }\n iterateRows(): AsyncIterable {\n return linesToRowsIterable(\n chunksToLinesIterable(this.iterableResultExecutor())\n )\n }\n lines(): Observable {\n return new ObservableQuery(this.executor, (observer) =>\n chunksToLines(observer, this.chunkCombiner)\n )\n }\n\n rows(): Observable {\n return new ObservableQuery(this.executor, (observer) => {\n return chunksToLines(\n linesToTables({\n next(values, tableMeta) {\n observer.next({values, tableMeta})\n },\n error(e) {\n observer.error(e)\n },\n complete() {\n observer.complete()\n },\n }),\n this.chunkCombiner\n )\n })\n }\n\n consumeLines(consumer: CommunicationObserver): void {\n this.executor(chunksToLines(consumer, this.chunkCombiner))\n }\n\n consumeRows(consumer: FluxResultObserver): void {\n this.executor(chunksToLines(linesToTables(consumer), this.chunkCombiner))\n }\n\n collectRows(\n rowMapper: (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined = defaultRowMapping as (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined\n ): Promise> {\n const retVal: Array = []\n return new Promise((resolve, reject) => {\n this.consumeRows({\n next(values: string[], tableMeta: FluxTableMetaData): void {\n const toAdd = rowMapper.call(this, values, tableMeta)\n if (toAdd !== undefined) {\n retVal.push(toAdd)\n }\n },\n error(error: Error): void {\n reject(error)\n },\n complete(): void {\n resolve(retVal)\n },\n })\n })\n }\n\n collectLines(): Promise> {\n const retVal: Array = []\n return new Promise((resolve, reject) => {\n this.consumeLines({\n next(line: string): void {\n retVal.push(line)\n },\n error(error: Error): void {\n reject(error)\n },\n complete(): void {\n resolve(retVal)\n },\n })\n })\n }\n}\n","import WriteApi from './WriteApi'\nimport {ClientOptions, WriteOptions, WritePrecisionType} from './options'\nimport WriteApiImpl from './impl/WriteApiImpl'\nimport {IllegalArgumentError} from './errors'\nimport {Transport} from './transport'\n// replaced by ./impl/browser/FetchTransport in browser builds\nimport TransportImpl from './impl/browser/FetchTransport'\nimport QueryApi, {QueryOptions} from './QueryApi'\nimport QueryApiImpl from './impl/QueryApiImpl'\nimport {\n AnnotatedCSVResponse,\n APIExecutor,\n IterableResultExecutor,\n} from './results'\nimport {AnnotatedCSVResponseImpl} from './results/AnnotatedCSVResponseImpl'\n\n/**\n * InfluxDB entry point that configures communication with InfluxDB server\n * and provide APIs to write and query data.\n */\nexport default class InfluxDB {\n private _options: ClientOptions\n readonly transport: Transport\n readonly processCSVResponse: (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ) => AnnotatedCSVResponse\n\n /**\n * Creates influxdb client options from an options object or url.\n * @param options - client options\n */\n constructor(options: ClientOptions | string) {\n if (typeof options === 'string') {\n this._options = {url: options}\n } else if (options !== null && typeof options === 'object') {\n this._options = options\n } else {\n throw new IllegalArgumentError('No url or configuration specified!')\n }\n const url = this._options.url\n if (typeof url !== 'string')\n throw new IllegalArgumentError('No url specified!')\n if (url.endsWith('/')) this._options.url = url.substring(0, url.length - 1)\n this.transport = this._options.transport ?? new TransportImpl(this._options)\n this.processCSVResponse = (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ): AnnotatedCSVResponse =>\n new AnnotatedCSVResponseImpl(\n executor,\n iterableResultExecutor,\n this.transport.chunkCombiner\n )\n }\n\n /**\n * Creates WriteApi for the supplied organization and bucket. BEWARE that returned instances must be closed\n * in order to flush the remaining data and close already scheduled retry executions.\n *\n * @remarks\n * Use {@link WriteOptions} to customize retry strategy options, data chunking\n * and flushing options. See {@link DEFAULT_WriteOptions} to see the defaults.\n *\n * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/write.mjs | write example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/writeAdvanced.mjs | writeAdvanced example},\n * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example}.\n *\n * @param org - Specifies the destination organization for writes. Takes either the ID or Name interchangeably.\n * @param bucket - The destination bucket for writes.\n * @param precision - Timestamp precision for line items.\n * @param writeOptions - Custom write options.\n * @returns WriteApi instance\n */\n getWriteApi(\n org: string,\n bucket: string,\n precision: WritePrecisionType = 'ns',\n writeOptions?: Partial\n ): WriteApi {\n return new WriteApiImpl(\n this.transport,\n org,\n bucket,\n precision,\n writeOptions ?? this._options.writeOptions\n )\n }\n\n /**\n * Creates QueryApi for the supplied organization .\n *\n * @remarks\n * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/query.ts | query.ts example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/queryWithParams.mjs | queryWithParams.mjs example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/rxjs-query.ts | rxjs-query.ts example},\n * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example},\n *\n * @param org - organization or query options\n * @returns QueryApi instance\n */\n getQueryApi(org: string | QueryOptions): QueryApi {\n return new QueryApiImpl(this.transport, this.processCSVResponse, org)\n }\n}\n"],"mappings":"AA2CO,SAASA,GAA2C,CACzD,IAAMC,EAAU,IAAI,YAAY,OAAO,EACvC,MAAO,CACL,OAAOC,EAAmBC,EAAgC,CACxD,IAAMC,EAAS,IAAI,WAAWF,EAAM,OAASC,EAAO,MAAM,EAC1D,OAAAC,EAAO,IAAIF,CAAK,EAChBE,EAAO,IAAID,EAAQD,EAAM,MAAM,EACxBE,CACT,EACA,KAAKC,EAAmBC,EAAeC,EAAyB,CAC9D,IAAMH,EAAS,IAAI,WAAWG,EAAMD,CAAK,EACzC,OAAAF,EAAO,IAAIC,EAAM,SAASC,EAAOC,CAAG,CAAC,EAC9BH,CACT,EACA,aAAaC,EAAmBC,EAAeC,EAAqB,CAClE,OAAON,EAAQ,OAAOI,EAAM,SAASC,EAA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D,OAAO,IAAIK,GAAa,KAAK,UAAW,KAAK,mBAAoBL,CAAG,CACtE,CACF","names":["createTextDecoderCombiner","decoder","first","second","retVal","chunk","start","end","chunksToLines","target","chunkCombiner","chunks","createTextDecoderCombiner","previous","finished","quoted","paused","resumeChunks","bufferReceived","chunk","index","start","c","end","retVal","e","error","cancellable","x","chunksToLinesIterable","source","chunkCombiner","chunks","createTextDecoderCombiner","previous","quoted","chunk","index","start","c","end","LineSplitter","val","line","quoteCount","startIndex","values","count","i","c","start","end","identity","x","typeSerializers","FluxTableColumnImpl","row","_a","val","UNKNOWN_COLUMN","newFluxTableColumn","createFluxTableColumn","object","_b","retVal","retriableStatusCodes","isStatusCodeRetriable","statusCode","IllegalArgumentError","message","HttpError","statusMessage","body","retryAfter","contentType","e","RETRY_CODES","canRetryHttpCall","error","getRetryDelay","retryJitter","retVal","RequestTimedOutError","AbortError","serializeDateTimeAsDate","typeSerializers","x","serializeDateTimeAsNumber","serializeDateTimeAsString","FluxTableMetaDataImpl","columns","col","i","label","errorOnMissingColumn","IllegalArgumentError","UNKNOWN_COLUMN","row","acc","column","createFluxTableMetaData","linesToTables","consumer","splitter","LineSplitter","columns","expectMeta","firstColumnIndex","lastMeta","retVal","error","line","values","size","i","newFluxTableColumn","createFluxTableMetaData","linesToRowsIterable","source","splitter","LineSplitter","columns","expectMeta","firstColumnIndex","lastMeta","line","values","size","i","newFluxTableColumn","createFluxTableMetaData","stringToLines","source","target","quoted","start","index","c","end","symbolObservable","QuerySubscription","observer","executor","value","e","c","_a","noop","completeObserver","next","error","complete","ObservableQuery","decorator","observerOrNext","symbolObservable","DEFAULT_ConnectionOptions","DEFAULT_RetryDelayStrategyOptions","DEFAULT_WriteOptions","createEscaper","characters","replacements","value","retVal","from","i","found","createQuotedEscaper","escaper","escape","zeroPadding","useProcessHrtime","use","lastMillis","stepsInMillis","nanos","millis","zeroPadding","micros","seconds","currentTime","dateToProtocolTimestamp","d","convertTimeToNanos","value","consoleLogger","message","error","provider","Log","setLogger","logger","previous","FLUX_VALUE","FluxParameter","fluxValue","isFluxParameterLike","value","sanitizeString","retVal","i","prepareRetVal","c","fluxString","sanitizeFloat","val","strVal","hasDot","fluxFloat","sanitizeInteger","negative","fluxInteger","sanitizeDateTime","fluxDateTime","fluxDuration","sanitizeRegExp","fluxRegExp","fluxBool","fluxExpression","toFluxValue","flux","strings","values","parts","partIndex","text","sanitized","Point","measurementName","name","value","val","strVal","code","escape","settings","fieldsLine","x","tagsLine","tags","time","convertTimeToNanos","line","RetryStrategyImpl","options","DEFAULT_RetryDelayStrategyOptions","error","failedAttempts","delay","getRetryDelay","nextDelay","i","createRetryDelayStrategy","findShrinkCandidate","first","parent","found","currentParent","RetryBuffer","maxLines","retryLines","onShrink","lines","retryCount","delay","expires","retryTime","origSize","newSize","Log","toAdd","current","toRetry","utf8Length","s","retVal","i","code","WriteBuffer","maxChunkRecords","maxBatchBytes","flushFn","scheduleSend","record","size","utf8Length","_e","lines","retVal","WriteApiImpl","transport","org","bucket","precision","writeOptions","DEFAULT_WriteOptions","currentTime","dateToProtocolTimestamp","scheduleNextSend","createRetryDelayStrategy","RetryBuffer","retryAttempts","expires","self","failedAttempts","error","onRetry","Log","resolve","reject","responseStatusCode","callbacks","_headers","statusCode","HttpError","message","records","i","point","line","points","withRetryBuffer","remaining","tags","value","completeCommunicationObserver","callbacks","state","retVal","data","error","headers","statusCode","getResponseHeaders","response","headers","value","key","previous","FetchTransport","connectionOptions","createTextDecoderCombiner","Log","path","body","options","callbacks","observer","completeCommunicationObserver","cancelled","signal","pausePromise","resumeQuickly","resume","controller","reader","chunk","useResume","msg","resolve","buffer","text","e","headerError","HttpError","_a","done","AbortError","responseStarted","_b","responseContentType","responseType","method","other","url","request","DEFAULT_dialect","QueryApiImpl","transport","createCSVResponse","org","options","query","type","gzip","headers","path","body","consumer","rowMapper","request","_a","QueryApiImpl_default","defaultRowMapping","values","tableMeta","AnnotatedCSVResponseImpl","executor","iterableResultExecutor","chunkCombiner","chunksToLinesIterable","linesToRowsIterable","ObservableQuery","observer","chunksToLines","linesToTables","e","consumer","rowMapper","retVal","resolve","reject","toAdd","error","line","InfluxDB","options","_a","IllegalArgumentError","url","FetchTransport","executor","iterableResultExecutor","AnnotatedCSVResponseImpl","org","bucket","precision","writeOptions","WriteApiImpl","QueryApiImpl_default"]} \ No newline at end of file diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/index.d.ts b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.d.ts new file mode 100644 index 0000000..36a0aca --- /dev/null +++ b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.d.ts @@ -0,0 +1,1197 @@ +/** + * ChunkCombiner is a simplified platform-neutral manipulation of Uint8arrays + * that allows to process text data on the fly. The implementation can be optimized + * for the target platform (node vs browser). + */ +interface ChunkCombiner { + /** + * Concatenates first and second chunk. + * @param first - first chunk + * @param second - second chunk + * @returns first + second + */ + concat(first: Uint8Array, second: Uint8Array): Uint8Array; + /** + * Converts chunk into a string. + * @param chunk - chunk + * @param start - start index + * @param end - end index + * @returns string representation of chunk slice + */ + toUtf8String(chunk: Uint8Array, start: number, end: number): string; + /** + * Creates a new chunk from the supplied chunk. + * @param chunk - chunk to copy + * @param start - start index + * @param end - end index + * @returns a copy of a chunk slice + */ + copy(chunk: Uint8Array, start: number, end: number): Uint8Array; +} +/** + * Creates a chunk combiner instance that uses UTF-8 + * TextDecoder to decode Uint8Arrays into strings. + */ +declare function createTextDecoderCombiner(): ChunkCombiner; + +/** + * Allows to cancel a running execution. + */ +interface Cancellable { + /** + * Cancels execution. + */ + cancel(): void; + isCancelled(): boolean; +} + +/** + * Type of HTTP headers. + */ +type HttpHeaders = { + [header: string]: string | string[] | undefined; +}; + +/** + * Informs about a start of response processing. + * @param headers - response HTTP headers + * @param statusCode - response status code + */ +type ResponseStartedFn = (headers: HttpHeaders, statusCode?: number) => void; +/** + * Observes communication with the server. + */ +interface CommunicationObserver { + /** + * Data chunk received, can be called multiple times. + * @param data - data + * @returns when `false` value is returned and {@link CommunicationObserver.useResume} is defined, + * future calls to `next` are paused until resume is called. + */ + next(data: T): void | boolean; + /** + * Communication ended with an error. + */ + error(error: Error): void; + /** + * Communication was successful. + */ + complete(): void; + /** + * Informs about a start of response processing. + */ + responseStarted?: ResponseStartedFn; + /** + * Setups cancelllable for this communication. + */ + useCancellable?: (cancellable: Cancellable) => void; + /** + * Setups a callback that resumes reading of next data, it is called whenever + * {@link CommunicationObserver.next} returns `false`. + * + * @param resume - a function that will resume reading of next data when called + */ + useResume?: (resume: () => void) => void; +} + +/** + * ChunksToLines is a transformation that accepts Uint8Array instances + * and emmits strings representing CSV lines. + * @param target - target to emmit CSV lines to + * @param chunkCombiner - chunk combiner + * @returns communication obrver to accept Uint8Arrays + */ +declare function chunksToLines(target: CommunicationObserver, chunkCombiner?: ChunkCombiner): CommunicationObserver; + +/** + * ChunksToLinesIterable is a transformation that accepts + * an iterable of Uint8Array instances and returns iterable of lines. + * @param source - iterable of transport buffers + * @param chunkCombiner - chunk combiner + * @returns iterable of lines + */ +declare function chunksToLinesIterable(source: AsyncIterable, chunkCombiner?: ChunkCombiner): AsyncIterableIterator; + +/** + * Type of query result column, see {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types } + */ +type ColumnType = 'boolean' | 'unsignedLong' | 'long' | 'double' | 'string' | 'base64Binary' | 'dateTime:RFC3339' | 'duration' | string; +/** + * FluxTableColumn describes {@link http://bit.ly/flux-spec#table | flux table} column. + */ +interface FluxTableColumn { + /** + * Label (e.g., "_start", "_stop", "_time"). + */ + label: string; + /** + * The data type of column (e.g., "string", "long", "dateTime:RFC3339"). + */ + dataType: ColumnType; + /** + * Boolean flag indicating if the column is a part of the table's group key. + */ + group: boolean; + /** + * Default value to be used for rows whose string value is an empty string. + */ + defaultValue: string; + /** + * Index of this column in a row array. + */ + index: number; + /** + * Get returns a JavaScript object of this column in the supplied result row, using default deserializers. + * @param row - a data row + * @returns column value + */ + get: (row: string[]) => any; +} +/** + * A dictionary of serializers of particular types returned by a flux query. + * See {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types } + */ +declare const typeSerializers: Record any>; +declare const UNKNOWN_COLUMN: FluxTableColumn; +/** + * Creates a new flux table column. + * @returns column instance + */ +declare function newFluxTableColumn(): FluxTableColumn; +/** + * Creates a flux table column from a partial FluxTableColumn. + * @param object - source object + * @returns column instance + */ +declare function createFluxTableColumn(object: Partial): FluxTableColumn; + +/** + * serializeDateTimeAsDate changes type serializers to return JavaScript Date instances + * for 'dateTime:RFC3339' query result data type. Empty value is converted to null. + * @remarks + * Please note that the result has millisecond precision whereas InfluxDB returns dateTime + * in nanosecond precision. + */ +declare function serializeDateTimeAsDate(): void; +/** + * serializeDateTimeAsNumber changes type serializers to return milliseconds since epoch + * for 'dateTime:RFC3339' query result data type. Empty value is converted to null. + * @remarks + * Please note that the result has millisecond precision whereas InfluxDB returns dateTime + * in nanosecond precision. + */ +declare function serializeDateTimeAsNumber(): void; +/** + * serializeDateTimeAsString changes type serializers to return string values + * for `dateTime:RFC3339` query result data type. Empty value is converted to null. + */ +declare function serializeDateTimeAsString(): void; +/** + * Represents metadata of a {@link http://bit.ly/flux-spec#table | flux table}. + */ +interface FluxTableMetaData { + /** + * Table columns. + */ + columns: Array; + /** + * Gets columns by name + * @param label - column label + * @param errorOnMissingColumn - throw error on missing column (by default), return UNKNOWN_COLUMN when false + * @returns table column + * @throws IllegalArgumentError if column is not found + **/ + column(label: string, errorOnMissingColumn?: boolean): FluxTableColumn; + /** + * Creates an object out of the supplied row with the help of column descriptors. + * @param row - a row with data for each column + */ + toObject(row: string[]): { + [key: string]: any; + }; + /** + * Gets column values out of the supplied row. + * @param row - a row with data for each column + * @param column - column name + * @returns column value, undefined for unknown column + */ + get(row: string[], column: string): any; +} +/** + * Created FluxTableMetaData from the columns supplied. + * @param columns - columns + * @returns - instance + */ +declare function createFluxTableMetaData(columns: FluxTableColumn[]): FluxTableMetaData; +/** Wraps values and associated metadata of a query result row */ +interface Row { + values: string[]; + tableMeta: FluxTableMetaData; +} + +/** + * Observes results of a flux query. + */ +interface FluxResultObserver { + /** + * Inform about a next record in a table. + * @param row - flux result + * @param tableMeta - actual table metata for the row supplied + * @returns when `false` value is returned and {@link FluxResultObserver.useResume} is defined, + * future calls to `next` are paused until resume is called. + */ + next(row: T, tableMeta: FluxTableMetaData): void | boolean; + /** + * Signalizes processing error. + */ + error(error: Error): void; + /** + * Signalizes completition. + */ + complete(): void; + /** + * Setups cancellable that can abort flux result processing. + */ + useCancellable?: (cancellable: Cancellable) => void; + /** + * Setups a callback that resumes reading of next data, it is called whenever + * {@link FluxResultObserver.next} returns `false`. + * + * @param resume - a function that will resume reading of next data when called + */ + useResume?: (resume: () => void) => void; +} + +/** + * LinesToTables creates a transformation that accepts (flux) annotated CSV lines + * and emits rows together with table metadata. + */ +declare function linesToTables(consumer: FluxResultObserver): CommunicationObserver; + +/** + * LinesToRowsIterable is a transformation that accepts + * an iterable of flux annotated CSV lines and returns + * an iterable of rows (row values and table metadata). + */ +declare function linesToRowsIterable(source: AsyncIterable): AsyncIterableIterator; + +/** + * Optimized tokenizer of a single CSV line. + */ +declare class LineSplitter { + /** returned value when reused */ + reusedValues: string[]; + /** last length of elements in */ + lastSplitLength: number; + private _reuse; + /** + * Reuse returned array between consecutive calls. + */ + get reuse(): boolean; + set reuse(val: boolean); + /** + * Sets the reuse flag and returns this. + */ + withReuse(): LineSplitter; + /** + * Splits the supplied line to elements that are separated by + * comma with values possibly escaped within double quotes ("value") + * @param line - line + * @returns array of splitted parts + */ + splitLine(line: string | undefined | null): string[]; + private getValue; +} + +/** + * StringToLines is a transformation that emmits strings for each CSV + * line in the supplied source string. + * @param source - source string + * @param target - target to emmit CSV lines to + * @returns communication obrver to accept Uint8Arrays + */ +declare function stringToLines(source: string, target: CommunicationObserver): void; + +declare global { + interface SymbolConstructor { + readonly observable: symbol; + } +} +/** Symbol.observable or a string "\@\@observable". Used for interop */ +declare const symbolObservable: typeof Symbol.observable | "@@observable"; + +/** Type of {@link Observer.next} */ +type ObserverNext = (value: T) => void; +/** Type of {@link Observer.error} */ +type ObserverError = (e: any) => void; +/** Type of {@link Observer.complete} */ +type ObserverComplete = () => void; +/** Observer mimics Observer from ECMAScript TC39 Observable proposal */ +interface Observer { + next: ObserverNext; + error: ObserverError; + complete: ObserverComplete; +} +interface Subscribable { + subscribe(observer: Partial>): Subscription; +} +/** + * An observable that aligns with the + * {@link https://github.com/tc39/proposal-observable | TC39 observable proposal} and + * can be consumed by other observable libraries like + * {@link https://github.com/ReactiveX/rxjs | rx js} or + * {@link https://github.com/zenparsing/zen-observable | zen-observable}. + */ +interface Observable { + subscribe(): Subscription; + subscribe(observer: Partial>): Subscription; + subscribe(next: ObserverNext, error?: ObserverError, complete?: ObserverComplete): Subscription; + [Symbol.observable](): Subscribable; +} +/** Subscription mimics Subscription from ECMAScript TC39 Observable proposal */ +interface Subscription { + readonly closed: boolean; + unsubscribe(): void; +} + +/** + * A factory that returns async iterables. + */ +type IterableResultExecutor = () => AsyncIterable; +/** + * AnnotatedCSVResponse provides various ways of how to + * process data from an annotated CSV response stream, + * which is returned as a result of a flux script execution. + */ +interface AnnotatedCSVResponse { + /** + * IterateLines returns iterable of CSV response lines suitable for `for-await` loop consumption. + * @returns iterable of lines + */ + iterateLines(): AsyncIterable; + /** + * IterateRows returns iterable of response table rows suitable for `for-await` loop consumption. + * @returns iterable of rows + */ + iterateRows(): AsyncIterable; + /** + * Lines creates a cold observable of the CSV response lines. + * @returns observable of CSV result lines + */ + lines(): Observable; + /** + * Rows creates a cold observable of the CSV response rows. + * @returns observable of CSV result rows + */ + rows(): Observable; + /** + * ConsumesLines consumes result lines (including empty and annotation lines) + * through the supplied consumer. See [annotated-csv](https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/). + * @param consumer - csv result lines and error consumer + */ + consumeLines(consumer: CommunicationObserver): void; + /** + * ConsumeRows consumes result rows through the supplied consumer. + * + * @param consumer - csv result lines and error consumer + */ + consumeRows(consumer: FluxResultObserver): void; + /** + * CollectRows collects all the result rows in the returned Promise. + * This method is suitable to collect simple results. Use with caution, + * a possibly huge stream of results is copied to memory. + * + * @param rowMapper - maps the supplied row to an item that is then collected, + * undefined return values are not collected. If no rowMapper is supplied, + * `row => tableMeta.toObject(row.values)` is used. + * @returns Promise of mapped results + */ + collectRows(rowMapper?: (values: string[], tableMeta: FluxTableMetaData) => T | undefined): Promise>; + /** + * CollectLines collects all result lines in the returned Promise. + * This method is suitable to collect simple results. Use with caution, + * a possibly huge stream of lines is copied to memory. + * + * @returns Promise of returned csv lines + */ + collectLines(): Promise>; +} + +/** APIExecutor executes the API and passes its response to the supplied consumer */ +type APIExecutor = (consumer: CommunicationObserver) => void; + +/** + * Options for sending a request message. + */ +interface SendOptions { + /** HTTP method (POST, PUT, GET, PATCH ...) */ + method: string; + /** Request HTTP headers. */ + headers?: { + [key: string]: string; + }; + /** When specified, message body larger than the treshold is gzipped */ + gzipThreshold?: number; + /** Abort signal */ + signal?: AbortSignal; +} +/** + * Simpified platform-neutral transport layer for communication with InfluxDB. + */ +interface Transport { + /** + * Send data to the server and receive communication events via callbacks. + * + * @param path - HTTP request path + * @param requestBody - HTTP request body + * @param options - send options + * @param callbacks - communication callbacks to received data in Uint8Array + */ + send(path: string, requestBody: string, options: SendOptions, callbacks?: Partial>): void; + /** + * Sends data to the server and receives decoded result. The type of the result depends on + * response's content-type (deserialized json, text). + + * @param path - HTTP request path + * @param requestBody - request body + * @param options - send options + * @returns response data + */ + request(path: string, requestBody: any, options: SendOptions, responseStarted?: ResponseStartedFn): Promise; + /** + * Sends requestBody and returns response chunks in an async iterable + * that can be easily consumed in an `for-await` loop. + * + * @param path - HTTP request path + * @param requestBody - request body + * @param options - send options + * @returns async iterable + */ + iterate(path: string, requestBody: any, options: SendOptions): AsyncIterableIterator; + /** + * Combines response chunks to create a single response object. + */ + readonly chunkCombiner: ChunkCombiner; +} + +/** + * Settings that control the way of how a {@link Point} is serialized + * to a protocol line. + */ +interface PointSettings { + /** default tags to add to every point */ + defaultTags?: { + [key: string]: string; + }; + /** convertTime serializes Point's timestamp to a line protocol value */ + convertTime?: (value: string | number | Date | undefined) => string | undefined; +} +/** + * Point defines values of a single measurement. + */ +declare class Point { + private name; + private tags; + /** escaped field values */ + fields: { + [key: string]: string; + }; + private time; + /** + * Create a new Point with specified a measurement name. + * + * @param measurementName - the measurement name + */ + constructor(measurementName?: string); + /** + * Sets point's measurement. + * + * @param name - measurement name + * @returns this + */ + measurement(name: string): Point; + /** + * Adds a tag. The caller has to ensure that both name and value are not empty + * and do not end with backslash. + * + * @param name - tag name + * @param value - tag value + * @returns this + */ + tag(name: string, value: string): Point; + /** + * Adds a boolean field. + * + * @param field - field name + * @param value - field value + * @returns this + */ + booleanField(name: string, value: boolean | any): Point; + /** + * Adds an integer field. + * + * @param name - field name + * @param value - field value + * @returns this + * @throws NaN or out of int64 range value is supplied + */ + intField(name: string, value: number | any): Point; + /** + * Adds an unsigned integer field. + * + * @param name - field name + * @param value - field value + * @returns this + * @throws NaN out of range value is supplied + */ + uintField(name: string, value: number | any): Point; + /** + * Adds a number field. + * + * @param name - field name + * @param value - field value + * @returns this + * @throws NaN/Infinity/-Infinity is supplied + */ + floatField(name: string, value: number | any): Point; + /** + * Adds a string field. + * + * @param name - field name + * @param value - field value + * @returns this + */ + stringField(name: string, value: string | any): Point; + /** + * Sets point timestamp. Timestamp can be specified as a Date (preferred), number, string + * or an undefined value. An undefined value instructs to assign a local timestamp using + * the client's clock. An empty string can be used to let the server assign + * the timestamp. A number value represents time as a count of time units since epoch, the + * exact time unit then depends on the {@link InfluxDB.getWriteApi | precision} of the API + * that writes the point. + * + * Beware that the current time in nanoseconds can't precisely fit into a JS number, + * which can hold at most 2^53 integer number. Nanosecond precision numbers are thus supplied as + * a (base-10) string. An application can also use ES2020 BigInt to represent nanoseconds, + * BigInt's `toString()` returns the required high-precision string. + * + * Note that InfluxDB requires the timestamp to fit into int64 data type. + * + * @param value - point time + * @returns this + */ + timestamp(value: Date | number | string | undefined): Point; + /** + * Creates an InfluxDB protocol line out of this instance. + * @param settings - settings control serialization of a point timestamp and can also add default tags, + * nanosecond timestamp precision is used when no `settings` or no `settings.convertTime` is supplied. + * @returns an InfluxDB protocol line out of this instance + */ + toLineProtocol(settings?: Partial): string | undefined; + toString(): string; +} + +/** + * Asynchronous API that writes time-series data into InfluxDB. + * This API always buffers points/lines to create batches under the hood + * to optimize data transfer to InfluxDB server, use `flush` to send + * the buffered data to InfluxDB immediately. + */ +interface WriteApi extends PointSettings { + /** + * Instructs to use the following default tags when writing points. + * Not applicable for writing records/lines. + * @param tags - default tags + * @returns this + */ + useDefaultTags(tags: { + [key: string]: string; + }): WriteApi; + /** + * Write a line of [Line Protocol](https://bit.ly/2QL99fu). + * + * @param record - line of InfluxDB Line Protocol + */ + writeRecord(record: string): void; + /** + * Write lines of [Line Protocol](https://bit.ly/2QL99fu). + * + * @param records - lines in InfluxDB Line Protocol + */ + writeRecords(records: Array): void; + /** + * Write point. + * + * @param point - point to write + */ + writePoint(point: Point): void; + /** + * Write points. + * + * @param points - points to write + */ + writePoints(points: ArrayLike): void; + /** + * Flushes pending writes to the server. + * @param withRetryBuffer - flush also all the scheduled retries + * @returns completition promise + */ + flush(withRetryBuffer?: boolean): Promise; + /** + * Flushes this writer and cancels retries of write operations that failed. + * @returns completition promise + */ + close(): Promise; + /** + * Unlike close, dispose simply quits without trying to flush + * the buffered data. + * @returns count of points that were not written to InfluxDB + */ + dispose(): number; + /** + * HTTP path and query parameters of InfluxDB query API. It is + * automatically initialized to `/api/v2/write?org=...`, + * but it can be changed after the API is obtained. + */ + path: string; +} + +/** + * Option for the communication with InfluxDB server. + */ +interface ConnectionOptions { + /** base URL */ + url: string; + /** authentication token */ + token?: string; + /** + * socket timeout, 10000 milliseconds by default in node.js + * @defaultValue 10000 + */ + timeout?: number; + /** + * TransportOptions supply extra options for the transport layer, they differ between node.js and browser/deno. + * Node.js transport accepts options specified in {@link https://nodejs.org/api/http.html#http_http_request_options_callback | http.request } or + * {@link https://nodejs.org/api/https.html#https_https_request_options_callback | https.request }. For example, an `agent` property can be set to + * {@link https://www.npmjs.com/package/proxy-http-agent | setup HTTP/HTTPS proxy }, {@link https://nodejs.org/api/tls.html#tls_tls_connect_options_callback | rejectUnauthorized } + * property can disable TLS server certificate verification. Additionally, + * {@link https://github.com/follow-redirects/follow-redirects | follow-redirects } property can be also specified + * in order to follow redirects in node.js. + * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | fetch } is used under the hood in browser/deno. + * For example, + * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | redirect } property can be set to 'error' to abort request if a redirect occurs. + */ + transportOptions?: { + [key: string]: any; + }; + /** + * Default HTTP headers to send with every request. + */ + headers?: Record; + /** + * Full HTTP web proxy URL including schema, for example http://your-proxy:8080. + */ + proxyUrl?: string; +} +/** default connection options */ +declare const DEFAULT_ConnectionOptions: Partial; +/** + * Options that configure strategy for retrying failed requests. + */ +interface RetryDelayStrategyOptions { + /** add `random(retryJitter)` milliseconds delay when retrying HTTP calls */ + retryJitter: number; + /** minimum delay when retrying write (milliseconds) */ + minRetryDelay: number; + /** maximum delay when retrying write (milliseconds) */ + maxRetryDelay: number; + /** base for the exponential retry delay */ + exponentialBase: number; + /** + * randomRetry indicates whether the next retry delay is deterministic (false) or random (true). + * The deterministic delay starts with `minRetryDelay * exponentialBase` and it is multiplied + * by `exponentialBase` until it exceeds `maxRetryDelay`. + * When random is `true`, the next delay is computed as a random number between next retry attempt (upper) + * and the lower number in the deterministic sequence. `random(retryJitter)` is added to every returned value. + */ + randomRetry: boolean; +} +/** + * Options that configure strategy for retrying failed InfluxDB write operations. + */ +interface WriteRetryOptions extends RetryDelayStrategyOptions { + /** + * WriteFailed is called to inform about write errors. + * @param this - the instance of the API that failed + * @param error - write error + * @param lines - failed lines + * @param attempt - count of already failed attempts to write the lines (1 ... maxRetries+1) + * @param expires - expiration time for the lines to be retried in millis since epoch + * @returns a Promise to force the API to use it as a result of the flush operation, + * void/undefined to continue with default retry mechanism + */ + writeFailed(this: WriteApi, error: Error, lines: Array, attempt: number, expires: number): Promise | void; + /** + * WriteSuccess is informed about successfully written lines. + * @param this - the instance of the API in use + * @param lines - written lines + */ + writeSuccess(this: WriteApi, lines: Array): void; + /** + * WriteRetrySkipped is informed about lines that were removed from the retry buffer + * to keep the size of the retry buffer under the configured limit (maxBufferLines). + * @param entry - lines that were skipped + */ + writeRetrySkipped(entry: { + lines: Array; + expires: number; + }): void; + /** max count of retries after the first write fails */ + maxRetries: number; + /** max time (millis) that can be spent with retries */ + maxRetryTime: number; + /** the maximum size of retry-buffer (in lines) */ + maxBufferLines: number; +} +/** + * Options used by {@link WriteApi} . + */ +interface WriteOptions extends WriteRetryOptions { + /** max number of records/lines to send in a batch */ + batchSize: number; + /** delay between data flushes in milliseconds, at most `batch size` records are sent during flush */ + flushInterval: number; + /** default tags, unescaped */ + defaultTags?: Record; + /** HTTP headers that will be sent with every write request */ + headers?: { + [key: string]: string; + }; + /** When specified, write bodies larger than the threshold are gzipped */ + gzipThreshold?: number; + /** max size of a batch in bytes */ + maxBatchBytes: number; + /** InfluxDB Enterprise write consistency as explained in https://docs.influxdata.com/enterprise_influxdb/v1.9/concepts/clustering/#write-consistency */ + consistency?: 'any' | 'one' | 'quorum' | 'all'; +} +/** default RetryDelayStrategyOptions */ +declare const DEFAULT_RetryDelayStrategyOptions: { + retryJitter: number; + minRetryDelay: number; + maxRetryDelay: number; + exponentialBase: number; + randomRetry: boolean; +}; +/** default writeOptions */ +declare const DEFAULT_WriteOptions: WriteOptions; +/** + * Options used by {@link InfluxDB} . + */ +interface ClientOptions extends ConnectionOptions { + /** supplies and overrides default writing options */ + writeOptions?: Partial; + /** specifies custom transport */ + transport?: Transport; +} +/** + * Timestamp precision used in write operations. + * See {@link https://docs.influxdata.com/influxdb/latest/api/#operation/PostWrite } + */ +type WritePrecisionType = 'ns' | 'us' | 'ms' | 's'; + +/** + * Strategy for calculating retry delays. + */ +interface RetryDelayStrategy { + /** + * Returns delay for a next retry + * @param error - reason for retrying + * @param failedAttempts - a count of already failed attempts, 1 being the first + * @returns milliseconds to wait before retrying + */ + nextDelay(error?: Error, failedAttempts?: number): number; + /** Implementation should reset its state, this is mandatory to call upon success. */ + success(): void; +} +/** + * Interface for errors to inform that an associated operation can be retried. + */ +interface RetriableDecision { + /** + * Informs whether this can be retried. + */ + canRetry(): boolean; + /** + * Get the delay in milliseconds to retry the action. + * @returns 0 to let the implementation decide, miliseconds delay otherwise + */ + retryAfter(): number; +} +/** isStatusCodeRetriable checks whether the supplied HTTP status code is retriable. */ +declare function isStatusCodeRetriable(statusCode: number): boolean; +/** IllegalArgumentError is thrown when illegal argument is supplied. */ +declare class IllegalArgumentError extends Error { + constructor(message: string); +} +/** + * A general HTTP error. + */ +declare class HttpError extends Error implements RetriableDecision { + readonly statusCode: number; + readonly statusMessage: string | undefined; + readonly body?: string | undefined; + readonly contentType?: string | null | undefined; + private _retryAfter; + /** application error code, when available */ + code: string | undefined; + /** json error response */ + json: any; + constructor(statusCode: number, statusMessage: string | undefined, body?: string | undefined, retryAfter?: string | undefined | null, contentType?: string | null | undefined, message?: string); + private setRetryAfter; + canRetry(): boolean; + retryAfter(): number; +} +/** + * Tests the error in order to know if an HTTP call can be retried. + * @param error - error to test + * @returns true for a retriable error + */ +declare function canRetryHttpCall(error: any): boolean; +/** + * Gets retry delay from the supplied error, possibly using random number up to retryJitter. + */ +declare function getRetryDelay(error?: Error, retryJitter?: number): number; +/** RequestTimedOutError indicates request timeout in the communication with the server */ +declare class RequestTimedOutError extends Error implements RetriableDecision { + constructor(); + canRetry(): boolean; + retryAfter(): number; +} +/** AbortError indicates that the communication with the server was aborted */ +declare class AbortError extends Error implements RetriableDecision { + constructor(); + canRetry(): boolean; + retryAfter(): number; +} + +/** + * Provides functions escape specific parts in InfluxDB line protocol. + */ +declare const escape: { + /** + * Measurement escapes measurement names. + */ + measurement: (value: string) => string; + /** + * Quoted escapes quoted values, such as database names. + */ + quoted: (value: string) => string; + /** + * TagEscaper escapes tag keys, tag values, and field keys. + */ + tag: (value: string) => string; +}; + +declare function useProcessHrtime(use: boolean): boolean; +/** + * Exposes functions that creates strings that represent a timestamp that + * can be used in the line protocol. Micro and nano timestamps are emulated + * depending on the js platform in use. + */ +declare const currentTime: { + s: () => string; + ms: () => string; + us: () => string; + ns: () => string; + seconds: () => string; + millis: () => string; + micros: () => string; + nanos: () => string; +}; +/** + * dateToProtocolTimestamp provides converters for JavaScript Date to InfluxDB Write Protocol Timestamp. Keys are supported precisions. + */ +declare const dateToProtocolTimestamp: { + s: (d: Date) => string; + ms: (d: Date) => string; + us: (d: Date) => string; + ns: (d: Date) => string; +}; +/** + * convertTimeToNanos converts Point's timestamp to a string. + * @param value - supported timestamp value + * @returns line protocol value + */ +declare function convertTimeToNanos(value: string | number | Date | undefined): string | undefined; + +/** + * Logging interface. + */ +interface Logger { + error(message: string, err?: any): void; + warn(message: string, err?: any): void; +} +/** + * Logger that logs to console.out + */ +declare const consoleLogger: Logger; +declare const Log: Logger; +/** + * Sets custom logger. + * @param logger - logger to use + * @returns previous logger + */ +declare function setLogger(logger: Logger): Logger; + +/** Property that offers a function that returns flux-sanitized value of an object. */ +declare const FLUX_VALUE: unique symbol; +/** + * A flux parameter can print its (sanitized) flux value. + */ +interface FluxParameterLike { + [FLUX_VALUE](): string; +} +/** + * Represents a parameterized query. + */ +interface ParameterizedQuery { + /** + * Returns flux query with sanitized parameters. + */ + toString(): string; +} +/** + * Creates a flux string literal. + */ +declare function fluxString(value: any): FluxParameterLike; +/** + * Sanitizes float value to avoid injections. + * @param value - InfluxDB float literal + * @returns sanitized float value + * @throws Error if the the value cannot be sanitized + */ +declare function sanitizeFloat(value: any): string; +/** + * Creates a flux float literal. + */ +declare function fluxFloat(value: any): FluxParameterLike; +/** + * Sanitizes integer value to avoid injections. + * @param value - InfluxDB integer literal + * @returns sanitized integer value + * @throws Error if the the value cannot be sanitized + */ +declare function sanitizeInteger(value: any): string; +/** + * Creates a flux integer literal. + */ +declare function fluxInteger(value: any): FluxParameterLike; +/** + * Creates flux date-time literal. + */ +declare function fluxDateTime(value: any): FluxParameterLike; +/** + * Creates flux date-time literal. + */ +declare function fluxDuration(value: any): FluxParameterLike; +/** + * Creates flux regexp literal out of a regular expression. See + * https://docs.influxdata.com/flux/latest/data-types/basic/regexp/#regular-expression-syntax + * for details. + */ +declare function fluxRegExp(value: any): FluxParameterLike; +/** + * Creates flux boolean literal. + */ +declare function fluxBool(value: any): FluxParameterLike; +/** + * Assumes that the supplied value is flux expression or literal that does not need sanitizing. + * + * @param value - any value + * @returns the supplied value as-is + */ +declare function fluxExpression(value: any): FluxParameterLike; +/** + * Escapes content of the supplied parameter so that it can be safely embedded into flux query. + * @param value - parameter value + * @returns sanitized flux value or an empty string if it cannot be converted + */ +declare function toFluxValue(value: any): string; +/** + * Flux is a tagged template that sanitizes supplied parameters + * to avoid injection attacks in flux. + */ +declare function flux(strings: TemplateStringsArray, ...values: any): ParameterizedQuery; + +/** QueryOptions contains QueryApi configuration options. */ +interface QueryOptions { + /** + * Specifies the name of the organization executing the query. Takes either the ID or Name interchangeably. + */ + org: string; + /** + * Type of the query, default is "flux" + */ + type?: 'flux'; + /** + * Requests gzip encoded response. + */ + gzip?: boolean; + /** + * Specifies the time that should be reported as "now" in the query. RFC3339 value must be returned, + * for example `new Date().toISOString()`. + */ + now?: () => string; + /** + * HTTP headers that will be sent with every query request. + */ + headers?: { + [key: string]: string; + }; +} +/** + * Query InfluxDB. Provides methods that notify about result lines of the executed query. + * See {@link https://docs.influxdata.com/influxdb/latest/api/#operation/PostQuery } + */ +interface QueryApi { + /** + * Returns a new query API with extra options applied. + * @param options - query options to use + * @returns queryApi instance with the supplied options + */ + with(options: Partial): QueryApi; + /** + * Response returns an AnnotatedCSVResponse instance that executes + * the query when asked for data. + * + * @param query - query + * @returns response with various methods to process data from the returned annotated + * CSV response data stream + */ + response(query: string | ParameterizedQuery): AnnotatedCSVResponse; + /** + * IterateLines executes the supplied query and returns results in + * an async iterable of annotated CSV lines. + * Async iterables are best consumed by `for-await` loop. + * + * @param query - query + * @returns async iterable of CSV result lines + */ + iterateLines(query: string | ParameterizedQuery): AsyncIterable; + /** + * IterateRows executes the supplied query and returns results in + * an async iterable of row data and table metadata pairs. + * Async iterables are best consumed by `for-await` loop. + * + * @param query - query + * @returns async iterable of CSV result lines + */ + iterateRows(query: string | ParameterizedQuery): AsyncIterable; + /** + * Creates a cold observable of the lines returned by the given query. + * + * @param query - query + * @returns observable of CSV result lines + */ + lines(query: string | ParameterizedQuery): Observable; + /** + * Creates a cold observable of the rows returned by the given query. + * + * @param query - query + * @returns observable of result rows + */ + rows(query: string | ParameterizedQuery): Observable; + /** + * Executes the query and receives result lines (including empty and annotation lines) + * through the supplied consumer. See [annotated-csv](https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/). + * + * @param query - query + * @param consumer - csv result lines and error consumer + */ + queryLines(query: string | ParameterizedQuery, consumer: CommunicationObserver): void; + /** + * Executes the query and receives table metadata and rows through the supplied consumer. + * + * @param query - query + * @param consumer - result rows and error consumer + */ + queryRows(query: string | ParameterizedQuery, consumer: FluxResultObserver): void; + /** + * QueryRaw executes a query and returns the full response as a string. + * Use with caution, a possibly huge stream is copied to memory. + * + * @param query - query + * @returns Promise of response text + */ + queryRaw(query: string | ParameterizedQuery): Promise; + /** + * CollectRows executes the query and collects all the results in the returned Promise. + * This method is suitable to collect simple results. Use with caution, + * a possibly huge stream of results is copied to memory. + * + * @param query - query + * @param rowMapper - maps the supplied row to an item that is then collected, + * undefined return values are not collected. If no rowMapper is supplied, + * `row => tableMeta.toObject(row.values)` is used. + * @returns Promise of mapped results + */ + collectRows(query: string | ParameterizedQuery, rowMapper?: (values: string[], tableMeta: FluxTableMetaData) => T | undefined): Promise>; + /** + * CollectLines executes the query and collects all result lines in the returned Promise. + * This method is suitable to collect simple results. Use with caution, + * a possibly huge stream of lines is copied to memory. + * + * @param query - query + * @returns Promise of returned csv lines + */ + collectLines(query: string | ParameterizedQuery): Promise>; +} + +/** + * InfluxDB entry point that configures communication with InfluxDB server + * and provide APIs to write and query data. + */ +declare class InfluxDB { + private _options; + readonly transport: Transport; + readonly processCSVResponse: (executor: APIExecutor, iterableResultExecutor: IterableResultExecutor) => AnnotatedCSVResponse; + /** + * Creates influxdb client options from an options object or url. + * @param options - client options + */ + constructor(options: ClientOptions | string); + /** + * Creates WriteApi for the supplied organization and bucket. BEWARE that returned instances must be closed + * in order to flush the remaining data and close already scheduled retry executions. + * + * @remarks + * Use {@link WriteOptions} to customize retry strategy options, data chunking + * and flushing options. See {@link DEFAULT_WriteOptions} to see the defaults. + * + * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/write.mjs | write example}, + * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/writeAdvanced.mjs | writeAdvanced example}, + * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example}. + * + * @param org - Specifies the destination organization for writes. Takes either the ID or Name interchangeably. + * @param bucket - The destination bucket for writes. + * @param precision - Timestamp precision for line items. + * @param writeOptions - Custom write options. + * @returns WriteApi instance + */ + getWriteApi(org: string, bucket: string, precision?: WritePrecisionType, writeOptions?: Partial): WriteApi; + /** + * Creates QueryApi for the supplied organization . + * + * @remarks + * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/query.ts | query.ts example}, + * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/queryWithParams.mjs | queryWithParams.mjs example}, + * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/rxjs-query.ts | rxjs-query.ts example}, + * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example}, + * + * @param org - organization or query options + * @returns QueryApi instance + */ + getQueryApi(org: string | QueryOptions): QueryApi; +} + +export { APIExecutor, AbortError, AnnotatedCSVResponse, Cancellable, ChunkCombiner, ClientOptions, ColumnType, CommunicationObserver, ConnectionOptions, DEFAULT_ConnectionOptions, DEFAULT_RetryDelayStrategyOptions, DEFAULT_WriteOptions, FLUX_VALUE, FluxParameterLike, FluxResultObserver, FluxTableColumn, FluxTableMetaData, HttpHeaders as Headers, HttpError, HttpHeaders, IllegalArgumentError, InfluxDB, IterableResultExecutor, LineSplitter, Log, Logger, Observable, Observer, ObserverComplete, ObserverError, ObserverNext, ParameterizedQuery, Point, PointSettings, QueryApi, QueryOptions, RequestTimedOutError, ResponseStartedFn, RetriableDecision, RetryDelayStrategy, RetryDelayStrategyOptions, Row, SendOptions, Subscribable, Subscription, Transport, UNKNOWN_COLUMN, WriteApi, WriteOptions, WritePrecisionType, WriteRetryOptions, canRetryHttpCall, chunksToLines, chunksToLinesIterable, consoleLogger, convertTimeToNanos, createFluxTableColumn, createFluxTableMetaData, createTextDecoderCombiner, currentTime, dateToProtocolTimestamp, escape, flux, fluxBool, fluxDateTime, fluxDuration, fluxExpression, fluxFloat, fluxInteger, fluxRegExp, fluxString, getRetryDelay, isStatusCodeRetriable, linesToRowsIterable, linesToTables, newFluxTableColumn, sanitizeFloat, sanitizeInteger, serializeDateTimeAsDate, serializeDateTimeAsNumber, serializeDateTimeAsString, setLogger, stringToLines, symbolObservable, toFluxValue, typeSerializers, useProcessHrtime }; diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/index.js b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.js new file mode 100644 index 0000000..83562aa --- /dev/null +++ b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.js @@ -0,0 +1,6 @@ +"use strict";var Ne=Object.create;var B=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var Je=(r,e)=>{for(var t in e)B(r,t,{get:e[t],enumerable:!0})},Se=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of qe(e))!je.call(r,i)&&i!==t&&B(r,i,{get:()=>e[i],enumerable:!(n=He(e,i))||n.enumerable});return r};var Q=(r,e,t)=>(t=r!=null?Ne(Qe(r)):{},Se(e||!r||!r.__esModule?B(t,"default",{value:r,enumerable:!0}):t,r)),Xe=r=>Se(B({},"__esModule",{value:!0}),r);var Tt={};Je(Tt,{AbortError:()=>b,DEFAULT_ConnectionOptions:()=>te,DEFAULT_RetryDelayStrategyOptions:()=>re,DEFAULT_WriteOptions:()=>ne,FLUX_VALUE:()=>E,HttpError:()=>m,IllegalArgumentError:()=>y,InfluxDB:()=>U,LineSplitter:()=>R,Log:()=>h,Point:()=>me,RequestTimedOutError:()=>x,UNKNOWN_COLUMN:()=>J,canRetryHttpCall:()=>Ze,chunksToLines:()=>T,chunksToLinesIterable:()=>$,consoleLogger:()=>Le,convertTimeToNanos:()=>fe,createFluxTableColumn:()=>Ye,createFluxTableMetaData:()=>A,createTextDecoderCombiner:()=>v,currentTime:()=>le,dateToProtocolTimestamp:()=>ue,escape:()=>w,flux:()=>gt,fluxBool:()=>ht,fluxDateTime:()=>ct,fluxDuration:()=>dt,fluxExpression:()=>pe,fluxFloat:()=>ut,fluxInteger:()=>ft,fluxRegExp:()=>mt,fluxString:()=>lt,getRetryDelay:()=>X,isStatusCodeRetriable:()=>ve,linesToRowsIterable:()=>G,linesToTables:()=>z,newFluxTableColumn:()=>O,sanitizeFloat:()=>ce,sanitizeInteger:()=>de,serializeDateTimeAsDate:()=>et,serializeDateTimeAsNumber:()=>tt,serializeDateTimeAsString:()=>rt,setLogger:()=>ot,stringToLines:()=>nt,symbolObservable:()=>K,toFluxValue:()=>N,typeSerializers:()=>C,useProcessHrtime:()=>Fe});module.exports=Xe(Tt);function v(){let r=new TextDecoder("utf-8");return{concat(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n},copy(e,t,n){let i=new Uint8Array(n-t);return i.set(e.subarray(t,n)),i},toUtf8String(e,t,n){return r.decode(e.subarray(t,n))}}}function T(r,e){let t=e!=null?e:v(),n,i=!1,s=!1,a=!1,o;function u(l){let p,c=0;for(n?(p=l.length===0?0:n.length,l=t.concat(n,l)):p=0;p0&&l[p-1]===13?p-1:p;if(i)return;if(a=r.next(t.toUtf8String(l,c,_))===!1,c=p+1,a)break}}else d===34&&(s=!s);p++}if(c{a=!1,u(new Uint8Array(0))});return}f.error(new Error("Unable to pause, useResume is not configured!")),a=!1}o&&(o(),o=void 0)}let f={next(l){if(!i)try{return u(l),!a}catch(p){this.error(p)}return!0},error(l){i||(i=!0,r.error(l))},complete(){i||(n&&r.next(t.toUtf8String(n,0,n.length)),i=!0,r.complete())}};return r.useCancellable&&(f.useCancellable=l=>{r.useCancellable&&r.useCancellable({cancel(){l.cancel(),n=void 0,f.complete()},isCancelled(){return l.isCancelled()}})}),r.useResume&&(f.useResume=l=>{o=l}),f}async function*$(r,e){let t=e!=null?e:v(),n,i=!1;for await(let s of r){let a,o=0;for(n?(a=n.length,s=t.concat(n,s)):a=0;a0&&s[a-1]===13?a-1:a;yield t.toUtf8String(s,o,f),o=a+1}}else u===34&&(i=!i);a++}or,C={boolean:r=>r===""?null:r==="true",unsignedLong:r=>r===""?null:+r,long:r=>r===""?null:+r,double(r){switch(r){case"":return null;case"+Inf":return Number.POSITIVE_INFINITY;case"-Inf":return Number.NEGATIVE_INFINITY;default:return+r}},string:j,base64Binary:j,duration:r=>r===""?null:r,"dateTime:RFC3339":r=>r===""?null:r},M=class{get(e){var n;let t=e[this.index];return(t===""||t===void 0)&&this.defaultValue&&(t=this.defaultValue),((n=C[this.dataType])!=null?n:j)(t)}},J=Object.freeze({label:"",dataType:"",group:!1,defaultValue:"",index:Number.MAX_SAFE_INTEGER,get:()=>{}});function O(){return new M}function Ye(r){var t,n;let e=new M;return e.label=String(r.label),e.dataType=r.dataType,e.group=Boolean(r.group),e.defaultValue=(t=r.defaultValue)!=null?t:"",e.index=(n=r.index)!=null?n:0,e}var Ge=[404,408,425,429,500,502,503,504];function ve(r){return Ge.includes(r)}var y=class extends Error{constructor(e){super(e),this.name="IllegalArgumentError",Object.setPrototypeOf(this,y.prototype)}},m=class extends Error{constructor(t,n,i,s,a,o){super();this.statusCode=t;this.statusMessage=n;this.body=i;this.contentType=a;if(Object.setPrototypeOf(this,m.prototype),o)this.message=o;else if(i){if(a!=null&&a.startsWith("application/json"))try{this.json=JSON.parse(i),this.message=this.json.message,this.code=this.json.code}catch(u){}this.message||(this.message=`${t} ${n} : ${i}`)}else this.message=`${t} ${n}`;this.name="HttpError",this.setRetryAfter(s)}setRetryAfter(t){typeof t=="string"?/^[0-9]+$/.test(t)?this._retryAfter=parseInt(t):this._retryAfter=0:this._retryAfter=0}canRetry(){return ve(this.statusCode)}retryAfter(){return this._retryAfter}},Ke=["ECONNRESET","ENOTFOUND","ESOCKETTIMEDOUT","ETIMEDOUT","ECONNREFUSED","EHOSTUNREACH","EPIPE"];function Ze(r){if(r){if(typeof r.canRetry=="function")return!!r.canRetry();if(r.code&&Ke.includes(r.code))return!0}else return!1;return!1}function X(r,e){if(r){let t;return typeof r.retryAfter=="function"?r.retryAfter():(t=0,e&&e>0?t+Math.round(Math.random()*e):t)}else return 0}var x=class extends Error{constructor(){super(),Object.setPrototypeOf(this,x.prototype),this.name="RequestTimedOutError",this.message="Request timed out"}canRetry(){return!0}retryAfter(){return 0}},b=class extends Error{constructor(){super(),this.name="AbortError",Object.setPrototypeOf(this,b.prototype),this.message="Response aborted"}canRetry(){return!0}retryAfter(){return 0}};function et(){C["dateTime:RFC3339"]=r=>r===""?null:new Date(Date.parse(r))}function tt(){C["dateTime:RFC3339"]=r=>r===""?null:Date.parse(r)}function rt(){C["dateTime:RFC3339"]=r=>r===""?null:r}var Y=class{constructor(e){e.forEach((t,n)=>t.index=n),this.columns=e}column(e,t=!0){for(let n=0;n0&&r.charCodeAt(i-1)===13?i-1:i;e.next(r.substring(n,a)),n=i+1}}else s===34&&(t=!t);i++}ntypeof Symbol=="function"&&Symbol.observable||"@@observable")();var ee=class{constructor(e,t){this.isClosed=!1;try{t({next:n=>{e.next(n)},error:n=>{this.isClosed=!0,e.error(n)},complete:()=>{this.isClosed=!0,e.complete()},useCancellable:n=>{this.cancellable=n}})}catch(n){this.isClosed=!0,e.error(n)}}get closed(){return this.isClosed}unsubscribe(){var e;(e=this.cancellable)==null||e.cancel(),this.isClosed=!0}};function Z(){}function it(r){let{next:e,error:t,complete:n}=r;return{next:e?e.bind(r):Z,error:t?t.bind(r):Z,complete:n?n.bind(r):Z}}var S=class{constructor(e,t){this.executor=e;this.decorator=t}subscribe(e,t,n){let i=it(typeof e!="object"||e===null?{next:e,error:t,complete:n}:e);return new ee(this.decorator(i),this.executor)}[K](){return this}};Symbol.observable;var te={timeout:1e4},re={retryJitter:200,minRetryDelay:5e3,maxRetryDelay:125e3,exponentialBase:5,randomRetry:!0},ne={batchSize:1e3,maxBatchBytes:5e7,flushInterval:6e4,writeFailed:function(){},writeSuccess:function(){},writeRetrySkipped:function(){},maxRetries:5,maxRetryTime:18e4,maxBufferLines:32e3,retryJitter:200,minRetryDelay:5e3,maxRetryDelay:125e3,exponentialBase:2,gzipThreshold:1e3,randomRetry:!0};function ie(r,e){return function(t){let n="",i=0,s=0;for(;s=0&&(n+=t.substring(i,s),n+=e[a],i=s+1),s++}return i==0?t:(i'"'+t(n)+'"'}var w={measurement:ie(`, +\r `,["\\,","\\ ","\\n","\\r","\\t"]),quoted:st('"\\',['\\"',"\\\\"]),tag:ie(`, = +\r `,["\\,","\\ ","\\=","\\n","\\r","\\t"])};var k="000000000",ae=!1;function Fe(r){return ae=r&&process&&typeof process.hrtime=="function"}Fe(!0);var Oe,V,Ae=Date.now(),se=0;function oe(){if(ae){let r=process.hrtime(),e=Date.now();V?(r[0]=r[0]-V[0],r[1]=r[1]-V[1],r[1]<0&&(r[0]-=1,r[1]+=1e9),e=Oe+r[0]*1e3+Math.floor(r[1]/1e6)):(V=r,Oe=e);let t=String(r[1]%1e6);return String(e)+k.substr(0,6-t.length)+t}else{let r=Date.now();r!==Ae?(Ae=r,se=0):se++;let e=String(se);return String(r)+k.substr(0,6-e.length)+e}}function Ee(){if(ae){let r=process.hrtime(),e=String(Math.trunc(r[1]/1e3)%1e3);return String(Date.now())+k.substr(0,3-e.length)+e}else return String(Date.now())+k.substr(0,3)}function De(){return String(Date.now())}function Pe(){return String(Math.floor(Date.now()/1e3))}var le={s:Pe,ms:De,us:Ee,ns:oe,seconds:Pe,millis:De,micros:Ee,nanos:oe},ue={s:r=>`${Math.floor(r.getTime()/1e3)}`,ms:r=>`${r.getTime()}`,us:r=>`${r.getTime()}000`,ns:r=>`${r.getTime()}000000`};function fe(r){return r===void 0?oe():typeof r=="string"?r.length>0?r:void 0:r instanceof Date?`${r.getTime()}000000`:String(typeof r=="number"?Math.floor(r):r)}var Le={error(r,e){console.error("ERROR: "+r,e||"")},warn(r,e){console.warn("WARN: "+r,e||"")}},W=Le,h={error(r,e){W.error(r,e)},warn(r,e){W.warn(r,e)}};function ot(r){let e=W;return W=r,e}var E=Symbol("FLUX_VALUE"),g=class{constructor(e){this.fluxValue=e}toString(){return this.fluxValue}[E](){return this.fluxValue}};function at(r){return typeof r=="object"&&typeof r[E]=="function"}function D(r){if(r==null)return"";r=r.toString();let e,t=0;function n(){e===void 0&&(e=r.substring(0,t))}for(;t="0"&&i<="9"||i=="-")){if(i==="."){n=!0;continue}return`float(v: "${t}")`}return n?t:t+".0"}function ut(r){return new g(ce(r))}function de(r){let e=String(r),t=e.startsWith("-"),n=t?e.substring(1):e;if(n.length===0||n.length>19)throw new Error(`not a flux integer: ${e}`);for(let i of n)if(i<"0"||i>"9")throw new Error(`not a flux integer: ${e}`);if(n.length===19){if(t&&n>"9223372036854775808")throw new Error(`flux integer out of bounds: ${e}`);if(!t&&n>"9223372036854775807")throw new Error(`flux integer out of bounds: ${e}`)}return e}function ft(r){return new g(de(r))}function pt(r){return`time(v: "${D(r)}")`}function ct(r){return new g(pt(r))}function dt(r){return new g(`duration(v: "${D(r)}")`)}function Ie(r){return r instanceof RegExp?r.toString():new RegExp(r).toString()}function mt(r){return new g(Ie(r))}function ht(r){return r==="true"||r==="false"?new g(r):new g((!!r).toString())}function pe(r){return new g(String(r))}function N(r){if(r===void 0)return"";if(r===null)return"null";if(typeof r=="boolean")return r.toString();if(typeof r=="string")return`"${D(r)}"`;if(typeof r=="number")return Number.isSafeInteger(r)?de(r):ce(r);if(typeof r=="object"){if(typeof r[E]=="function")return r[E]();if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return Ie(r);if(Array.isArray(r))return`[${r.map(N).join(",")}]`}else if(typeof r=="bigint")return`${r}.0`;return N(r.toString())}function gt(r,...e){if(r.length==1&&e.length===0)return pe(r[0]);let t=new Array(r.length+e.length),n=0;for(let i=0;i=9223372036854776e3)throw new Error(`invalid integer value for field '${e}': '${t}'!`);return this.fields[e]=`${Math.floor(n)}i`,this}uintField(e,t){if(typeof t=="number"){if(isNaN(t)||t<0||t>Number.MAX_SAFE_INTEGER)throw new Error(`uint value for field '${e}' out of range: ${t}`);this.fields[e]=`${Math.floor(t)}u`}else{let n=String(t);for(let i=0;i57)throw new Error(`uint value has an unsupported character at pos ${i}: ${t}`)}if(n.length>20||n.length===20&&n.localeCompare("18446744073709551615")>0)throw new Error(`uint value for field '${e}' out of range: ${n}`);this.fields[e]=`${n}u`}return this}floatField(e,t){let n;if(typeof t=="number"?n=t:n=parseFloat(t),!isFinite(n))throw new Error(`invalid float value for field '${e}': ${t}`);return this.fields[e]=String(n),this}stringField(e,t){return t!=null&&(typeof t!="string"&&(t=String(t)),this.fields[e]=w.quoted(t)),this}timestamp(e){return this.time=e,this}toLineProtocol(e){if(!this.name)return;let t="";if(Object.keys(this.fields).sort().forEach(a=>{if(a){let o=this.fields[a];t.length>0&&(t+=","),t+=`${w.tag(a)}=${o}`}}),t.length===0)return;let n="",i=e&&e.defaultTags?{...e.defaultTags,...this.tags}:this.tags;Object.keys(i).sort().forEach(a=>{if(a){let o=i[a];o&&(n+=",",n+=`${w.tag(a)}=${w.tag(o)}`)}});let s=this.time;return e&&e.convertTime?s=e.convertTime(s):s=fe(s),`${w.measurement(this.name)}${n} ${t}${s!==void 0?" "+s:""}`}toString(){let e=this.toLineProtocol(void 0);return e||`invalid point: ${JSON.stringify(this,void 0)}`}};var he=class{constructor(e){this.options={...re,...e},this.success()}nextDelay(e,t){let n=X(e);if(n&&n>0)return n+Math.round(Math.random()*this.options.retryJitter);if(t&&t>0){if(this.options.randomRetry){let s=Math.max(this.options.minRetryDelay,1),a=s*this.options.exponentialBase;for(let o=1;o=this.options.maxRetryDelay){a=this.options.maxRetryDelay;break}return s+Math.round(Math.random()*(a-s)+Math.random()*this.options.retryJitter)}let i=Math.max(this.options.minRetryDelay,1);for(let s=1;s=this.options.maxRetryDelay){i=this.options.maxRetryDelay;break}return i+Math.round(Math.random()*this.options.retryJitter)}else this.currentDelay?this.currentDelay=Math.min(Math.max(this.currentDelay*this.options.exponentialBase,1)+Math.round(Math.random()*this.options.retryJitter),this.options.maxRetryDelay):this.currentDelay=this.options.minRetryDelay+Math.round(Math.random()*this.options.retryJitter);return this.currentDelay}success(){this.currentDelay=void 0}};function Ue(r){return new he(r)}function yt(r){let e,t=r,n=r;for(;n.next;)n.next.expires{}){this.maxLines=e;this.retryLines=t;this.onShrink=n;this.size=0;this.closed=!1;this._timeoutHandle=void 0}addLines(e,t,n,i){if(this.closed||!e.length)return;let s=Date.now()+n;if(ithis.maxLines){let f=this.size,l=f*.7;do{let[p,c]=yt(this.first);this.size-=p.lines.length,c?c.next=p.next:(this.first=p.next,this.first&&this.scheduleRetry(this.first.retryTime-Date.now())),p.next=void 0,this.onShrink(p)}while(this.first&&this.size+e.length>l);h.error(`RetryBuffer: ${f-this.size} oldest lines removed to keep buffer size under the limit of ${this.maxLines} lines.`)}let a={lines:e,retryCount:t,retryTime:s,expires:i},o=this.first,u;for(;;){if(!o||o.retryTime>s){a.next=o,u?u.next=a:(this.first=a,this.scheduleRetry(s-Date.now()));break}u=o,o=o.next}this.size+=e.length}removeLines(){if(this.first){let e=this.first;return this.first=this.first.next,e.next=void 0,this.size-=e.lines.length,e}}scheduleRetry(e){this._timeoutHandle&&clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{let t=this.removeLines();t?this.retryLines(t.lines,t.retryCount,t.expires).catch(()=>{}).finally(()=>{this.first&&this.scheduleRetry(this.first.retryTime-Date.now())}):this._timeoutHandle=void 0},Math.max(e,0))}async flush(){let e;for(;e=this.removeLines();)await this.retryLines(e.lines,e.retryCount,e.expires)}close(){return this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this.closed=!0,this.size}};function ge(r){let e=r.length;for(let t=0;t=128&&n<=2047?e++:n>=2048&&n<=65535?n>=55296&&n<=57343?e++:e+=2:e+=3)}return e}var ye=class{constructor(e,t,n,i){this.maxChunkRecords=e;this.maxBatchBytes=t;this.flushFn=n;this.scheduleSend=i;this.length=0;this.bytes=-1;this.lines=new Array(e)}add(e){let t=ge(e);this.length===0?this.scheduleSend():this.bytes+t+1>=this.maxBatchBytes&&this.flush().catch(n=>{}),this.lines[this.length]=e,this.length++,this.bytes+=t+1,(this.length>=this.maxChunkRecords||this.bytes>=this.maxBatchBytes)&&this.flush().catch(n=>{})}flush(){let e=this.reset();return e.length>0?this.flushFn(e):Promise.resolve()}reset(){let e=this.lines.slice(0,this.length);return this.length=0,this.bytes=-1,e}},F=class{constructor(e,t,n,i,s){this.transport=e;this.closed=!1;this._timeoutHandle=void 0;this.path=`/api/v2/write?org=${encodeURIComponent(t)}&bucket=${encodeURIComponent(n)}&precision=${i}`,s!=null&&s.consistency&&(this.path+=`&consistency=${encodeURIComponent(s.consistency)}`),this.writeOptions={...ne,...s},this.currentTime=le[i],this.dateToProtocolTimestamp=ue[i],this.writeOptions.defaultTags&&this.useDefaultTags(this.writeOptions.defaultTags),this.sendOptions={method:"POST",headers:{"content-type":"text/plain; charset=utf-8",...s==null?void 0:s.headers},gzipThreshold:this.writeOptions.gzipThreshold};let a=()=>{this.writeOptions.flushInterval>0&&(this._clearFlushTimeout(),this.closed||(this._timeoutHandle=setTimeout(()=>this.sendBatch(this.writeBuffer.reset(),this.writeOptions.maxRetries).catch(o=>{}),this.writeOptions.flushInterval)))};this.writeBuffer=new ye(this.writeOptions.batchSize,this.writeOptions.maxBatchBytes,o=>(this._clearFlushTimeout(),this.sendBatch(o,this.writeOptions.maxRetries)),a),this.sendBatch=this.sendBatch.bind(this),this.retryStrategy=Ue(this.writeOptions),this.retryBuffer=new P(this.writeOptions.maxBufferLines,this.sendBatch,this.writeOptions.writeRetrySkipped)}sendBatch(e,t,n=Date.now()+this.writeOptions.maxRetryTime){let i=this,s=i.writeOptions.maxRetries+1-t;if(!this.closed&&e.length>0){if(n<=Date.now()){let a=new Error("Max retry time exceeded."),o=i.writeOptions.writeFailed.call(i,a,e,s,n);return o||(h.error(`Write to InfluxDB failed (attempt: ${s}).`,a),Promise.reject(a))}return new Promise((a,o)=>{let u,f={responseStarted(l,p){u=p},error(l){let p=i.writeOptions.writeFailed.call(i,l,e,s,n);if(p){p.then(a,o);return}if(l instanceof m&&l.json&&typeof l.json.error=="string"&&l.json.error.includes("hinted handoff queue not empty")){h.warn("Write to InfluxDB returns: "+l.json.error),u=204,f.complete();return}if(!i.closed&&t>0&&(!(l instanceof m)||l.statusCode>=429)){h.warn(`Write to InfluxDB failed (attempt: ${s}).`,l),i.retryBuffer.addLines(e,t-1,i.retryStrategy.nextDelay(l,s),n),o(l);return}h.error("Write to InfluxDB failed.",l),o(l)},complete(){if(u==204||u==null)i.writeOptions.writeSuccess.call(i,e),i.retryStrategy.success(),a();else{let l=`204 HTTP response status code expected, but ${u} returned`,p=new m(u,l,void 0,"0");p.message=l,f.error(p)}}};this.transport.send(this.path,e.join(` +`),this.sendOptions,f)})}else return Promise.resolve()}_clearFlushTimeout(){this._timeoutHandle!==void 0&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0)}writeRecord(e){if(this.closed)throw new Error("writeApi: already closed!");this.writeBuffer.add(e)}writeRecords(e){if(this.closed)throw new Error("writeApi: already closed!");for(let t=0;t{let t=this.retryBuffer.close();t&&h.error(`Retry buffer closed with ${t} items that were not written to InfluxDB!`,null),this.closed=!0})}dispose(){return this._clearFlushTimeout(),this.closed=!0,this.retryBuffer.close()+this.writeBuffer.length}useDefaultTags(e){return this.defaultTags=e,this}convertTime(e){return e===void 0?this.currentTime():typeof e=="string"?e.length>0?e:void 0:e instanceof Date?this.dateToProtocolTimestamp(e):String(typeof e=="number"?Math.floor(e):e)}};var Re=require("url"),$e=Q(require("http")),Me=Q(require("https")),H=require("buffer");var be=require("buffer"),bt={concat(r,e){return be.Buffer.concat([r,e])},toUtf8String(r,e,t){return r.toString("utf-8",e,t)},copy(r,e,t){let n=be.Buffer.allocUnsafe(t-e);return r.copy(n,0,e,t),n}},_e=bt;var L=Q(require("zlib"));function xe(r={}){let e=0,t={next:n=>{if(e===0&&r.next&&n!==null&&n!==void 0)return r.next(n)},error:n=>{e===0&&(e=1,r.error&&r.error(n))},complete:()=>{e===0&&(e=2,r.complete&&r.complete())},responseStarted:(n,i)=>{r.responseStarted&&r.responseStarted(n,i)}};return r.useCancellable&&(t.useCancellable=r.useCancellable.bind(r)),r.useResume&&(t.useResume=r.useResume.bind(r)),t}var Be="1.33.1";var ze=require("stream"),xt={flush:L.default.constants.Z_SYNC_FLUSH,finishFlush:L.default.constants.Z_SYNC_FLUSH},Rt=H.Buffer.allocUnsafe(0),we=class{constructor(){this.cancelled=!1}cancel(){this.cancelled=!0,this.resume&&(this.resume(),this.resume=void 0)}isCancelled(){return this.cancelled}},Te=class{constructor(e){this.chunkCombiner=_e;var u,f,l,p,c,d,_;let{url:t,proxyUrl:n,token:i,transportOptions:s,...a}=e,o=(0,Re.parse)(n||t);if(this.token=i,this.defaultOptions={...te,...a,...s,port:o.port,protocol:o.protocol,hostname:o.hostname},this.contextPath=n?t:(u=o.path)!=null?u:"",this.contextPath.endsWith("/")&&(this.contextPath=this.contextPath.substring(0,this.contextPath.length-1)),Object.keys(this.defaultOptions).forEach(Ce=>this.defaultOptions[Ce]===void 0&&delete this.defaultOptions[Ce]),this.contextPath.endsWith("/api/v2")&&(h.warn(`Please remove '/api/v2' context path from InfluxDB base url, using ${o.protocol}//${o.hostname}:${o.port} !`),this.contextPath=""),o.protocol==="http:")this.requestApi=(p=(l=(f=this.defaultOptions["follow-redirects"])==null?void 0:f.http)==null?void 0:l.request)!=null?p:$e.request;else if(o.protocol==="https:")this.requestApi=(_=(d=(c=this.defaultOptions["follow-redirects"])==null?void 0:c.https)==null?void 0:d.request)!=null?_:Me.request;else throw new Error(`Unsupported protocol "${o.protocol} in URL: "${e.url}"`);this.headers={"User-Agent":`influxdb-client-js/${Be}`,...e.headers},n&&(this.headers.Host=(0,Re.parse)(t).host)}send(e,t,n,i){let s=new we;i&&i.useCancellable&&i.useCancellable(s),this.createRequestMessage(e,t,n,a=>{this._request(a,s,i)},a=>(i==null?void 0:i.error)&&i.error(a))}request(e,t,n,i){t?typeof t!="string"&&(t=JSON.stringify(t)):t="";let s=Rt,a,o;return new Promise((u,f)=>{this.send(e,t,n,{responseStarted(l,p){i&&i(l,p),a=String(l["content-type"]),o=p},next:l=>{s=H.Buffer.concat([s,l])},complete:()=>{var p,c;let l=(c=(p=n.headers)==null?void 0:p.accept)!=null?c:a;try{o===204&&u(void 0),l.includes("json")?s.length?u(JSON.parse(s.toString("utf8"))):u(void 0):l.includes("text")||l.startsWith("application/csv")?u(s.toString("utf8")):u(s)}catch(d){f(d)}},error:l=>{f(l)}})})}async*iterate(e,t,n){var l;let i,s;function a(p){i=p,s(p)}let o=await new Promise((p,c)=>{s=c,this.createRequestMessage(e,t,n,p,a)});(l=o.signal)!=null&&l.addEventListener&&o.signal.addEventListener("abort",()=>{a(new b)});let u=await new Promise((p,c)=>{s=c;let d=this.requestApi(o,p);d.on("timeout",()=>a(new x)),d.on("error",a),d.write(o.body),d.end()}),f=await new Promise((p,c)=>{s=c,this._prepareResponse(u,p,a)});for await(let p of f){if(i)throw i;yield p}}createRequestMessage(e,t,n,i,s){let a=H.Buffer.from(t,"utf-8"),o={"content-type":"application/json; charset=utf-8",...this.headers};this.token&&(o.authorization="Token "+this.token);let u={...this.defaultOptions,path:this.contextPath+e,method:n.method,headers:{...o,...n.headers}};if(n.signal&&(u.signal=n.signal),n.gzipThreshold!==void 0&&n.gzipThreshold{if(f)return s(f);u.headers["content-encoding"]="gzip",u.body=l,i(u)});return}u.body=a,u.headers["content-length"]=u.body.length,i(u)}_prepareResponse(e,t,n){var o;e.on("aborted",()=>{n(new b)}),e.on("error",n);let i=(o=e.statusCode)!=null?o:600,s=e.headers["content-encoding"],a;if(s==="gzip"?(a=L.default.createGunzip(xt),a=(0,ze.pipeline)(e,a,u=>u&&n(u))):a=e,i>=300){let u="",f=String(e.headers["content-type"]).startsWith("application/json");a.on("data",l=>{u+=l.toString(),!f&&u.length>1e3&&(u=u.slice(0,1e3),e.resume())}),a.on("end",()=>{u===""&&!!e.headers["x-influxdb-error"]&&(u=e.headers["x-influxdb-error"].toString()),n(new m(i,e.statusMessage,u,e.headers["retry-after"],e.headers["content-type"]))})}else t(a)}_request(e,t,n){var a;let i=xe(n);if(t.isCancelled()){i.complete();return}(a=e.signal)!=null&&a.addEventListener&&e.signal.addEventListener("abort",()=>{i.error(new b)});let s=this.requestApi(e,o=>{if(t.isCancelled()){o.resume(),i.complete();return}i.responseStarted(o.headers,o.statusCode),this._prepareResponse(o,u=>{u.on("data",f=>{if(t.isCancelled())o.resume();else if(i.next(f)===!1){if(!i.useResume){i.error(new Error("Unable to pause, useResume is not configured!")),o.resume();return}o.pause();let l=()=>{o.resume()};t.resume=l,i.useResume(l)}}),u.on("end",i.complete)},i.error)});typeof s.setTimeout=="function"&&e.timeout&&s.setTimeout(e.timeout),s.on("timeout",()=>{i.error(new x)}),s.on("error",o=>{i.error(o)}),e.body&&s.write(e.body),s.end()}},Ve=Te;var ke={header:!0,delimiter:",",quoteChar:'"',commentPrefix:"#",annotations:["datatype","group","default"]},I=class{constructor(e,t,n){this.transport=e;this.createCSVResponse=t;this.options=typeof n=="string"?{org:n}:n}with(e){return new I(this.transport,this.createCSVResponse,{...this.options,...e})}response(e){let{org:t,type:n,gzip:i,headers:s}=this.options,a=`/api/v2/query?org=${encodeURIComponent(t)}`,o=JSON.stringify(this.decorateRequest({query:e.toString(),dialect:ke,type:n})),u={method:"POST",headers:{"content-type":"application/json; encoding=utf-8","accept-encoding":i?"gzip":"identity",...s}};return this.createCSVResponse(f=>this.transport.send(a,o,u,f),()=>this.transport.iterate(a,o,u))}iterateLines(e){return this.response(e).iterateLines()}iterateRows(e){return this.response(e).iterateRows()}lines(e){return this.response(e).lines()}rows(e){return this.response(e).rows()}queryLines(e,t){return this.response(e).consumeLines(t)}queryRows(e,t){return this.response(e).consumeRows(t)}collectRows(e,t){return this.response(e).collectRows(t)}collectLines(e){return this.response(e).collectLines()}queryRaw(e){let{org:t,type:n,gzip:i,headers:s}=this.options;return this.transport.request(`/api/v2/query?org=${encodeURIComponent(t)}`,JSON.stringify(this.decorateRequest({query:e.toString(),dialect:ke,type:n})),{method:"POST",headers:{accept:"text/csv","accept-encoding":i?"gzip":"identity","content-type":"application/json; encoding=utf-8",...s}})}decorateRequest(e){var t;return typeof this.options.now=="function"&&(e.now=this.options.now()),e.type=(t=this.options.type)!=null?t:"flux",e}},We=I;function wt(r,e){return e.toObject(r)}var q=class{constructor(e,t,n){this.executor=e;this.iterableResultExecutor=t;this.chunkCombiner=n}iterateLines(){return $(this.iterableResultExecutor())}iterateRows(){return G($(this.iterableResultExecutor()))}lines(){return new S(this.executor,e=>T(e,this.chunkCombiner))}rows(){return new S(this.executor,e=>T(z({next(t,n){e.next({values:t,tableMeta:n})},error(t){e.error(t)},complete(){e.complete()}}),this.chunkCombiner))}consumeLines(e){this.executor(T(e,this.chunkCombiner))}consumeRows(e){this.executor(T(z(e),this.chunkCombiner))}collectRows(e=wt){let t=[];return new Promise((n,i)=>{this.consumeRows({next(s,a){let o=e.call(this,s,a);o!==void 0&&t.push(o)},error(s){i(s)},complete(){n(t)}})})}collectLines(){let e=[];return new Promise((t,n)=>{this.consumeLines({next(i){e.push(i)},error(i){n(i)},complete(){t(e)}})})}};var U=class{constructor(e){var n;if(typeof e=="string")this._options={url:e};else if(e!==null&&typeof e=="object")this._options=e;else throw new y("No url or configuration specified!");let t=this._options.url;if(typeof t!="string")throw new y("No url specified!");t.endsWith("/")&&(this._options.url=t.substring(0,t.length-1)),this.transport=(n=this._options.transport)!=null?n:new Ve(this._options),this.processCSVResponse=(i,s)=>new q(i,s,this.transport.chunkCombiner)}getWriteApi(e,t,n="ns",i){return new F(this.transport,e,t,n,i!=null?i:this._options.writeOptions)}getQueryApi(e){return new We(this.transport,this.processCSVResponse,e)}};0&&(module.exports={AbortError,DEFAULT_ConnectionOptions,DEFAULT_RetryDelayStrategyOptions,DEFAULT_WriteOptions,FLUX_VALUE,HttpError,IllegalArgumentError,InfluxDB,LineSplitter,Log,Point,RequestTimedOutError,UNKNOWN_COLUMN,canRetryHttpCall,chunksToLines,chunksToLinesIterable,consoleLogger,convertTimeToNanos,createFluxTableColumn,createFluxTableMetaData,createTextDecoderCombiner,currentTime,dateToProtocolTimestamp,escape,flux,fluxBool,fluxDateTime,fluxDuration,fluxExpression,fluxFloat,fluxInteger,fluxRegExp,fluxString,getRetryDelay,isStatusCodeRetriable,linesToRowsIterable,linesToTables,newFluxTableColumn,sanitizeFloat,sanitizeInteger,serializeDateTimeAsDate,serializeDateTimeAsNumber,serializeDateTimeAsString,setLogger,stringToLines,symbolObservable,toFluxValue,typeSerializers,useProcessHrtime}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/index.js.gz b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.js.gz new file mode 100644 index 0000000000000000000000000000000000000000..c94408d659f3b4e6ad605c0de11a8902707620cf GIT binary patch literal 10858 zcmV-wDwWkAiwFP!000021GRm7U)#pg@ZZn*6hO60xH&d$zlXLp?<=bc<+(O5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unkCombiner\n): CommunicationObserver {\n const chunks = chunkCombiner ?? createTextDecoderCombiner()\n let previous: Uint8Array | undefined\n let finished = false\n let quoted = false\n let paused = false\n let resumeChunks: (() => void) | undefined\n\n function bufferReceived(chunk: Uint8Array): void {\n let index: number\n let start = 0\n if (previous) {\n // inspect the whole remaining data upon empty chunk\n // empty chunk signalizes to restart of receiving\n index = chunk.length === 0 ? 0 : (previous as Uint8Array).length\n chunk = chunks.concat(previous, chunk)\n } else {\n index = 0\n }\n while (index < chunk.length) {\n const c = chunk[index]\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n // do not emmit more lines if the processing is already finished\n if (finished) {\n return\n }\n paused = target.next(chunks.toUtf8String(chunk, start, end)) === false\n start = index + 1\n if (paused) {\n break\n }\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < chunk.length) {\n previous = chunks.copy(chunk, start, chunk.length)\n } else {\n previous = undefined\n }\n if (paused) {\n if (target.useResume) {\n target.useResume(() => {\n paused = false\n bufferReceived(new Uint8Array(0))\n })\n return\n }\n retVal.error(new Error('Unable to pause, useResume is not configured!'))\n paused = false // consume remaining data\n }\n if (resumeChunks) {\n resumeChunks()\n resumeChunks = undefined\n }\n }\n\n const retVal: CommunicationObserver = {\n next(chunk: Uint8Array): boolean {\n if (!finished) {\n try {\n bufferReceived(chunk)\n return !paused\n } catch (e) {\n this.error(e as Error)\n }\n }\n return true\n },\n error(error: Error): void {\n if (!finished) {\n finished = true\n target.error(error)\n }\n },\n complete(): void {\n if (!finished) {\n if (previous) {\n target.next(chunks.toUtf8String(previous, 0, previous.length))\n }\n finished = true\n target.complete()\n }\n },\n }\n if (target.useCancellable) {\n retVal.useCancellable = (cancellable: Cancellable) => {\n target.useCancellable &&\n target.useCancellable({\n cancel(): void {\n cancellable.cancel()\n previous = undefined // do not emit more lines\n retVal.complete()\n },\n isCancelled(): boolean {\n return cancellable.isCancelled()\n },\n })\n }\n }\n if (target.useResume) {\n retVal.useResume = (x: () => void) => {\n resumeChunks = x\n }\n }\n\n return retVal\n}\n","import {ChunkCombiner, createTextDecoderCombiner} from './chunkCombiner'\n\n/**\n * ChunksToLinesIterable is a transformation that accepts\n * an iterable of Uint8Array instances and returns iterable of lines.\n * @param source - iterable of transport buffers\n * @param chunkCombiner - chunk combiner\n * @returns iterable of lines\n */\nexport async function* chunksToLinesIterable(\n source: AsyncIterable,\n chunkCombiner?: ChunkCombiner\n): AsyncIterableIterator {\n const chunks = chunkCombiner ?? createTextDecoderCombiner()\n let previous: Uint8Array | undefined\n let quoted = false\n\n for await (let chunk of source) {\n let index: number\n let start = 0\n if (previous) {\n index = previous.length\n chunk = chunks.concat(previous, chunk)\n } else {\n index = 0\n }\n while (index < chunk.length) {\n const c = chunk[index]\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n yield chunks.toUtf8String(chunk, start, end)\n start = index + 1\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < chunk.length) {\n previous = chunks.copy(chunk, start, chunk.length)\n } else {\n previous = undefined\n }\n }\n if (previous) {\n yield chunks.toUtf8String(previous, 0, previous.length)\n }\n}\n","/**\n * Optimized tokenizer of a single CSV line.\n */\nexport class LineSplitter {\n /** returned value when reused */\n reusedValues: string[]\n /** last length of elements in */\n lastSplitLength: number\n private _reuse = false\n\n /**\n * Reuse returned array between consecutive calls.\n */\n get reuse(): boolean {\n return this._reuse\n }\n set reuse(val: boolean) {\n if (val && !this.reusedValues) {\n this.reusedValues = new Array(10)\n }\n this._reuse = val\n }\n\n /**\n * Sets the reuse flag and returns this.\n */\n withReuse(): LineSplitter {\n this.reuse = true\n return this\n }\n\n /**\n * Splits the supplied line to elements that are separated by\n * comma with values possibly escaped within double quotes (\"value\")\n * @param line - line\n * @returns array of splitted parts\n */\n splitLine(line: string | undefined | null): string[] {\n if (line === null || line === undefined) {\n this.lastSplitLength = 0\n return []\n }\n let quoteCount = 0\n let startIndex = 0\n const values = this._reuse ? this.reusedValues : []\n let count = 0\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (c === ',') {\n if (quoteCount % 2 === 0) {\n const val = this.getValue(line, startIndex, i, quoteCount)\n if (this._reuse) {\n values[count++] = val\n } else {\n values.push(val)\n }\n startIndex = i + 1\n quoteCount = 0\n }\n } else if (c === '\"') {\n quoteCount++\n }\n }\n const val = this.getValue(line, startIndex, line.length, quoteCount)\n if (this._reuse) {\n values[count] = val\n this.lastSplitLength = count + 1\n } else {\n values.push(val)\n this.lastSplitLength = values.length\n }\n\n return values\n }\n\n private getValue(\n line: string,\n start: number,\n end: number,\n quoteCount: number\n ): string {\n if (start === line.length) {\n return ''\n } else if (quoteCount === 0) {\n return line.substring(start, end)\n } else if (quoteCount === 2) {\n return line.substring(start + 1, end - 1)\n } else {\n // quoteCount >= 4\n return line.substring(start + 1, end - 1).replace(/\"\"/gi, '\"')\n }\n }\n}\n","/**\n * Type of query result column, see {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport type ColumnType =\n | 'boolean'\n | 'unsignedLong'\n | 'long'\n | 'double'\n | 'string'\n | 'base64Binary'\n | 'dateTime:RFC3339'\n | 'duration'\n | string\n\n/**\n * FluxTableColumn describes {@link http://bit.ly/flux-spec#table | flux table} column.\n */\nexport interface FluxTableColumn {\n /**\n * Label (e.g., \"_start\", \"_stop\", \"_time\").\n */\n label: string\n\n /**\n * The data type of column (e.g., \"string\", \"long\", \"dateTime:RFC3339\").\n */\n dataType: ColumnType\n\n /**\n * Boolean flag indicating if the column is a part of the table's group key.\n */\n group: boolean\n\n /**\n * Default value to be used for rows whose string value is an empty string.\n */\n defaultValue: string\n\n /**\n * Index of this column in a row array.\n */\n index: number\n\n /**\n * Get returns a JavaScript object of this column in the supplied result row, using default deserializers.\n * @param row - a data row\n * @returns column value\n */\n get: (row: string[]) => any\n}\n\nconst identity = (x: string): any => x\n\n/**\n * A dictionary of serializers of particular types returned by a flux query.\n * See {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport const typeSerializers: Record any> = {\n boolean: (x: string): any => (x === '' ? null : x === 'true'),\n unsignedLong: (x: string): any => (x === '' ? null : +x),\n long: (x: string): any => (x === '' ? null : +x),\n double(x: string): any {\n switch (x) {\n case '':\n return null\n case '+Inf':\n return Number.POSITIVE_INFINITY\n case '-Inf':\n return Number.NEGATIVE_INFINITY\n default:\n return +x\n }\n },\n string: identity,\n base64Binary: identity,\n duration: (x: string): any => (x === '' ? null : x),\n 'dateTime:RFC3339': (x: string): any => (x === '' ? null : x),\n}\n\n/**\n * FluxTableColumn implementation.\n */\nclass FluxTableColumnImpl implements FluxTableColumn {\n label: string\n dataType: ColumnType\n group: boolean\n defaultValue: string\n index: number\n public get(row: string[]): any {\n let val = row[this.index]\n if ((val === '' || val === undefined) && this.defaultValue) {\n val = this.defaultValue\n }\n return (typeSerializers[this.dataType] ?? identity)(val)\n }\n}\nexport const UNKNOWN_COLUMN: FluxTableColumn = Object.freeze({\n label: '',\n dataType: '',\n group: false,\n defaultValue: '',\n index: Number.MAX_SAFE_INTEGER,\n get: () => undefined,\n})\n\n/**\n * Creates a new flux table column.\n * @returns column instance\n */\nexport function newFluxTableColumn(): FluxTableColumn {\n return new FluxTableColumnImpl()\n}\n\n/**\n * Creates a flux table column from a partial FluxTableColumn.\n * @param object - source object\n * @returns column instance\n */\nexport function createFluxTableColumn(\n object: Partial\n): FluxTableColumn {\n const retVal = new FluxTableColumnImpl()\n retVal.label = String(object.label)\n retVal.dataType = object.dataType as ColumnType\n retVal.group = Boolean(object.group)\n retVal.defaultValue = object.defaultValue ?? ''\n retVal.index = object.index ?? 0\n return retVal\n}\n","/**\n * Strategy for calculating retry delays.\n */\nexport interface RetryDelayStrategy {\n /**\n * Returns delay for a next retry\n * @param error - reason for retrying\n * @param failedAttempts - a count of already failed attempts, 1 being the first\n * @returns milliseconds to wait before retrying\n */\n nextDelay(error?: Error, failedAttempts?: number): number\n /** Implementation should reset its state, this is mandatory to call upon success. */\n success(): void\n}\n\n/**\n * Interface for errors to inform that an associated operation can be retried.\n */\nexport interface RetriableDecision {\n /**\n * Informs whether this can be retried.\n */\n canRetry(): boolean\n /**\n * Get the delay in milliseconds to retry the action.\n * @returns 0 to let the implementation decide, miliseconds delay otherwise\n */\n retryAfter(): number\n}\n\nconst retriableStatusCodes = [404, 408, 425, 429, 500, 502, 503, 504]\n/** isStatusCodeRetriable checks whether the supplied HTTP status code is retriable. */\nexport function isStatusCodeRetriable(statusCode: number): boolean {\n return retriableStatusCodes.includes(statusCode)\n}\n\n/** IllegalArgumentError is thrown when illegal argument is supplied. */\nexport class IllegalArgumentError extends Error {\n /* istanbul ignore next */\n constructor(message: string) {\n super(message)\n this.name = 'IllegalArgumentError'\n Object.setPrototypeOf(this, IllegalArgumentError.prototype)\n }\n}\n\n/**\n * A general HTTP error.\n */\nexport class HttpError extends Error implements RetriableDecision {\n private _retryAfter: number\n /** application error code, when available */\n public code: string | undefined\n /** json error response */\n public json: any\n\n /* istanbul ignore next because of super() not being covered*/\n constructor(\n readonly statusCode: number,\n readonly statusMessage: string | undefined,\n readonly body?: string,\n retryAfter?: string | undefined | null,\n readonly contentType?: string | undefined | null,\n message?: string\n ) {\n super()\n Object.setPrototypeOf(this, HttpError.prototype)\n if (message) {\n this.message = message\n } else if (body) {\n if (contentType?.startsWith('application/json')) {\n try {\n this.json = JSON.parse(body)\n this.message = this.json.message\n this.code = this.json.code\n } catch (e) {\n // silently ignore, body string is still available\n }\n }\n if (!this.message) {\n this.message = `${statusCode} ${statusMessage} : ${body}`\n }\n } else {\n this.message = `${statusCode} ${statusMessage}`\n }\n this.name = 'HttpError'\n this.setRetryAfter(retryAfter)\n }\n\n private setRetryAfter(retryAfter?: string | undefined | null): void {\n if (typeof retryAfter === 'string') {\n // try to parse the supplied number as milliseconds\n if (/^[0-9]+$/.test(retryAfter)) {\n this._retryAfter = parseInt(retryAfter)\n } else {\n this._retryAfter = 0\n }\n } else {\n this._retryAfter = 0\n }\n }\n\n canRetry(): boolean {\n return isStatusCodeRetriable(this.statusCode)\n }\n retryAfter(): number {\n return this._retryAfter\n }\n}\n\n//see https://nodejs.org/api/errors.html\nconst RETRY_CODES = [\n 'ECONNRESET',\n 'ENOTFOUND',\n 'ESOCKETTIMEDOUT',\n 'ETIMEDOUT',\n 'ECONNREFUSED',\n 'EHOSTUNREACH',\n 'EPIPE',\n]\n\n/**\n * Tests the error in order to know if an HTTP call can be retried.\n * @param error - error to test\n * @returns true for a retriable error\n */\nexport function canRetryHttpCall(error: any): boolean {\n if (!error) {\n return false\n } else if (typeof (error as any).canRetry === 'function') {\n return !!((error as any).canRetry as () => boolean)()\n } else if ((error as any).code && RETRY_CODES.includes((error as any).code)) {\n return true\n }\n return false\n}\n\n/**\n * Gets retry delay from the supplied error, possibly using random number up to retryJitter.\n */\nexport function getRetryDelay(error?: Error, retryJitter?: number): number {\n if (!error) {\n return 0\n } else {\n let retVal\n if (typeof (error as any).retryAfter === 'function') {\n return ((error as any).retryAfter as () => number)()\n } else {\n retVal = 0\n }\n if (retryJitter && retryJitter > 0) {\n return retVal + Math.round(Math.random() * retryJitter)\n } else {\n return retVal\n }\n }\n}\n\n/** RequestTimedOutError indicates request timeout in the communication with the server */\nexport class RequestTimedOutError extends Error implements RetriableDecision {\n /* istanbul ignore next because of super() not being covered */\n constructor() {\n super()\n Object.setPrototypeOf(this, RequestTimedOutError.prototype)\n this.name = 'RequestTimedOutError'\n this.message = 'Request timed out'\n }\n canRetry(): boolean {\n return true\n }\n retryAfter(): number {\n return 0\n }\n}\n\n/** AbortError indicates that the communication with the server was aborted */\nexport class AbortError extends Error implements RetriableDecision {\n /* istanbul ignore next because of super() not being covered */\n constructor() {\n super()\n this.name = 'AbortError'\n Object.setPrototypeOf(this, AbortError.prototype)\n this.message = 'Response aborted'\n }\n canRetry(): boolean {\n return true\n }\n retryAfter(): number {\n return 0\n }\n}\n","import {\n FluxTableColumn,\n UNKNOWN_COLUMN,\n typeSerializers,\n} from './FluxTableColumn'\nimport {IllegalArgumentError} from '../errors'\n\n/**\n * serializeDateTimeAsDate changes type serializers to return JavaScript Date instances\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsDate(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : new Date(Date.parse(x))\n}\n/**\n * serializeDateTimeAsNumber changes type serializers to return milliseconds since epoch\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsNumber(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : Date.parse(x)\n}\n/**\n * serializeDateTimeAsString changes type serializers to return string values\n * for `dateTime:RFC3339` query result data type. Empty value is converted to null.\n */\nexport function serializeDateTimeAsString(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : x\n}\n\n/**\n * Represents metadata of a {@link http://bit.ly/flux-spec#table | flux table}.\n */\nexport interface FluxTableMetaData {\n /**\n * Table columns.\n */\n columns: Array\n\n /**\n * Gets columns by name\n * @param label - column label\n * @param errorOnMissingColumn - throw error on missing column (by default), return UNKNOWN_COLUMN when false\n * @returns table column\n * @throws IllegalArgumentError if column is not found\n **/\n column(label: string, errorOnMissingColumn?: boolean): FluxTableColumn\n\n /**\n * Creates an object out of the supplied row with the help of column descriptors.\n * @param row - a row with data for each column\n */\n toObject(row: string[]): {[key: string]: any}\n\n /**\n * Gets column values out of the supplied row.\n * @param row - a row with data for each column\n * @param column - column name\n * @returns column value, undefined for unknown column\n */\n get(row: string[], column: string): any\n}\n\n/**\n * FluxTableMetaData Implementation.\n */\nclass FluxTableMetaDataImpl implements FluxTableMetaData {\n columns: Array\n constructor(columns: FluxTableColumn[]) {\n columns.forEach((col, i) => (col.index = i))\n this.columns = columns\n }\n column(label: string, errorOnMissingColumn = true): FluxTableColumn {\n for (let i = 0; i < this.columns.length; i++) {\n const col = this.columns[i]\n if (col.label === label) return col\n }\n if (errorOnMissingColumn) {\n throw new IllegalArgumentError(`Column ${label} not found!`)\n }\n return UNKNOWN_COLUMN\n }\n toObject(row: string[]): {[key: string]: any} {\n const acc: any = {}\n for (let i = 0; i < this.columns.length && i < row.length; i++) {\n const column = this.columns[i]\n acc[column.label] = column.get(row)\n }\n return acc\n }\n get(row: string[], column: string): any {\n return this.column(column, false).get(row)\n }\n}\n\n/**\n * Created FluxTableMetaData from the columns supplied.\n * @param columns - columns\n * @returns - instance\n */\nexport function createFluxTableMetaData(\n columns: FluxTableColumn[]\n): FluxTableMetaData {\n return new FluxTableMetaDataImpl(columns)\n}\n\n/** Wraps values and associated metadata of a query result row */\nexport interface Row {\n values: string[]\n tableMeta: FluxTableMetaData\n}\n","import {CommunicationObserver} from './CommunicationObserver'\nimport {LineSplitter} from './LineSplitter'\nimport {FluxResultObserver} from './FluxResultObserver'\nimport {\n FluxTableColumn,\n ColumnType,\n newFluxTableColumn,\n} from './FluxTableColumn'\nimport {FluxTableMetaData, createFluxTableMetaData} from './FluxTableMetaData'\n\n/**\n * LinesToTables creates a transformation that accepts (flux) annotated CSV lines\n * and emits rows together with table metadata.\n */\nexport function linesToTables(\n consumer: FluxResultObserver\n): CommunicationObserver {\n const splitter = new LineSplitter().withReuse()\n let columns: FluxTableColumn[] | undefined\n let expectMeta = true\n let firstColumnIndex = 0\n let lastMeta: FluxTableMetaData\n const retVal: CommunicationObserver = {\n error(error: Error): void {\n consumer.error(error)\n },\n next(line: string): void | boolean {\n if (line === '') {\n expectMeta = true\n columns = undefined\n } else {\n const values = splitter.splitLine(line)\n const size = splitter.lastSplitLength\n if (expectMeta) {\n // create columns\n if (!columns) {\n columns = new Array(size)\n for (let i = 0; i < size; i++) {\n columns[i] = newFluxTableColumn()\n }\n }\n if (!values[0].startsWith('#')) {\n // fill in column names\n if (values[0] === '') {\n firstColumnIndex = 1\n columns = columns.slice(1)\n } else {\n firstColumnIndex = 0\n }\n for (let i = firstColumnIndex; i < size; i++) {\n columns[i - firstColumnIndex].label = values[i]\n }\n lastMeta = createFluxTableMetaData(columns)\n expectMeta = false\n } else if (values[0] === '#datatype') {\n for (let i = 1; i < size; i++) {\n columns[i].dataType = values[i] as ColumnType\n }\n } else if (values[0] === '#default') {\n for (let i = 1; i < size; i++) {\n columns[i].defaultValue = values[i]\n }\n } else if (values[0] === '#group') {\n for (let i = 1; i < size; i++) {\n columns[i].group = values[i][0] === 't'\n }\n }\n } else {\n return consumer.next(values.slice(firstColumnIndex, size), lastMeta)\n }\n }\n return true\n },\n complete(): void {\n consumer.complete()\n },\n }\n if (consumer.useCancellable) {\n retVal.useCancellable = consumer.useCancellable.bind(consumer)\n }\n if (consumer.useResume) {\n retVal.useResume = consumer.useResume.bind(consumer)\n }\n return retVal\n}\n","import {LineSplitter} from './LineSplitter'\nimport {\n FluxTableColumn,\n ColumnType,\n newFluxTableColumn,\n} from './FluxTableColumn'\nimport {\n FluxTableMetaData,\n createFluxTableMetaData,\n Row,\n} from './FluxTableMetaData'\n\n/**\n * LinesToRowsIterable is a transformation that accepts\n * an iterable of flux annotated CSV lines and returns\n * an iterable of rows (row values and table metadata).\n */\nexport async function* linesToRowsIterable(\n source: AsyncIterable\n): AsyncIterableIterator {\n const splitter = new LineSplitter().withReuse()\n let columns: FluxTableColumn[] | undefined\n let expectMeta = true\n let firstColumnIndex = 0\n let lastMeta: FluxTableMetaData | undefined = undefined\n for await (const line of source) {\n if (line === '') {\n expectMeta = true\n columns = undefined\n } else {\n const values = splitter.splitLine(line)\n const size = splitter.lastSplitLength\n if (expectMeta) {\n // create columns\n if (!columns) {\n columns = new Array(size)\n for (let i = 0; i < size; i++) {\n columns[i] = newFluxTableColumn()\n }\n }\n if (!values[0].startsWith('#')) {\n // fill in column names\n if (values[0] === '') {\n firstColumnIndex = 1\n columns = columns.slice(1)\n } else {\n firstColumnIndex = 0\n }\n for (let i = firstColumnIndex; i < size; i++) {\n columns[i - firstColumnIndex].label = values[i]\n }\n lastMeta = createFluxTableMetaData(columns)\n expectMeta = false\n } else if (values[0] === '#datatype') {\n for (let i = 1; i < size; i++) {\n columns[i].dataType = values[i] as ColumnType\n }\n } else if (values[0] === '#default') {\n for (let i = 1; i < size; i++) {\n columns[i].defaultValue = values[i]\n }\n } else if (values[0] === '#group') {\n for (let i = 1; i < size; i++) {\n columns[i].group = values[i][0] === 't'\n }\n }\n } else {\n yield {\n values: values.slice(firstColumnIndex, size),\n tableMeta:\n lastMeta as unknown as FluxTableMetaData /* never undefined */,\n }\n }\n }\n }\n}\n","import {CommunicationObserver} from './CommunicationObserver'\n\n/**\n * StringToLines is a transformation that emmits strings for each CSV\n * line in the supplied source string.\n * @param source - source string\n * @param target - target to emmit CSV lines to\n * @returns communication obrver to accept Uint8Arrays\n */\nexport function stringToLines(\n source: string,\n target: CommunicationObserver\n): void {\n let quoted = false\n let start = 0\n let index = 0\n\n while (index < source.length) {\n const c = source.charCodeAt(index)\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end =\n index > 0 && source.charCodeAt(index - 1) === 13 ? index - 1 : index\n // do not emmit more lines if the processing is already finished\n target.next(source.substring(start, end))\n start = index + 1\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < index) {\n target.next(source.substring(start, index))\n }\n target.complete()\n}\n","/* Observable interop typing. Taken from https://github.com/ReactiveX/rxjs */\n\n/* Note: This will add Symbol.observable globally for all TypeScript users */\ndeclare global {\n interface SymbolConstructor {\n readonly observable: symbol\n }\n}\n\n/** Symbol.observable or a string \"\\@\\@observable\". Used for interop */\nexport const symbolObservable = (():\n | typeof Symbol.observable\n | '@@observable' =>\n (typeof Symbol === 'function' && Symbol.observable) || '@@observable')()\n","import {\n Observable,\n Observer,\n ObserverComplete,\n ObserverError,\n ObserverNext,\n Subscription,\n symbolObservable,\n} from '../observable'\nimport {CommunicationObserver} from '../results/CommunicationObserver'\nimport {Cancellable} from '../results/Cancellable'\n\n/** APIExecutor executes the API and passes its response to the supplied consumer */\nexport type APIExecutor = (consumer: CommunicationObserver) => void\n\ntype Decorator = (observer: Observer) => Observer\n\nclass QuerySubscription implements Subscription {\n private cancellable?: Cancellable\n private isClosed = false\n\n public constructor(observer: Observer, executor: APIExecutor) {\n try {\n executor({\n next: (value) => {\n observer.next(value)\n },\n error: (e) => {\n this.isClosed = true\n observer.error(e)\n },\n complete: () => {\n this.isClosed = true\n observer.complete()\n },\n useCancellable: (c) => {\n this.cancellable = c\n },\n })\n } catch (e) {\n this.isClosed = true\n observer.error(e)\n }\n }\n\n public get closed(): boolean {\n return this.isClosed\n }\n\n public unsubscribe(): void {\n this.cancellable?.cancel()\n this.isClosed = true\n }\n}\n\nfunction noop(): void {}\n\nfunction completeObserver(observer: Partial>): Observer {\n const {next, error, complete} = observer\n\n return {\n next: next ? next.bind(observer) : noop,\n error: error ? error.bind(observer) : noop,\n complete: complete ? complete.bind(observer) : noop,\n }\n}\n\nexport default class ObservableQuery implements Observable {\n public constructor(\n private readonly executor: APIExecutor,\n private readonly decorator: Decorator\n ) {}\n\n public subscribe(\n observerOrNext?: Partial> | ObserverNext,\n error?: ObserverError,\n complete?: ObserverComplete\n ): Subscription {\n const observer = completeObserver(\n typeof observerOrNext !== 'object' || observerOrNext === null\n ? {next: observerOrNext, error, complete}\n : observerOrNext\n )\n\n return new QuerySubscription(this.decorator(observer), this.executor)\n }\n\n public [symbolObservable](): this {\n return this\n }\n\n // this makes sure we satisfy the interface, while using a possibly polyfilled\n // [symbolObservable] above for the actual implementation\n public declare [Symbol.observable]: () => this\n}\n","import {Transport} from './transport'\nimport WriteApi from './WriteApi'\n\n/**\n * Option for the communication with InfluxDB server.\n */\nexport interface ConnectionOptions {\n /** base URL */\n url: string\n /** authentication token */\n token?: string\n /**\n * socket timeout, 10000 milliseconds by default in node.js\n * @defaultValue 10000\n */\n timeout?: number\n /**\n * TransportOptions supply extra options for the transport layer, they differ between node.js and browser/deno.\n * Node.js transport accepts options specified in {@link https://nodejs.org/api/http.html#http_http_request_options_callback | http.request } or\n * {@link https://nodejs.org/api/https.html#https_https_request_options_callback | https.request }. For example, an `agent` property can be set to\n * {@link https://www.npmjs.com/package/proxy-http-agent | setup HTTP/HTTPS proxy }, {@link https://nodejs.org/api/tls.html#tls_tls_connect_options_callback | rejectUnauthorized }\n * property can disable TLS server certificate verification. Additionally,\n * {@link https://github.com/follow-redirects/follow-redirects | follow-redirects } property can be also specified\n * in order to follow redirects in node.js.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | fetch } is used under the hood in browser/deno.\n * For example,\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | redirect } property can be set to 'error' to abort request if a redirect occurs.\n */\n transportOptions?: {[key: string]: any}\n /**\n * Default HTTP headers to send with every request.\n */\n headers?: Record\n /**\n * Full HTTP web proxy URL including schema, for example http://your-proxy:8080.\n */\n proxyUrl?: string\n}\n\n/** default connection options */\nexport const DEFAULT_ConnectionOptions: Partial = {\n timeout: 10000,\n}\n\n/**\n * Options that configure strategy for retrying failed requests.\n */\nexport interface RetryDelayStrategyOptions {\n /** add `random(retryJitter)` milliseconds delay when retrying HTTP calls */\n retryJitter: number\n /** minimum delay when retrying write (milliseconds) */\n minRetryDelay: number\n /** maximum delay when retrying write (milliseconds) */\n maxRetryDelay: number\n /** base for the exponential retry delay */\n exponentialBase: number\n /**\n * randomRetry indicates whether the next retry delay is deterministic (false) or random (true).\n * The deterministic delay starts with `minRetryDelay * exponentialBase` and it is multiplied\n * by `exponentialBase` until it exceeds `maxRetryDelay`.\n * When random is `true`, the next delay is computed as a random number between next retry attempt (upper)\n * and the lower number in the deterministic sequence. `random(retryJitter)` is added to every returned value.\n */\n randomRetry: boolean\n}\n\n/**\n * Options that configure strategy for retrying failed InfluxDB write operations.\n */\nexport interface WriteRetryOptions extends RetryDelayStrategyOptions {\n /**\n * WriteFailed is called to inform about write errors.\n * @param this - the instance of the API that failed\n * @param error - write error\n * @param lines - failed lines\n * @param attempt - count of already failed attempts to write the lines (1 ... maxRetries+1)\n * @param expires - expiration time for the lines to be retried in millis since epoch\n * @returns a Promise to force the API to use it as a result of the flush operation,\n * void/undefined to continue with default retry mechanism\n */\n writeFailed(\n this: WriteApi,\n error: Error,\n lines: Array,\n attempt: number,\n expires: number\n ): Promise | void\n\n /**\n * WriteSuccess is informed about successfully written lines.\n * @param this - the instance of the API in use\n * @param lines - written lines\n */\n writeSuccess(this: WriteApi, lines: Array): void\n\n /**\n * WriteRetrySkipped is informed about lines that were removed from the retry buffer\n * to keep the size of the retry buffer under the configured limit (maxBufferLines).\n * @param entry - lines that were skipped\n */\n writeRetrySkipped(entry: {lines: Array; expires: number}): void\n\n /** max count of retries after the first write fails */\n maxRetries: number\n /** max time (millis) that can be spent with retries */\n maxRetryTime: number\n /** the maximum size of retry-buffer (in lines) */\n maxBufferLines: number\n}\n\n/**\n * Options used by {@link WriteApi} .\n */\nexport interface WriteOptions extends WriteRetryOptions {\n /** max number of records/lines to send in a batch */\n batchSize: number\n /** delay between data flushes in milliseconds, at most `batch size` records are sent during flush */\n flushInterval: number\n /** default tags, unescaped */\n defaultTags?: Record\n /** HTTP headers that will be sent with every write request */\n headers?: {[key: string]: string}\n /** When specified, write bodies larger than the threshold are gzipped */\n gzipThreshold?: number\n /** max size of a batch in bytes */\n maxBatchBytes: number\n /** InfluxDB Enterprise write consistency as explained in https://docs.influxdata.com/enterprise_influxdb/v1.9/concepts/clustering/#write-consistency */\n consistency?: 'any' | 'one' | 'quorum' | 'all'\n}\n\n/** default RetryDelayStrategyOptions */\nexport const DEFAULT_RetryDelayStrategyOptions = {\n retryJitter: 200,\n minRetryDelay: 5000,\n maxRetryDelay: 125000,\n exponentialBase: 5,\n randomRetry: true,\n}\n\n/** default writeOptions */\nexport const DEFAULT_WriteOptions: WriteOptions = {\n batchSize: 1000,\n maxBatchBytes: 50_000_000, // default max batch size in the cloud\n flushInterval: 60000,\n writeFailed: function () {},\n writeSuccess: function () {},\n writeRetrySkipped: function () {},\n maxRetries: 5,\n maxRetryTime: 180_000,\n maxBufferLines: 32_000,\n // a copy of DEFAULT_RetryDelayStrategyOptions, so that DEFAULT_WriteOptions could be tree-shaken\n retryJitter: 200,\n minRetryDelay: 5000,\n maxRetryDelay: 125000,\n exponentialBase: 2,\n gzipThreshold: 1000,\n randomRetry: true,\n}\n\n/**\n * Options used by {@link InfluxDB} .\n */\nexport interface ClientOptions extends ConnectionOptions {\n /** supplies and overrides default writing options */\n writeOptions?: Partial\n /** specifies custom transport */\n transport?: Transport\n}\n\n/**\n * Timestamp precision used in write operations.\n * See {@link https://docs.influxdata.com/influxdb/latest/api/#operation/PostWrite }\n */\nexport type WritePrecisionType = 'ns' | 'us' | 'ms' | 's'\n","function createEscaper(\n characters: string,\n replacements: string[]\n): (value: string) => string {\n return function (value: string): string {\n let retVal = ''\n let from = 0\n let i = 0\n while (i < value.length) {\n const found = characters.indexOf(value[i])\n if (found >= 0) {\n retVal += value.substring(from, i)\n retVal += replacements[found]\n from = i + 1\n }\n i++\n }\n if (from == 0) {\n return value\n } else if (from < value.length) {\n retVal += value.substring(from, value.length)\n }\n return retVal\n }\n}\nfunction createQuotedEscaper(\n characters: string,\n replacements: string[]\n): (value: string) => string {\n const escaper = createEscaper(characters, replacements)\n return (value: string): string => '\"' + escaper(value) + '\"'\n}\n\n/**\n * Provides functions escape specific parts in InfluxDB line protocol.\n */\nexport const escape = {\n /**\n * Measurement escapes measurement names.\n */\n measurement: createEscaper(', \\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\n', '\\\\r', '\\\\t']),\n /**\n * Quoted escapes quoted values, such as database names.\n */\n quoted: createQuotedEscaper('\"\\\\', ['\\\\\"', '\\\\\\\\']),\n\n /**\n * TagEscaper escapes tag keys, tag values, and field keys.\n */\n tag: createEscaper(', =\\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\=', '\\\\n', '\\\\r', '\\\\t']),\n}\n","declare let process: any\nconst zeroPadding = '000000000'\nlet useHrTime = false\n\nexport function useProcessHrtime(use: boolean): boolean {\n /* istanbul ignore else */\n if (!process.env.BUILD_BROWSER) {\n return (useHrTime = use && process && typeof process.hrtime === 'function')\n } else {\n return false\n }\n}\nuseProcessHrtime(true) // preffer node\n\nlet startHrMillis: number | undefined = undefined\nlet startHrTime: [number, number] | undefined = undefined\nlet lastMillis = Date.now()\nlet stepsInMillis = 0\nfunction nanos(): string {\n if (!process.env.BUILD_BROWSER && useHrTime) {\n const hrTime = process.hrtime() as [number, number]\n let millis = Date.now()\n if (!startHrTime) {\n startHrTime = hrTime\n startHrMillis = millis\n } else {\n hrTime[0] = hrTime[0] - startHrTime[0]\n hrTime[1] = hrTime[1] - startHrTime[1]\n // istanbul ignore next \"cannot mock system clock, manually reviewed\"\n if (hrTime[1] < 0) {\n hrTime[0] -= 1\n hrTime[1] += 1000_000_000\n }\n millis =\n (startHrMillis as number) +\n hrTime[0] * 1000 +\n Math.floor(hrTime[1] / 1000_000)\n }\n const nanos = String(hrTime[1] % 1000_000)\n return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n } else {\n const millis = Date.now()\n if (millis !== lastMillis) {\n lastMillis = millis\n stepsInMillis = 0\n } else {\n stepsInMillis++\n }\n const nanos = String(stepsInMillis)\n return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n }\n}\n\nfunction micros(): string {\n if (!process.env.BUILD_BROWSER && useHrTime) {\n const hrTime = process.hrtime() as [number, number]\n const micros = String(Math.trunc(hrTime[1] / 1000) % 1000)\n return (\n String(Date.now()) + zeroPadding.substr(0, 3 - micros.length) + micros\n )\n } else {\n return String(Date.now()) + zeroPadding.substr(0, 3)\n }\n}\nfunction millis(): string {\n return String(Date.now())\n}\nfunction seconds(): string {\n return String(Math.floor(Date.now() / 1000))\n}\n\n/**\n * Exposes functions that creates strings that represent a timestamp that\n * can be used in the line protocol. Micro and nano timestamps are emulated\n * depending on the js platform in use.\n */\nexport const currentTime = {\n s: seconds as () => string,\n ms: millis as () => string,\n us: micros as () => string,\n ns: nanos as () => string,\n seconds: seconds as () => string,\n millis: millis as () => string,\n micros: micros as () => string,\n nanos: nanos as () => string,\n}\n\n/**\n * dateToProtocolTimestamp provides converters for JavaScript Date to InfluxDB Write Protocol Timestamp. Keys are supported precisions.\n */\nexport const dateToProtocolTimestamp = {\n s: (d: Date): string => `${Math.floor(d.getTime() / 1000)}`,\n ms: (d: Date): string => `${d.getTime()}`,\n us: (d: Date): string => `${d.getTime()}000`,\n ns: (d: Date): string => `${d.getTime()}000000`,\n}\n\n/**\n * convertTimeToNanos converts Point's timestamp to a string.\n * @param value - supported timestamp value\n * @returns line protocol value\n */\nexport function convertTimeToNanos(\n value: string | number | Date | undefined\n): string | undefined {\n if (value === undefined) {\n return nanos()\n } else if (typeof value === 'string') {\n return value.length > 0 ? value : undefined\n } else if (value instanceof Date) {\n return `${value.getTime()}000000`\n } else if (typeof value === 'number') {\n return String(Math.floor(value))\n } else {\n return String(value)\n }\n}\n","/**\n * Logging interface.\n */\nexport interface Logger {\n error(message: string, err?: any): void\n warn(message: string, err?: any): void\n}\n\n/**\n * Logger that logs to console.out\n */\nexport const consoleLogger: Logger = {\n error(message, error) {\n // eslint-disable-next-line no-console\n console.error('ERROR: ' + message, error ? error : '')\n },\n warn(message, error) {\n // eslint-disable-next-line no-console\n console.warn('WARN: ' + message, error ? error : '')\n },\n}\nlet provider: Logger = consoleLogger\n\nexport const Log: Logger = {\n error(message, error) {\n provider.error(message, error)\n },\n warn(message, error) {\n provider.warn(message, error)\n },\n}\n\n/**\n * Sets custom logger.\n * @param logger - logger to use\n * @returns previous logger\n */\nexport function setLogger(logger: Logger): Logger {\n const previous = provider\n provider = logger\n return previous\n}\n","/** Property that offers a function that returns flux-sanitized value of an object. */\nexport const FLUX_VALUE = Symbol('FLUX_VALUE')\n\n/**\n * A flux parameter can print its (sanitized) flux value.\n */\nexport interface FluxParameterLike {\n [FLUX_VALUE](): string\n}\n\n/**\n * Represents a parameterized query.\n */\nexport interface ParameterizedQuery {\n /**\n * Returns flux query with sanitized parameters.\n */\n toString(): string\n}\n\nclass FluxParameter implements FluxParameterLike, ParameterizedQuery {\n constructor(private fluxValue: string) {}\n toString(): string {\n return this.fluxValue\n }\n [FLUX_VALUE](): string {\n return this.fluxValue\n }\n}\n\n/**\n * Checks if the supplied object is FluxParameterLike\n * @param value - any value\n * @returns true if it is\n */\nfunction isFluxParameterLike(value: any): boolean {\n return typeof value === 'object' && typeof value[FLUX_VALUE] === 'function'\n}\n\n/**\n * Escapes content of the supplied string so it can be wrapped into double qoutes\n * to become a [flux string literal](https://docs.influxdata.com/flux/latest/spec/lexical-elements/#string-literals).\n * @param value - string value\n * @returns sanitized string\n */\nfunction sanitizeString(value: any): string {\n if (value === null || value === undefined) return ''\n value = value.toString()\n let retVal: any = undefined\n let i = 0\n function prepareRetVal(): void {\n if (retVal === undefined) {\n retVal = value.substring(0, i)\n }\n }\n for (; i < value.length; i++) {\n const c = value.charAt(i)\n switch (c) {\n case '\\r':\n prepareRetVal()\n retVal += '\\\\r'\n break\n case '\\n':\n prepareRetVal()\n retVal += '\\\\n'\n break\n case '\\t':\n prepareRetVal()\n retVal += '\\\\t'\n break\n case '\"':\n case '\\\\':\n prepareRetVal()\n retVal = retVal + '\\\\' + c\n break\n case '$':\n // escape ${\n if (i + 1 < value.length && value.charAt(i + 1) === '{') {\n prepareRetVal()\n i++\n retVal += '\\\\${'\n break\n }\n // append $\n if (retVal != undefined) {\n retVal += c\n }\n break\n default:\n if (retVal != undefined) {\n retVal += c\n }\n }\n }\n if (retVal !== undefined) {\n return retVal\n }\n return value\n}\n\n/**\n * Creates a flux string literal.\n */\nexport function fluxString(value: any): FluxParameterLike {\n return new FluxParameter(`\"${sanitizeString(value)}\"`)\n}\n\n/**\n * Sanitizes float value to avoid injections.\n * @param value - InfluxDB float literal\n * @returns sanitized float value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeFloat(value: any): string {\n const val = Number(value)\n if (!isFinite(val)) {\n if (typeof value === 'number') {\n return `float(v: \"${val}\")`\n }\n throw new Error(`not a flux float: ${value}`)\n }\n // try to return a flux float literal if possible\n // https://docs.influxdata.com/flux/latest/data-types/basic/float/#float-syntax\n const strVal = val.toString()\n let hasDot = false\n for (const c of strVal) {\n if ((c >= '0' && c <= '9') || c == '-') continue\n if (c === '.') {\n hasDot = true\n continue\n }\n return `float(v: \"${strVal}\")`\n }\n return hasDot ? strVal : strVal + '.0'\n}\n/**\n * Creates a flux float literal.\n */\nexport function fluxFloat(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeFloat(value))\n}\n\n/**\n * Sanitizes integer value to avoid injections.\n * @param value - InfluxDB integer literal\n * @returns sanitized integer value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeInteger(value: any): string {\n // https://docs.influxdata.com/flux/latest/data-types/basic/int/\n // Min value: -9223372036854775808\n // Max value: 9223372036854775807\n // \"9223372036854775807\".length === 19\n const strVal = String(value)\n const negative = strVal.startsWith('-')\n const val = negative ? strVal.substring(1) : strVal\n if (val.length === 0 || val.length > 19) {\n throw new Error(`not a flux integer: ${strVal}`)\n }\n for (const c of val) {\n if (c < '0' || c > '9') throw new Error(`not a flux integer: ${strVal}`)\n }\n if (val.length === 19) {\n if (negative && val > '9223372036854775808') {\n throw new Error(`flux integer out of bounds: ${strVal}`)\n }\n if (!negative && val > '9223372036854775807') {\n throw new Error(`flux integer out of bounds: ${strVal}`)\n }\n }\n return strVal\n}\n\n/**\n * Creates a flux integer literal.\n */\nexport function fluxInteger(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeInteger(value))\n}\n\nfunction sanitizeDateTime(value: any): string {\n return `time(v: \"${sanitizeString(value)}\")`\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDateTime(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeDateTime(value))\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDuration(value: any): FluxParameterLike {\n return new FluxParameter(`duration(v: \"${sanitizeString(value)}\")`)\n}\n\nfunction sanitizeRegExp(value: any): string {\n if (value instanceof RegExp) {\n return value.toString()\n }\n return new RegExp(value).toString()\n}\n\n/**\n * Creates flux regexp literal out of a regular expression. See\n * https://docs.influxdata.com/flux/latest/data-types/basic/regexp/#regular-expression-syntax\n * for details.\n */\nexport function fluxRegExp(value: any): FluxParameterLike {\n // let the server decide if a regexp can be parsed\n return new FluxParameter(sanitizeRegExp(value))\n}\n\n/**\n * Creates flux boolean literal.\n */\nexport function fluxBool(value: any): FluxParameterLike {\n if (value === 'true' || value === 'false') {\n return new FluxParameter(value)\n }\n return new FluxParameter((!!value).toString())\n}\n\n/**\n * Assumes that the supplied value is flux expression or literal that does not need sanitizing.\n *\n * @param value - any value\n * @returns the supplied value as-is\n */\nexport function fluxExpression(value: any): FluxParameterLike {\n return new FluxParameter(String(value))\n}\n\n/**\n * Escapes content of the supplied parameter so that it can be safely embedded into flux query.\n * @param value - parameter value\n * @returns sanitized flux value or an empty string if it cannot be converted\n */\nexport function toFluxValue(value: any): string {\n if (value === undefined) {\n return ''\n } else if (value === null) {\n return 'null'\n } else if (typeof value === 'boolean') {\n return value.toString()\n } else if (typeof value === 'string') {\n return `\"${sanitizeString(value)}\"`\n } else if (typeof value === 'number') {\n if (Number.isSafeInteger(value)) {\n return sanitizeInteger(value)\n }\n return sanitizeFloat(value)\n } else if (typeof value === 'object') {\n if (typeof value[FLUX_VALUE] === 'function') {\n return value[FLUX_VALUE]()\n } else if (value instanceof Date) {\n return value.toISOString()\n } else if (value instanceof RegExp) {\n return sanitizeRegExp(value)\n } else if (Array.isArray(value)) {\n return `[${value.map(toFluxValue).join(',')}]`\n }\n } else if (typeof value === 'bigint') {\n return `${value}.0`\n }\n // use toString value for unrecognized object, symbol\n return toFluxValue(value.toString())\n}\n\n/**\n * Flux is a tagged template that sanitizes supplied parameters\n * to avoid injection attacks in flux.\n */\nexport function flux(\n strings: TemplateStringsArray,\n ...values: any\n): ParameterizedQuery {\n if (strings.length == 1 && values.length === 0) {\n return fluxExpression(strings[0]) // the simplest case\n }\n const parts = new Array(strings.length + values.length)\n let partIndex = 0\n for (let i = 0; i < strings.length; i++) {\n const text = strings[i]\n parts[partIndex++] = text\n if (i < values.length) {\n const val = values[i]\n let sanitized: string\n if (\n text.endsWith('\"') &&\n i + 1 < strings.length &&\n strings[i + 1].startsWith('\"')\n ) {\n // parameter is wrapped into flux double quotes\n sanitized = sanitizeString(val)\n } else {\n sanitized = toFluxValue(val)\n if (sanitized === '') {\n // do not allow to insert empty strings, unless it is FluxParameterLike\n if (!isFluxParameterLike(val)) {\n throw new Error(\n `Unsupported parameter literal '${val}' at index: ${i}, type: ${typeof val}`\n )\n }\n }\n }\n parts[partIndex++] = sanitized\n } else if (i < strings.length - 1) {\n throw new Error('Too few parameters supplied!')\n }\n }\n // return flux expression so that flux can be embedded into another flux as-is\n return fluxExpression(parts.join(''))\n}\n","import {convertTimeToNanos} from './util/currentTime'\nimport {escape} from './util/escape'\n\n/**\n * Settings that control the way of how a {@link Point} is serialized\n * to a protocol line.\n */\nexport interface PointSettings {\n /** default tags to add to every point */\n defaultTags?: {[key: string]: string}\n /** convertTime serializes Point's timestamp to a line protocol value */\n convertTime?: (\n value: string | number | Date | undefined\n ) => string | undefined\n}\n\n/**\n * Point defines values of a single measurement.\n */\nexport class Point {\n private name: string\n private tags: {[key: string]: string} = {}\n /** escaped field values */\n public fields: {[key: string]: string} = {}\n private time: string | number | Date | undefined\n\n /**\n * Create a new Point with specified a measurement name.\n *\n * @param measurementName - the measurement name\n */\n constructor(measurementName?: string) {\n if (measurementName) this.name = measurementName\n }\n\n /**\n * Sets point's measurement.\n *\n * @param name - measurement name\n * @returns this\n */\n public measurement(name: string): Point {\n this.name = name\n return this\n }\n\n /**\n * Adds a tag. The caller has to ensure that both name and value are not empty\n * and do not end with backslash.\n *\n * @param name - tag name\n * @param value - tag value\n * @returns this\n */\n public tag(name: string, value: string): Point {\n this.tags[name] = value\n return this\n }\n\n /**\n * Adds a boolean field.\n *\n * @param field - field name\n * @param value - field value\n * @returns this\n */\n public booleanField(name: string, value: boolean | any): Point {\n this.fields[name] = value ? 'T' : 'F'\n return this\n }\n\n /**\n * Adds an integer field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN or out of int64 range value is supplied\n */\n public intField(name: string, value: number | any): Point {\n let val: number\n if (typeof value === 'number') {\n val = value\n } else {\n val = parseInt(String(value))\n }\n if (isNaN(val) || val <= -9223372036854776e3 || val >= 9223372036854776e3) {\n throw new Error(`invalid integer value for field '${name}': '${value}'!`)\n }\n this.fields[name] = `${Math.floor(val)}i`\n return this\n }\n\n /**\n * Adds an unsigned integer field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN out of range value is supplied\n */\n public uintField(name: string, value: number | any): Point {\n if (typeof value === 'number') {\n if (isNaN(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {\n throw new Error(`uint value for field '${name}' out of range: ${value}`)\n }\n this.fields[name] = `${Math.floor(value as number)}u`\n } else {\n const strVal = String(value)\n for (let i = 0; i < strVal.length; i++) {\n const code = strVal.charCodeAt(i)\n if (code < 48 || code > 57) {\n throw new Error(\n `uint value has an unsupported character at pos ${i}: ${value}`\n )\n }\n }\n if (\n strVal.length > 20 ||\n (strVal.length === 20 &&\n strVal.localeCompare('18446744073709551615') > 0)\n ) {\n throw new Error(\n `uint value for field '${name}' out of range: ${strVal}`\n )\n }\n this.fields[name] = `${strVal}u`\n }\n return this\n }\n\n /**\n * Adds a number field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN/Infinity/-Infinity is supplied\n */\n public floatField(name: string, value: number | any): Point {\n let val: number\n if (typeof value === 'number') {\n val = value\n } else {\n val = parseFloat(value)\n }\n if (!isFinite(val)) {\n throw new Error(`invalid float value for field '${name}': ${value}`)\n }\n\n this.fields[name] = String(val)\n return this\n }\n\n /**\n * Adds a string field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n */\n public stringField(name: string, value: string | any): Point {\n if (value !== null && value !== undefined) {\n if (typeof value !== 'string') value = String(value)\n this.fields[name] = escape.quoted(value)\n }\n return this\n }\n\n /**\n * Sets point timestamp. Timestamp can be specified as a Date (preferred), number, string\n * or an undefined value. An undefined value instructs to assign a local timestamp using\n * the client's clock. An empty string can be used to let the server assign\n * the timestamp. A number value represents time as a count of time units since epoch, the\n * exact time unit then depends on the {@link InfluxDB.getWriteApi | precision} of the API\n * that writes the point.\n *\n * Beware that the current time in nanoseconds can't precisely fit into a JS number,\n * which can hold at most 2^53 integer number. Nanosecond precision numbers are thus supplied as\n * a (base-10) string. An application can also use ES2020 BigInt to represent nanoseconds,\n * BigInt's `toString()` returns the required high-precision string.\n *\n * Note that InfluxDB requires the timestamp to fit into int64 data type.\n *\n * @param value - point time\n * @returns this\n */\n public timestamp(value: Date | number | string | undefined): Point {\n this.time = value\n return this\n }\n\n /**\n * Creates an InfluxDB protocol line out of this instance.\n * @param settings - settings control serialization of a point timestamp and can also add default tags,\n * nanosecond timestamp precision is used when no `settings` or no `settings.convertTime` is supplied.\n * @returns an InfluxDB protocol line out of this instance\n */\n public toLineProtocol(settings?: Partial): string | undefined {\n if (!this.name) return undefined\n let fieldsLine = ''\n Object.keys(this.fields)\n .sort()\n .forEach((x) => {\n if (x) {\n const val = this.fields[x]\n if (fieldsLine.length > 0) fieldsLine += ','\n fieldsLine += `${escape.tag(x)}=${val}`\n }\n })\n if (fieldsLine.length === 0) return undefined // no fields present\n let tagsLine = ''\n const tags =\n settings && settings.defaultTags\n ? {...settings.defaultTags, ...this.tags}\n : this.tags\n Object.keys(tags)\n .sort()\n .forEach((x) => {\n if (x) {\n const val = tags[x]\n if (val) {\n tagsLine += ','\n tagsLine += `${escape.tag(x)}=${escape.tag(val)}`\n }\n }\n })\n let time = this.time\n if (settings && settings.convertTime) {\n time = settings.convertTime(time)\n } else {\n time = convertTimeToNanos(time)\n }\n\n return `${escape.measurement(this.name)}${tagsLine} ${fieldsLine}${\n time !== undefined ? ' ' + time : ''\n }`\n }\n\n toString(): string {\n const line = this.toLineProtocol(undefined)\n return line ? line : `invalid point: ${JSON.stringify(this, undefined)}`\n }\n}\n","import {getRetryDelay, RetryDelayStrategy} from '../errors'\nimport {\n RetryDelayStrategyOptions,\n DEFAULT_RetryDelayStrategyOptions,\n} from '../options'\n\n/**\n * Applies a variant of exponential backoff with initial and max delay and a random\n * jitter delay. It also respects `retry delay` when specified together with an error.\n */\nexport class RetryStrategyImpl implements RetryDelayStrategy {\n options: RetryDelayStrategyOptions\n currentDelay: number | undefined\n\n constructor(options?: Partial) {\n this.options = {...DEFAULT_RetryDelayStrategyOptions, ...options}\n this.success()\n }\n\n nextDelay(error?: Error, failedAttempts?: number): number {\n const delay = getRetryDelay(error)\n if (delay && delay > 0) {\n return delay + Math.round(Math.random() * this.options.retryJitter)\n } else {\n if (failedAttempts && failedAttempts > 0) {\n // compute delay\n if (this.options.randomRetry) {\n // random delay between deterministic delays\n let delay = Math.max(this.options.minRetryDelay, 1)\n let nextDelay = delay * this.options.exponentialBase\n for (let i = 1; i < failedAttempts; i++) {\n delay = nextDelay\n nextDelay = nextDelay * this.options.exponentialBase\n if (nextDelay >= this.options.maxRetryDelay) {\n nextDelay = this.options.maxRetryDelay\n break\n }\n }\n return (\n delay +\n Math.round(\n Math.random() * (nextDelay - delay) +\n Math.random() * this.options.retryJitter\n )\n )\n }\n // deterministric delay otherwise\n let delay = Math.max(this.options.minRetryDelay, 1)\n for (let i = 1; i < failedAttempts; i++) {\n delay = delay * this.options.exponentialBase\n if (delay >= this.options.maxRetryDelay) {\n delay = this.options.maxRetryDelay\n break\n }\n }\n return delay + Math.round(Math.random() * this.options.retryJitter)\n } else if (this.currentDelay) {\n this.currentDelay = Math.min(\n Math.max(this.currentDelay * this.options.exponentialBase, 1) +\n Math.round(Math.random() * this.options.retryJitter),\n this.options.maxRetryDelay\n )\n } else {\n this.currentDelay =\n this.options.minRetryDelay +\n Math.round(Math.random() * this.options.retryJitter)\n }\n return this.currentDelay\n }\n }\n success(): void {\n this.currentDelay = undefined\n }\n}\n\n/**\n * Creates a new instance of retry strategy.\n * @param options - retry options\n * @returns retry strategy implementation\n */\nexport function createRetryDelayStrategy(\n options?: Partial\n): RetryDelayStrategy {\n return new RetryStrategyImpl(options)\n}\n","import {Log} from '../util/logger'\n\ninterface RetryItem {\n lines: string[]\n retryCount: number\n retryTime: number\n expires: number\n next?: RetryItem\n}\n\ntype FindShrinkCandidateResult = [found: RetryItem, parent?: RetryItem]\n\nfunction findShrinkCandidate(first: RetryItem): FindShrinkCandidateResult {\n let parent = undefined\n let found = first\n let currentParent = first\n while (currentParent.next) {\n if (currentParent.next.expires < found.expires) {\n parent = currentParent\n found = currentParent.next\n }\n currentParent = currentParent.next\n }\n return [found, parent]\n}\n\n/**\n * Retries lines up to a limit of max buffer size.\n */\nexport default class RetryBuffer {\n first?: RetryItem\n size = 0\n closed = false\n private _timeoutHandle: any = undefined\n\n constructor(\n private maxLines: number,\n private retryLines: (\n lines: string[],\n retryCountdown: number,\n started: number\n ) => Promise,\n private onShrink: (entry: {\n lines: string[]\n retryCount: number\n expires: number\n }) => void = () => undefined\n ) {}\n\n addLines(\n lines: string[],\n retryCount: number,\n delay: number,\n expires: number\n ): void {\n if (this.closed) return\n if (!lines.length) return\n let retryTime = Date.now() + delay\n if (expires < retryTime) {\n retryTime = expires\n }\n // ensure at most maxLines are in the Buffer\n if (this.first && this.size + lines.length > this.maxLines) {\n const origSize = this.size\n const newSize = origSize * 0.7 // reduce to 70 %\n do {\n // remove \"oldest\" item\n const [found, parent] = findShrinkCandidate(this.first)\n this.size -= found.lines.length\n if (parent) {\n parent.next = found.next\n } else {\n this.first = found.next\n if (this.first) {\n this.scheduleRetry(this.first.retryTime - Date.now())\n }\n }\n found.next = undefined\n this.onShrink(found)\n } while (this.first && this.size + lines.length > newSize)\n Log.error(\n `RetryBuffer: ${\n origSize - this.size\n } oldest lines removed to keep buffer size under the limit of ${\n this.maxLines\n } lines.`\n )\n }\n const toAdd: RetryItem = {\n lines,\n retryCount,\n retryTime,\n expires,\n }\n // insert sorted according to retryTime\n let current: RetryItem | undefined = this.first\n let parent = undefined\n for (;;) {\n if (!current || current.retryTime > retryTime) {\n toAdd.next = current\n if (parent) {\n parent.next = toAdd\n } else {\n this.first = toAdd\n this.scheduleRetry(retryTime - Date.now())\n }\n break\n }\n parent = current\n current = current.next\n }\n this.size += lines.length\n }\n\n removeLines(): RetryItem | undefined {\n if (this.first) {\n const toRetry = this.first\n this.first = this.first.next\n toRetry.next = undefined\n this.size -= toRetry.lines.length\n return toRetry\n }\n return undefined\n }\n\n scheduleRetry(delay: number): void {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle)\n }\n this._timeoutHandle = setTimeout(() => {\n const toRetry = this.removeLines()\n if (toRetry) {\n this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n .catch(() => {\n /* error is already logged, it must be caught */\n })\n .finally(() => {\n // schedule next retry execution\n if (this.first) {\n this.scheduleRetry(this.first.retryTime - Date.now())\n }\n })\n } else {\n this._timeoutHandle = undefined\n }\n }, Math.max(delay, 0))\n }\n\n async flush(): Promise {\n let toRetry\n while ((toRetry = this.removeLines())) {\n await this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n }\n }\n\n close(): number {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle)\n this._timeoutHandle = undefined\n }\n this.closed = true\n return this.size\n }\n}\n","/**\n * Utf8Length returns an expected length of a string when UTF-8 encoded.\n * @param s - input string\n * @returns expected count of bytes\n */\nexport default function utf8Length(s: string): number {\n let retVal = s.length\n // extends the size with code points (https://en.wikipedia.org/wiki/UTF-8#Encoding)\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i)\n /* istanbul ignore else - JS does not count with 4-bytes UNICODE characters at the moment */\n if (code < 0x80) {\n continue\n } else if (code >= 0x80 && code <= 0x7ff) {\n retVal++\n } else if (code >= 0x800 && code <= 0xffff) {\n if (code >= 0xd800 && code <= 0xdfff) {\n // node.js represents unicode characters above 0xffff by two UTF-16 surrogate halves\n // see https://en.wikipedia.org/wiki/UTF-8#Codepage_layout\n retVal++\n } else {\n retVal += 2\n }\n } else {\n // never happens in node.js 14, the situation can vary in the futures or in deno/browsers\n retVal += 3\n }\n }\n return retVal\n}\n","import WriteApi from '../WriteApi'\nimport {\n DEFAULT_WriteOptions,\n WriteOptions,\n WritePrecisionType,\n} from '../options'\nimport {Transport, SendOptions} from '../transport'\nimport {Headers} from '../results'\nimport {Log} from '../util/logger'\nimport {HttpError, RetryDelayStrategy} from '../errors'\nimport {Point} from '../Point'\nimport {currentTime, dateToProtocolTimestamp} from '../util/currentTime'\nimport {createRetryDelayStrategy} from './retryStrategy'\nimport RetryBuffer from './RetryBuffer'\nimport utf8Length from '../util/utf8Length'\n\nclass WriteBuffer {\n length = 0\n bytes = -1\n lines: string[]\n\n constructor(\n private maxChunkRecords: number,\n private maxBatchBytes: number,\n private flushFn: (lines: string[]) => Promise,\n private scheduleSend: () => void\n ) {\n this.lines = new Array(maxChunkRecords)\n }\n\n add(record: string): void {\n const size = utf8Length(record)\n if (this.length === 0) {\n this.scheduleSend()\n } else if (this.bytes + size + 1 >= this.maxBatchBytes) {\n // the new size already exceeds maxBatchBytes, send it\n this.flush().catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n })\n }\n this.lines[this.length] = record\n this.length++\n this.bytes += size + 1\n if (\n this.length >= this.maxChunkRecords ||\n this.bytes >= this.maxBatchBytes\n ) {\n this.flush().catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n })\n }\n }\n flush(): Promise {\n const lines = this.reset()\n if (lines.length > 0) {\n return this.flushFn(lines)\n } else {\n return Promise.resolve()\n }\n }\n reset(): string[] {\n const retVal = this.lines.slice(0, this.length)\n this.length = 0\n this.bytes = -1 // lines are joined with \\n\n return retVal\n }\n}\n\nexport default class WriteApiImpl implements WriteApi {\n public path: string\n\n private writeBuffer: WriteBuffer\n private closed = false\n private writeOptions: WriteOptions\n private sendOptions: SendOptions\n private _timeoutHandle: any = undefined\n private currentTime: () => string\n private dateToProtocolTimestamp: (d: Date) => string\n\n retryBuffer: RetryBuffer\n retryStrategy: RetryDelayStrategy\n\n constructor(\n private transport: Transport,\n org: string,\n bucket: string,\n precision: WritePrecisionType,\n writeOptions?: Partial\n ) {\n this.path = `/api/v2/write?org=${encodeURIComponent(\n org\n )}&bucket=${encodeURIComponent(bucket)}&precision=${precision}`\n if (writeOptions?.consistency) {\n this.path += `&consistency=${encodeURIComponent(\n writeOptions.consistency\n )}`\n }\n this.writeOptions = {\n ...DEFAULT_WriteOptions,\n ...writeOptions,\n }\n this.currentTime = currentTime[precision]\n this.dateToProtocolTimestamp = dateToProtocolTimestamp[precision]\n if (this.writeOptions.defaultTags) {\n this.useDefaultTags(this.writeOptions.defaultTags)\n }\n this.sendOptions = {\n method: 'POST',\n headers: {\n 'content-type': 'text/plain; charset=utf-8',\n ...writeOptions?.headers,\n },\n gzipThreshold: this.writeOptions.gzipThreshold,\n }\n\n const scheduleNextSend = (): void => {\n if (this.writeOptions.flushInterval > 0) {\n this._clearFlushTimeout()\n /* istanbul ignore else manually reviewed, hard to reproduce */\n if (!this.closed) {\n this._timeoutHandle = setTimeout(\n () =>\n this.sendBatch(\n this.writeBuffer.reset(),\n this.writeOptions.maxRetries\n ).catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n }),\n this.writeOptions.flushInterval\n )\n }\n }\n }\n // write buffer\n this.writeBuffer = new WriteBuffer(\n this.writeOptions.batchSize,\n this.writeOptions.maxBatchBytes,\n (lines) => {\n this._clearFlushTimeout()\n return this.sendBatch(lines, this.writeOptions.maxRetries)\n },\n scheduleNextSend\n )\n this.sendBatch = this.sendBatch.bind(this)\n // retry buffer\n this.retryStrategy = createRetryDelayStrategy(this.writeOptions)\n this.retryBuffer = new RetryBuffer(\n this.writeOptions.maxBufferLines,\n this.sendBatch,\n this.writeOptions.writeRetrySkipped\n )\n }\n\n sendBatch(\n lines: string[],\n retryAttempts: number,\n expires: number = Date.now() + this.writeOptions.maxRetryTime\n ): Promise {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self: WriteApiImpl = this\n const failedAttempts = self.writeOptions.maxRetries + 1 - retryAttempts\n if (!this.closed && lines.length > 0) {\n if (expires <= Date.now()) {\n const error = new Error('Max retry time exceeded.')\n const onRetry = self.writeOptions.writeFailed.call(\n self,\n error,\n lines,\n failedAttempts,\n expires\n )\n if (onRetry) {\n return onRetry\n }\n Log.error(\n `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n error\n )\n return Promise.reject(error)\n }\n return new Promise((resolve, reject) => {\n let responseStatusCode: number | undefined\n const callbacks = {\n responseStarted(_headers: Headers, statusCode?: number): void {\n responseStatusCode = statusCode\n },\n error(error: Error): void {\n // call the writeFailed listener and check if we can retry\n const onRetry = self.writeOptions.writeFailed.call(\n self,\n error,\n lines,\n failedAttempts,\n expires\n )\n if (onRetry) {\n onRetry.then(resolve, reject)\n return\n }\n // ignore informational message about the state of InfluxDB\n // enterprise cluster, if present\n if (\n error instanceof HttpError &&\n error.json &&\n typeof error.json.error === 'string' &&\n error.json.error.includes('hinted handoff queue not empty')\n ) {\n Log.warn('Write to InfluxDB returns: ' + error.json.error)\n responseStatusCode = 204\n callbacks.complete()\n return\n }\n // retry if possible\n if (\n !self.closed &&\n retryAttempts > 0 &&\n (!(error instanceof HttpError) ||\n (error as HttpError).statusCode >= 429)\n ) {\n Log.warn(\n `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n error\n )\n self.retryBuffer.addLines(\n lines,\n retryAttempts - 1,\n self.retryStrategy.nextDelay(error, failedAttempts),\n expires\n )\n reject(error)\n return\n }\n Log.error(`Write to InfluxDB failed.`, error)\n reject(error)\n },\n complete(): void {\n // older implementations of transport do not report status code\n if (responseStatusCode == 204 || responseStatusCode == undefined) {\n self.writeOptions.writeSuccess.call(self, lines)\n self.retryStrategy.success()\n resolve()\n } else {\n const message = `204 HTTP response status code expected, but ${responseStatusCode} returned`\n const error = new HttpError(\n responseStatusCode,\n message,\n undefined,\n '0'\n )\n error.message = message\n callbacks.error(error)\n }\n },\n }\n this.transport.send(\n this.path,\n lines.join('\\n'),\n this.sendOptions,\n callbacks\n )\n })\n } else {\n return Promise.resolve()\n }\n }\n\n private _clearFlushTimeout(): void {\n if (this._timeoutHandle !== undefined) {\n clearTimeout(this._timeoutHandle)\n this._timeoutHandle = undefined\n }\n }\n\n writeRecord(record: string): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n this.writeBuffer.add(record)\n }\n writeRecords(records: ArrayLike): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n for (let i = 0; i < records.length; i++) {\n this.writeBuffer.add(records[i])\n }\n }\n writePoint(point: Point): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n const line = point.toLineProtocol(this)\n if (line) this.writeBuffer.add(line)\n }\n writePoints(points: ArrayLike): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n for (let i = 0; i < points.length; i++) {\n const line = points[i].toLineProtocol(this)\n if (line) this.writeBuffer.add(line)\n }\n }\n async flush(withRetryBuffer?: boolean): Promise {\n await this.writeBuffer.flush()\n if (withRetryBuffer) {\n return await this.retryBuffer.flush()\n }\n }\n close(): Promise {\n const retVal = this.writeBuffer.flush().finally(() => {\n const remaining = this.retryBuffer.close()\n if (remaining) {\n Log.error(\n `Retry buffer closed with ${remaining} items that were not written to InfluxDB!`,\n null\n )\n }\n this.closed = true\n })\n return retVal\n }\n dispose(): number {\n this._clearFlushTimeout()\n this.closed = true\n return this.retryBuffer.close() + this.writeBuffer.length\n }\n\n // PointSettings\n defaultTags: {[key: string]: string} | undefined\n useDefaultTags(tags: {[key: string]: string}): WriteApi {\n this.defaultTags = tags\n return this\n }\n convertTime(value: string | number | Date | undefined): string | undefined {\n if (value === undefined) {\n return this.currentTime()\n } else if (typeof value === 'string') {\n return value.length > 0 ? value : undefined\n } else if (value instanceof Date) {\n return this.dateToProtocolTimestamp(value)\n } else if (typeof value === 'number') {\n return String(Math.floor(value))\n } else {\n return String(value)\n }\n }\n}\n","import {ConnectionOptions, DEFAULT_ConnectionOptions} from '../../options'\nimport {parse} from 'url'\nimport * as http from 'http'\nimport * as https from 'https'\nimport {Buffer} from 'buffer'\nimport {RequestTimedOutError, AbortError, HttpError} from '../../errors'\nimport {Transport, SendOptions} from '../../transport'\nimport {\n Cancellable,\n ChunkCombiner,\n CommunicationObserver,\n Headers,\n ResponseStartedFn,\n} from '../../results'\nimport nodeChunkCombiner from './nodeChunkCombiner'\nimport zlib from 'zlib'\nimport completeCommunicationObserver from '../completeCommunicationObserver'\nimport {CLIENT_LIB_VERSION} from '../version'\nimport {Log} from '../../util/logger'\nimport {pipeline, Readable} from 'stream'\n\nconst zlibOptions = {\n flush: zlib.constants.Z_SYNC_FLUSH,\n finishFlush: zlib.constants.Z_SYNC_FLUSH,\n}\nconst emptyBuffer = Buffer.allocUnsafe(0)\n\nclass CancellableImpl implements Cancellable {\n private cancelled = false\n public resume?: () => void\n cancel(): void {\n this.cancelled = true\n if (this.resume) {\n this.resume()\n this.resume = undefined\n }\n }\n isCancelled(): boolean {\n return this.cancelled\n }\n}\n\n/**\n * Transport layer on top of node http or https library.\n */\nexport class NodeHttpTransport implements Transport {\n /* required transport member */\n readonly chunkCombiner: ChunkCombiner = nodeChunkCombiner\n\n private defaultOptions: {[key: string]: any}\n private requestApi: (\n options: http.RequestOptions,\n callback: (res: http.IncomingMessage) => void\n ) => http.ClientRequest\n private contextPath: string\n private token?: string\n private headers: Record\n /**\n * Creates a node transport using for the client options supplied.\n * @param connectionOptions - connection options\n */\n constructor(connectionOptions: ConnectionOptions) {\n const {\n url: _url,\n proxyUrl,\n token,\n transportOptions,\n ...nodeSupportedOptions\n } = connectionOptions\n const url = parse(proxyUrl || _url)\n this.token = token\n this.defaultOptions = {\n ...DEFAULT_ConnectionOptions,\n ...nodeSupportedOptions,\n ...transportOptions,\n port: url.port,\n protocol: url.protocol,\n hostname: url.hostname,\n }\n this.contextPath = proxyUrl ? _url : url.path ?? ''\n if (this.contextPath.endsWith('/')) {\n this.contextPath = this.contextPath.substring(\n 0,\n this.contextPath.length - 1\n )\n }\n // remove all undefined field to avoid node validation errors\n // https://github.com/influxdata/influxdb-client-js/issues/380\n Object.keys(this.defaultOptions).forEach(\n (key) =>\n this.defaultOptions[key] === undefined &&\n delete this.defaultOptions[key]\n )\n // https://github.com/influxdata/influxdb-client-js/issues/263\n // don't allow /api/v2 suffix to avoid future problems\n if (this.contextPath.endsWith('/api/v2')) {\n Log.warn(\n `Please remove '/api/v2' context path from InfluxDB base url, using ${url.protocol}//${url.hostname}:${url.port} !`\n )\n this.contextPath = ''\n }\n\n if (url.protocol === 'http:') {\n this.requestApi =\n this.defaultOptions['follow-redirects']?.http?.request ?? http.request\n } else if (url.protocol === 'https:') {\n this.requestApi =\n this.defaultOptions['follow-redirects']?.https?.request ?? https.request\n } else {\n throw new Error(\n `Unsupported protocol \"${url.protocol} in URL: \"${connectionOptions.url}\"`\n )\n }\n this.headers = {\n 'User-Agent': `influxdb-client-js/${CLIENT_LIB_VERSION}`,\n ...connectionOptions.headers,\n }\n if (proxyUrl) {\n this.headers['Host'] = parse(_url).host as string\n }\n }\n\n /**\n * Sends data to server and receives communication events via communication callbacks.\n *\n * @param path - HTTP request path\n * @param body - message body\n * @param headers - HTTP headers\n * @param method - HTTP method\n * @param callbacks - communication callbacks\n */\n send(\n path: string,\n body: string,\n options: SendOptions,\n callbacks?: Partial>\n ): void {\n const cancellable = new CancellableImpl()\n if (callbacks && callbacks.useCancellable)\n callbacks.useCancellable(cancellable)\n this.createRequestMessage(\n path,\n body,\n options,\n (message: {[key: string]: any}) => {\n this._request(message, cancellable, callbacks)\n },\n /* istanbul ignore next - hard to simulate failure, manually reviewed */\n (err: Error) => callbacks?.error && callbacks.error(err)\n )\n }\n\n /**\n * Sends data to the server and receives decoded result. The type of the result depends on\n * response's content-type (deserialized json, text).\n \n * @param path - HTTP path\n * @param requestBody - request body\n * @param options - send options\n * @returns Promise of response body\n */\n request(\n path: string,\n body: any,\n options: SendOptions,\n responseStarted?: ResponseStartedFn\n ): Promise {\n if (!body) {\n body = ''\n } else if (typeof body !== 'string') {\n body = JSON.stringify(body)\n }\n let buffer = emptyBuffer\n let contentType: string\n let responseStatusCode: number | undefined\n return new Promise((resolve, reject) => {\n this.send(path, body as string, options, {\n responseStarted(headers: Headers, statusCode?: number) {\n if (responseStarted) {\n responseStarted(headers, statusCode)\n }\n contentType = String(headers['content-type'])\n responseStatusCode = statusCode\n },\n next: (data: Uint8Array): void => {\n buffer = Buffer.concat([buffer, data])\n },\n complete: (): void => {\n const responseType = options.headers?.accept ?? contentType\n try {\n if (responseStatusCode === 204) {\n // ignore body of NO_CONTENT response\n resolve(undefined)\n }\n if (responseType.includes('json')) {\n if (buffer.length) {\n resolve(JSON.parse(buffer.toString('utf8')))\n } else {\n resolve(undefined)\n }\n } else if (\n responseType.includes('text') ||\n responseType.startsWith('application/csv')\n ) {\n resolve(buffer.toString('utf8'))\n } else {\n resolve(buffer)\n }\n } catch (e) {\n reject(e)\n }\n },\n error: (e: Error): void => {\n reject(e)\n },\n })\n })\n }\n\n async *iterate(\n path: string,\n body: string,\n options: SendOptions\n ): AsyncIterableIterator {\n let terminationError: Error | undefined = undefined\n let nestedReject: (e: Error) => void\n function wrapReject(error: Error) {\n terminationError = error\n nestedReject(error)\n }\n const requestMessage = await new Promise>(\n (resolve, reject) => {\n nestedReject = reject\n this.createRequestMessage(path, body, options, resolve, wrapReject)\n }\n )\n if (requestMessage.signal?.addEventListener) {\n ;(requestMessage.signal as AbortSignal).addEventListener('abort', () => {\n wrapReject(new AbortError())\n })\n }\n const response = await new Promise(\n (resolve, reject) => {\n nestedReject = reject\n const req = this.requestApi(requestMessage, resolve)\n req.on('timeout', () => wrapReject(new RequestTimedOutError()))\n req.on('error', wrapReject)\n\n req.write(requestMessage.body)\n req.end()\n }\n )\n const res = await new Promise((resolve, reject) => {\n nestedReject = reject\n this._prepareResponse(response, resolve, wrapReject)\n })\n for await (const chunk of res) {\n if (terminationError) {\n throw terminationError\n }\n yield chunk\n }\n }\n /**\n * Creates configuration for a specific request.\n *\n * @param path - API path starting with '/' and containing also query parameters\n * @param body - request body, will be utf-8 encoded\n * @returns a configuration object that is suitable for making the request\n */\n private createRequestMessage(\n path: string,\n body: string,\n sendOptions: SendOptions,\n resolve: (req: http.RequestOptions) => void,\n reject: (err: Error) => void\n ): void {\n const bodyBuffer = Buffer.from(body, 'utf-8')\n const headers: {[key: string]: any} = {\n 'content-type': 'application/json; charset=utf-8',\n ...this.headers,\n }\n if (this.token) {\n headers.authorization = 'Token ' + this.token\n }\n const options: {[key: string]: any} = {\n ...this.defaultOptions,\n path: this.contextPath + path,\n method: sendOptions.method,\n headers: {\n ...headers,\n ...sendOptions.headers,\n },\n }\n if (sendOptions.signal) {\n options.signal = sendOptions.signal\n }\n if (\n sendOptions.gzipThreshold !== undefined &&\n sendOptions.gzipThreshold < bodyBuffer.length\n ) {\n zlib.gzip(bodyBuffer, (err, res) => {\n /* istanbul ignore next - hard to simulate failure, manually reviewed */\n if (err) {\n return reject(err)\n }\n options.headers['content-encoding'] = 'gzip'\n options.body = res\n resolve(options)\n })\n return\n }\n options.body = bodyBuffer\n options.headers['content-length'] = options.body.length\n resolve(options)\n }\n\n private _prepareResponse(\n res: http.IncomingMessage,\n resolve: (res: Readable) => void,\n reject: (err: Error) => void\n ) {\n res.on('aborted', () => {\n reject(new AbortError())\n })\n res.on('error', reject)\n /* istanbul ignore next statusCode is optional in http.IncomingMessage */\n const statusCode = res.statusCode ?? 600\n const contentEncoding = res.headers['content-encoding']\n let responseData\n if (contentEncoding === 'gzip') {\n responseData = zlib.createGunzip(zlibOptions)\n responseData = pipeline(res, responseData, (e) => e && reject(e))\n } else {\n responseData = res\n }\n if (statusCode >= 300) {\n let body = ''\n const isJson = String(res.headers['content-type']).startsWith(\n 'application/json'\n )\n responseData.on('data', (s) => {\n body += s.toString()\n if (!isJson && body.length > 1000) {\n body = body.slice(0, 1000)\n res.resume()\n }\n })\n responseData.on('end', () => {\n if (body === '' && !!res.headers['x-influxdb-error']) {\n body = res.headers['x-influxdb-error'].toString()\n }\n reject(\n new HttpError(\n statusCode,\n res.statusMessage,\n body,\n res.headers['retry-after'],\n res.headers['content-type']\n )\n )\n })\n } else {\n resolve(responseData)\n }\n }\n\n private _request(\n requestMessage: {[key: string]: any},\n cancellable: CancellableImpl,\n callbacks?: Partial>\n ): void {\n const listeners = completeCommunicationObserver(callbacks)\n if (cancellable.isCancelled()) {\n listeners.complete()\n return\n }\n if (requestMessage.signal?.addEventListener) {\n ;(requestMessage.signal as AbortSignal).addEventListener('abort', () => {\n listeners.error(new AbortError())\n })\n }\n const req = this.requestApi(requestMessage, (res: http.IncomingMessage) => {\n /* istanbul ignore next - hard to simulate failure, manually reviewed */\n if (cancellable.isCancelled()) {\n res.resume()\n listeners.complete()\n return\n }\n listeners.responseStarted(res.headers, res.statusCode)\n this._prepareResponse(\n res,\n (responseData) => {\n responseData.on('data', (data) => {\n if (cancellable.isCancelled()) {\n res.resume()\n } else {\n if (listeners.next(data) === false) {\n // pause processing, the consumer signalizes that\n // it is not able to receive more data\n if (!listeners.useResume) {\n listeners.error(\n new Error('Unable to pause, useResume is not configured!')\n )\n res.resume()\n return\n }\n res.pause()\n const resume = () => {\n res.resume()\n }\n cancellable.resume = resume\n listeners.useResume(resume)\n }\n }\n })\n responseData.on('end', listeners.complete)\n },\n listeners.error\n )\n })\n // Support older Nodes which don't allow `timeout` in the\n // request options\n /* istanbul ignore else support older node versions */\n if (typeof req.setTimeout === 'function' && requestMessage.timeout) {\n req.setTimeout(requestMessage.timeout)\n }\n\n req.on('timeout', () => {\n listeners.error(new RequestTimedOutError())\n })\n req.on('error', (error) => {\n listeners.error(error)\n })\n\n /* istanbul ignore else support older node versions */\n if (requestMessage.body) {\n req.write(requestMessage.body)\n }\n req.end()\n }\n}\nexport default NodeHttpTransport\n","import {Buffer} from 'buffer'\nimport {ChunkCombiner} from '../../results'\n\nconst nodeChunkCombiner: ChunkCombiner = {\n concat(first: Uint8Array, second: Uint8Array): Uint8Array {\n return Buffer.concat([first, second])\n },\n toUtf8String(chunk: Uint8Array, start: number, end: number): string {\n return (chunk as Buffer).toString('utf-8', start, end)\n },\n copy(chunk: Uint8Array, start: number, end: number): Uint8Array {\n const retVal = Buffer.allocUnsafe(end - start)\n ;(chunk as Buffer).copy(retVal, 0, start, end)\n return retVal\n },\n}\n\nexport default nodeChunkCombiner\n","import {CommunicationObserver, Headers} from '../results'\n\ntype CompleteObserver = Omit<\n Required>,\n 'useCancellable' | 'useResume'\n> &\n Pick, 'useResume' | 'useCancellable'>\n\nexport default function completeCommunicationObserver(\n callbacks: Partial> = {}\n): CompleteObserver {\n let state = 0\n const retVal: CompleteObserver = {\n next: (data: any): void | boolean => {\n if (\n state === 0 &&\n callbacks.next &&\n data !== null &&\n data !== undefined\n ) {\n return callbacks.next(data)\n }\n },\n error: (error: Error): void => {\n /* istanbul ignore else propagate error at most once */\n if (state === 0) {\n state = 1\n /* istanbul ignore else safety check */\n if (callbacks.error) callbacks.error(error)\n }\n },\n complete: (): void => {\n if (state === 0) {\n state = 2\n /* istanbul ignore else safety check */\n if (callbacks.complete) callbacks.complete()\n }\n },\n responseStarted: (headers: Headers, statusCode?: number): void => {\n if (callbacks.responseStarted)\n callbacks.responseStarted(headers, statusCode)\n },\n }\n if (callbacks.useCancellable) {\n retVal.useCancellable = callbacks.useCancellable.bind(callbacks)\n }\n if (callbacks.useResume) {\n retVal.useResume = callbacks.useResume.bind(callbacks)\n }\n return retVal\n}\n","export const CLIENT_LIB_VERSION = '1.33.1'\n","import {Observable} from '../observable'\nimport QueryApi, {QueryOptions} from '../QueryApi'\nimport {Transport} from '../transport'\nimport {\n CommunicationObserver,\n FluxResultObserver,\n FluxTableMetaData,\n Row,\n AnnotatedCSVResponse,\n IterableResultExecutor,\n} from '../results'\nimport {ParameterizedQuery} from '../query/flux'\nimport {APIExecutor} from '../results/ObservableQuery'\n\nconst DEFAULT_dialect: any = {\n header: true,\n delimiter: ',',\n quoteChar: '\"',\n commentPrefix: '#',\n annotations: ['datatype', 'group', 'default'],\n}\n\nexport class QueryApiImpl implements QueryApi {\n private options: QueryOptions\n constructor(\n private transport: Transport,\n private createCSVResponse: (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ) => AnnotatedCSVResponse,\n org: string | QueryOptions\n ) {\n this.options = typeof org === 'string' ? {org} : org\n }\n\n with(options: Partial): QueryApi {\n return new QueryApiImpl(this.transport, this.createCSVResponse, {\n ...this.options,\n ...options,\n })\n }\n\n response(query: string | ParameterizedQuery): AnnotatedCSVResponse {\n const {org, type, gzip, headers} = this.options\n const path = `/api/v2/query?org=${encodeURIComponent(org)}`\n const body = JSON.stringify(\n this.decorateRequest({\n query: query.toString(),\n dialect: DEFAULT_dialect,\n type,\n })\n )\n const options = {\n method: 'POST',\n headers: {\n 'content-type': 'application/json; encoding=utf-8',\n 'accept-encoding': gzip ? 'gzip' : 'identity',\n ...headers,\n },\n }\n return this.createCSVResponse(\n (consumer) => this.transport.send(path, body, options, consumer),\n () => this.transport.iterate(path, body, options)\n )\n }\n\n iterateLines(query: string | ParameterizedQuery): AsyncIterable {\n return this.response(query).iterateLines()\n }\n iterateRows(query: string | ParameterizedQuery): AsyncIterable {\n return this.response(query).iterateRows()\n }\n lines(query: string | ParameterizedQuery): Observable {\n return this.response(query).lines()\n }\n\n rows(query: string | ParameterizedQuery): Observable {\n return this.response(query).rows()\n }\n\n queryLines(\n query: string | ParameterizedQuery,\n consumer: CommunicationObserver\n ): void {\n return this.response(query).consumeLines(consumer)\n }\n\n queryRows(\n query: string | ParameterizedQuery,\n consumer: FluxResultObserver\n ): void {\n return this.response(query).consumeRows(consumer)\n }\n\n collectRows(\n query: string | ParameterizedQuery,\n rowMapper?: (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined\n ): Promise> {\n return this.response(query).collectRows(rowMapper)\n }\n\n collectLines(query: string | ParameterizedQuery): Promise> {\n return this.response(query).collectLines()\n }\n\n queryRaw(query: string | ParameterizedQuery): Promise {\n const {org, type, gzip, headers} = this.options\n return this.transport.request(\n `/api/v2/query?org=${encodeURIComponent(org)}`,\n JSON.stringify(\n this.decorateRequest({\n query: query.toString(),\n dialect: DEFAULT_dialect,\n type,\n })\n ),\n {\n method: 'POST',\n headers: {\n accept: 'text/csv',\n 'accept-encoding': gzip ? 'gzip' : 'identity',\n 'content-type': 'application/json; encoding=utf-8',\n ...headers,\n },\n }\n )\n }\n\n private decorateRequest(request: any): any {\n if (typeof this.options.now === 'function') {\n request.now = this.options.now()\n }\n // https://docs.influxdata.com/influxdb/latest/api/#operation/PostQuery requires type\n request.type = this.options.type ?? 'flux'\n return request\n }\n}\n\nexport default QueryApiImpl\n","import {\n CommunicationObserver,\n FluxResultObserver,\n FluxTableMetaData,\n Row,\n linesToTables,\n ChunkCombiner,\n chunksToLines,\n chunksToLinesIterable,\n linesToRowsIterable,\n} from '../results'\nimport {Observable} from '../observable'\nimport {\n AnnotatedCSVResponse,\n IterableResultExecutor,\n} from './AnnotatedCSVResponse'\nimport ObservableQuery, {APIExecutor} from './ObservableQuery'\n\nexport function defaultRowMapping(\n values: string[],\n tableMeta: FluxTableMetaData\n): Record {\n return tableMeta.toObject(values)\n}\n\n/**\n * AnnotatedCsvResponseImpl is an implementation AnnotatedCsvResponse\n * that uses the supplied executor to supply a response data stream.\n */\nexport class AnnotatedCSVResponseImpl implements AnnotatedCSVResponse {\n constructor(\n private executor: APIExecutor,\n private iterableResultExecutor: IterableResultExecutor,\n private chunkCombiner: ChunkCombiner\n ) {}\n iterateLines(): AsyncIterable {\n return chunksToLinesIterable(this.iterableResultExecutor())\n }\n iterateRows(): AsyncIterable {\n return linesToRowsIterable(\n chunksToLinesIterable(this.iterableResultExecutor())\n )\n }\n lines(): Observable {\n return new ObservableQuery(this.executor, (observer) =>\n chunksToLines(observer, this.chunkCombiner)\n )\n }\n\n rows(): Observable {\n return new ObservableQuery(this.executor, (observer) => {\n return chunksToLines(\n linesToTables({\n next(values, tableMeta) {\n observer.next({values, tableMeta})\n },\n error(e) {\n observer.error(e)\n },\n complete() {\n observer.complete()\n },\n }),\n this.chunkCombiner\n )\n })\n }\n\n consumeLines(consumer: CommunicationObserver): void {\n this.executor(chunksToLines(consumer, this.chunkCombiner))\n }\n\n consumeRows(consumer: FluxResultObserver): void {\n this.executor(chunksToLines(linesToTables(consumer), this.chunkCombiner))\n }\n\n collectRows(\n rowMapper: (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined = defaultRowMapping as (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined\n ): Promise> {\n const retVal: Array = []\n return new Promise((resolve, reject) => {\n this.consumeRows({\n next(values: string[], tableMeta: FluxTableMetaData): void {\n const toAdd = rowMapper.call(this, values, tableMeta)\n if (toAdd !== undefined) {\n retVal.push(toAdd)\n }\n },\n error(error: Error): void {\n reject(error)\n },\n complete(): void {\n resolve(retVal)\n },\n })\n })\n }\n\n collectLines(): Promise> {\n const retVal: Array = []\n return new Promise((resolve, reject) => {\n this.consumeLines({\n next(line: string): void {\n retVal.push(line)\n },\n error(error: Error): void {\n reject(error)\n },\n complete(): void {\n resolve(retVal)\n },\n })\n })\n }\n}\n","import WriteApi from './WriteApi'\nimport {ClientOptions, WriteOptions, WritePrecisionType} from './options'\nimport WriteApiImpl from './impl/WriteApiImpl'\nimport {IllegalArgumentError} from './errors'\nimport {Transport} from './transport'\n// replaced by ./impl/browser/FetchTransport in browser builds\nimport TransportImpl from './impl/node/NodeHttpTransport'\nimport QueryApi, {QueryOptions} from './QueryApi'\nimport QueryApiImpl from './impl/QueryApiImpl'\nimport {\n AnnotatedCSVResponse,\n APIExecutor,\n IterableResultExecutor,\n} from './results'\nimport {AnnotatedCSVResponseImpl} from './results/AnnotatedCSVResponseImpl'\n\n/**\n * InfluxDB entry point that configures communication with InfluxDB server\n * and provide APIs to write and query data.\n */\nexport default class InfluxDB {\n private _options: ClientOptions\n readonly transport: Transport\n readonly processCSVResponse: (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ) => AnnotatedCSVResponse\n\n /**\n * Creates influxdb client options from an options object or url.\n * @param options - client options\n */\n constructor(options: ClientOptions | string) {\n if (typeof options === 'string') {\n this._options = {url: options}\n } else if (options !== null && typeof options === 'object') {\n this._options = options\n } else {\n throw new IllegalArgumentError('No url or configuration specified!')\n }\n const url = this._options.url\n if (typeof url !== 'string')\n throw new IllegalArgumentError('No url specified!')\n if (url.endsWith('/')) this._options.url = url.substring(0, url.length - 1)\n this.transport = this._options.transport ?? new TransportImpl(this._options)\n this.processCSVResponse = (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ): AnnotatedCSVResponse =>\n new AnnotatedCSVResponseImpl(\n executor,\n iterableResultExecutor,\n this.transport.chunkCombiner\n )\n }\n\n /**\n * Creates WriteApi for the supplied organization and bucket. BEWARE that returned instances must be closed\n * in order to flush the remaining data and close already scheduled retry executions.\n *\n * @remarks\n * Use {@link WriteOptions} to customize retry strategy options, data chunking\n * and flushing options. See {@link DEFAULT_WriteOptions} to see the defaults.\n *\n * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/write.mjs | write example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/writeAdvanced.mjs | writeAdvanced example},\n * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example}.\n *\n * @param org - Specifies the destination organization for writes. Takes either the ID or Name interchangeably.\n * @param bucket - The destination bucket for writes.\n * @param precision - Timestamp precision for line items.\n * @param writeOptions - Custom write options.\n * @returns WriteApi instance\n */\n getWriteApi(\n org: string,\n bucket: string,\n precision: WritePrecisionType = 'ns',\n writeOptions?: Partial\n ): WriteApi {\n return new WriteApiImpl(\n this.transport,\n org,\n bucket,\n precision,\n writeOptions ?? this._options.writeOptions\n )\n }\n\n /**\n * Creates QueryApi for the supplied organization .\n *\n * @remarks\n * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/query.ts | query.ts example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/queryWithParams.mjs | queryWithParams.mjs example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/rxjs-query.ts | rxjs-query.ts example},\n * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example},\n *\n * @param org - organization or query options\n * @returns QueryApi instance\n */\n getQueryApi(org: string | QueryOptions): QueryApi {\n return new QueryApiImpl(this.transport, this.processCSVResponse, org)\n }\n}\n"],"mappings":"ykBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,gBAAAE,EAAA,8BAAAC,GAAA,sCAAAC,GAAA,yBAAAC,GAAA,eAAAC,EAAA,cAAAC,EAAA,yBAAAC,EAAA,aAAAC,EAAA,iBAAAC,EAAA,QAAAC,EAAA,UAAAC,GAAA,yBAAAC,EAAA,mBAAAC,EAAA,qBAAAC,GAAA,kBAAAC,EAAA,0BAAAC,EAAA,kBAAAC,GAAA,uBAAAC,GAAA,0BAAAC,GAAA,4BAAAC,EAAA,8BAAAC,EAAA,gBAAAC,GAAA,4BAAAC,GAAA,WAAAC,EAAA,SAAAC,GAAA,aAAAC,GAAA,iBAAAC,GAAA,iBAAAC,GAAA,mBAAAC,GAAA,cAAAC,GAAA,gBAAAC,GAAA,eAAAC,GAAA,eAAAC,GAAA,kBAAAC,EAAA,0BAAAC,GAAA,wBAAAC,EAAA,kBAAAC,EAAA,uBAAAC,EAAA,kBAAAC,GAAA,oBAAAC,GAAA,4BAA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gC,KAChCC,EACU,CACV,OAAO,IAAIC,EACT,KAAK,UACLJ,EACAC,EACAC,EACAC,GAAA,KAAAA,EAAgB,KAAK,SAAS,YAChC,CACF,CAcA,YAAYH,EAAsC,CAChD,OAAO,IAAIK,GAAa,KAAK,UAAW,KAAK,mBAAoBL,CAAG,CACtE,CACF","names":["src_exports","__export","AbortError","DEFAULT_ConnectionOptions","DEFAULT_RetryDelayStrategyOptions","DEFAULT_WriteOptions","FLUX_VALUE","HttpError","IllegalArgumentError","InfluxDB","LineSplitter","Log","Point","RequestTimedOutError","UNKNOWN_COLUMN","canRetryHttpCall","chunksToLines","chunksToLinesIterable","consoleLogger","convertTimeToNanos","createFluxTableColumn","createFluxTableMetaData","createTextDecoderCombiner","currentTime","dateToProtocolTimestamp","escape","flux","fluxBool","fluxDateTime","fluxDuration","fluxExpression","fluxFloat","fluxInteger","fluxRegExp","fluxString","getRetryDelay","isStatusCodeRetriable","linesToRowsIterable","linesToTables","newFluxTableColumn","sanitizeFloat","sanitizeInteger","serializeDateTimeAsDate","serializeDateTimeAsNumber","serializeDateTimeAsString","setLogger","stringToLines","symbolObservable","toFluxValue","typeSerializers","useProcessHrtime","__toCommonJS","createTextDecoderCombiner","decoder","first","second","retVal","chunk","start","end","chunksToLines","target","chunkCombiner","chunks","createTextDecoderCombiner","previous","finished","quoted","paused","resumeChunks","bufferReceived","chunk","index","start","c","end","retVal","e","error","cancellable","x","chunksToLinesIterable","source","chunkCombiner","chunks","createTextDecoderCombiner","previous","quoted","chunk","index","start","c","end","LineSplitter","val","line","quoteCount","startIndex","values","count","i","c","start","end","identity","x","typeSerializers","FluxTableColumnImpl","row","_a","val","UNKNOWN_COLUMN","newFluxTableColumn","createFluxTableColumn","object","_b","retVal","retriableStatusCodes","isStatusCodeRetriable","statusCode","IllegalArgumentError","message","HttpError","statusMessage","body","retryAfter","contentType","e","RETRY_CODES","canRetryHttpCall","error","getRetryDelay","retryJitter","retVal","RequestTimedOutError","AbortError","serializeDateTimeAsDate","typeSerializers","x","serializeDateTimeAsNumber","serializeDateTimeAsString","FluxTableMetaDataImpl","columns","col","i","label","errorOnMissingColumn","IllegalArgumentError","UNKNOWN_COLUMN","row","acc","column","createFluxTableMetaData","linesToTables","consumer","splitter","LineSplitter","columns","expectMeta","firstColumnIndex","lastMeta","retVal","error","line","values","size","i","newFluxTableColumn","createFluxTableMetaData","linesToRowsIterable","source","splitter","LineSplitter","columns","expectMeta","firstColumnIndex","lastMeta","line","values","size","i","newFluxTableColumn","createFluxTableMetaData","stringToLines","source","target","quoted","start","index","c","end","symbolObservable","QuerySubscription","observer","executor","value","e","c","_a","noop","completeObserver","next","error","complete","ObservableQuery","decorator","observerOrNext","symbolObservable","DEFAULT_ConnectionOptions","DEFAULT_RetryDelayStrategyOptions","DEFAULT_WriteOptions","createEscaper","characters","replacements","value","retVal","from","i","found","createQuotedEscaper","escaper","escape","zeroPadding","useHrTime","useProcessHrtime","use","startHrMillis","startHrTime","lastMillis","stepsInMillis","nanos","hrTime","millis","micros","seconds","currentTime","dateToProtocolTimestamp","d","convertTimeToNanos","value","consoleLogger","message","error","provider","Log","setLogger","logger","previous","FLUX_VALUE","FluxParameter","fluxValue","isFluxParameterLike","value","sanitizeString","retVal","i","prepareRetVal","c","fluxString","sanitizeFloat","val","strVal","hasDot","fluxFloat","sanitizeInteger","negative","fluxInteger","sanitizeDateTime","fluxDateTime","fluxDuration","sanitizeRegExp","fluxRegExp","fluxBool","fluxExpression","toFluxValue","flux","strings","values","parts","partIndex","text","sanitized","Point","measurementName","name","value","val","strVal","code","escape","settings","fieldsLine","x","tagsLine","tags","time","convertTimeToNanos","line","RetryStrategyImpl","options","DEFAULT_RetryDelayStrategyOptions","error","failedAttempts","delay","getRetryDelay","nextDelay","i","createRetryDelayStrategy","findShrinkCandidate","first","parent","found","currentParent","RetryBuffer","maxLines","retryLines","onShrink","lines","retryCount","delay","expires","retryTime","origSize","newSize","Log","toAdd","current","toRetry","utf8Length","s","retVal","i","code","WriteBuffer","maxChunkRecords","maxBatchBytes","flushFn","scheduleSend","record","size","utf8Length","_e","lines","retVal","WriteApiImpl","transport","org","bucket","precision","writeOptions","DEFAULT_WriteOptions","currentTime","dateToProtocolTimestamp","scheduleNextSend","createRetryDelayStrategy","RetryBuffer","retryAttempts","expires","self","failedAttempts","error","onRetry","Log","resolve","reject","responseStatusCode","callbacks","_headers","statusCode","HttpError","message","records","i","point","line","points","withRetryBuffer","remaining","tags","value","import_url","http","https","import_buffer","import_buffer","nodeChunkCombiner","first","second","chunk","start","end","retVal","nodeChunkCombiner_default","import_zlib","completeCommunicationObserver","callbacks","state","retVal","data","error","headers","statusCode","CLIENT_LIB_VERSION","import_stream","zlibOptions","zlib","emptyBuffer","CancellableImpl","NodeHttpTransport","connectionOptions","nodeChunkCombiner_default","_a","_b","_c","_d","_e","_f","_g","_url","proxyUrl","token","transportOptions","nodeSupportedOptions","url","DEFAULT_ConnectionOptions","key","Log","CLIENT_LIB_VERSION","path","body","options","callbacks","cancellable","message","err","responseStarted","buffer","contentType","responseStatusCode","resolve","reject","headers","statusCode","data","responseType","e","terminationError","nestedReject","wrapReject","error","requestMessage","AbortError","response","req","RequestTimedOutError","res","chunk","sendOptions","bodyBuffer","contentEncoding","responseData","isJson","s","HttpError","listeners","completeCommunicationObserver","resume","NodeHttpTransport_default","DEFAULT_dialect","QueryApiImpl","transport","createCSVResponse","org","options","query","type","gzip","headers","path","body","consumer","rowMapper","request","_a","QueryApiImpl_default","defaultRowMapping","values","tableMeta","AnnotatedCSVResponseImpl","executor","iterableResultExecutor","chunkCombiner","chunksToLinesIterable","linesToRowsIterable","ObservableQuery","observer","chunksToLines","linesToTables","e","consumer","rowMapper","retVal","resolve","reject","toAdd","error","line","InfluxDB","options","_a","IllegalArgumentError","url","NodeHttpTransport_default","executor","iterableResultExecutor","AnnotatedCSVResponseImpl","org","bucket","precision","writeOptions","WriteApiImpl","QueryApiImpl_default"]} \ No newline at end of file diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/index.mjs b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.mjs new file mode 100644 index 0000000..cce65fd --- /dev/null +++ b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.mjs @@ -0,0 +1,6 @@ +function P(){let r=new TextDecoder("utf-8");return{concat(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n},copy(e,t,n){let i=new Uint8Array(n-t);return i.set(e.subarray(t,n)),i},toUtf8String(e,t,n){return r.decode(e.subarray(t,n))}}}function C(r,e){let t=e!=null?e:P(),n,i=!1,s=!1,a=!1,o;function u(l){let p,c=0;for(n?(p=l.length===0?0:n.length,l=t.concat(n,l)):p=0;p0&&l[p-1]===13?p-1:p;if(i)return;if(a=r.next(t.toUtf8String(l,c,D))===!1,c=p+1,a)break}}else d===34&&(s=!s);p++}if(c{a=!1,u(new Uint8Array(0))});return}f.error(new Error("Unable to pause, useResume is not configured!")),a=!1}o&&(o(),o=void 0)}let f={next(l){if(!i)try{return u(l),!a}catch(p){this.error(p)}return!0},error(l){i||(i=!0,r.error(l))},complete(){i||(n&&r.next(t.toUtf8String(n,0,n.length)),i=!0,r.complete())}};return r.useCancellable&&(f.useCancellable=l=>{r.useCancellable&&r.useCancellable({cancel(){l.cancel(),n=void 0,f.complete()},isCancelled(){return l.isCancelled()}})}),r.useResume&&(f.useResume=l=>{o=l}),f}async function*k(r,e){let t=e!=null?e:P(),n,i=!1;for await(let s of r){let a,o=0;for(n?(a=n.length,s=t.concat(n,s)):a=0;a0&&s[a-1]===13?a-1:a;yield t.toUtf8String(s,o,f),o=a+1}}else u===34&&(i=!i);a++}or,S={boolean:r=>r===""?null:r==="true",unsignedLong:r=>r===""?null:+r,long:r=>r===""?null:+r,double(r){switch(r){case"":return null;case"+Inf":return Number.POSITIVE_INFINITY;case"-Inf":return Number.NEGATIVE_INFINITY;default:return+r}},string:W,base64Binary:W,duration:r=>r===""?null:r,"dateTime:RFC3339":r=>r===""?null:r},F=class{get(e){var n;let t=e[this.index];return(t===""||t===void 0)&&this.defaultValue&&(t=this.defaultValue),((n=S[this.dataType])!=null?n:W)(t)}},oe=Object.freeze({label:"",dataType:"",group:!1,defaultValue:"",index:Number.MAX_SAFE_INTEGER,get:()=>{}});function L(){return new F}function st(r){var t,n;let e=new F;return e.label=String(r.label),e.dataType=r.dataType,e.group=Boolean(r.group),e.defaultValue=(t=r.defaultValue)!=null?t:"",e.index=(n=r.index)!=null?n:0,e}var Be=[404,408,425,429,500,502,503,504];function $e(r){return Be.includes(r)}var y=class extends Error{constructor(e){super(e),this.name="IllegalArgumentError",Object.setPrototypeOf(this,y.prototype)}},h=class extends Error{constructor(t,n,i,s,a,o){super();this.statusCode=t;this.statusMessage=n;this.body=i;this.contentType=a;if(Object.setPrototypeOf(this,h.prototype),o)this.message=o;else if(i){if(a!=null&&a.startsWith("application/json"))try{this.json=JSON.parse(i),this.message=this.json.message,this.code=this.json.code}catch(u){}this.message||(this.message=`${t} ${n} : ${i}`)}else this.message=`${t} ${n}`;this.name="HttpError",this.setRetryAfter(s)}setRetryAfter(t){typeof t=="string"?/^[0-9]+$/.test(t)?this._retryAfter=parseInt(t):this._retryAfter=0:this._retryAfter=0}canRetry(){return $e(this.statusCode)}retryAfter(){return this._retryAfter}},Me=["ECONNRESET","ENOTFOUND","ESOCKETTIMEDOUT","ETIMEDOUT","ECONNREFUSED","EHOSTUNREACH","EPIPE"];function at(r){if(r){if(typeof r.canRetry=="function")return!!r.canRetry();if(r.code&&Me.includes(r.code))return!0}else return!1;return!1}function ae(r,e){if(r){let t;return typeof r.retryAfter=="function"?r.retryAfter():(t=0,e&&e>0?t+Math.round(Math.random()*e):t)}else return 0}var x=class extends Error{constructor(){super(),Object.setPrototypeOf(this,x.prototype),this.name="RequestTimedOutError",this.message="Request timed out"}canRetry(){return!0}retryAfter(){return 0}},b=class extends Error{constructor(){super(),this.name="AbortError",Object.setPrototypeOf(this,b.prototype),this.message="Response aborted"}canRetry(){return!0}retryAfter(){return 0}};function ct(){S["dateTime:RFC3339"]=r=>r===""?null:new Date(Date.parse(r))}function dt(){S["dateTime:RFC3339"]=r=>r===""?null:Date.parse(r)}function mt(){S["dateTime:RFC3339"]=r=>r===""?null:r}var N=class{constructor(e){e.forEach((t,n)=>t.index=n),this.columns=e}column(e,t=!0){for(let n=0;n0&&r.charCodeAt(i-1)===13?i-1:i;e.next(r.substring(n,a)),n=i+1}}else s===34&&(t=!t);i++}ntypeof Symbol=="function"&&Symbol.observable||"@@observable")();var Q=class{constructor(e,t){this.isClosed=!1;try{t({next:n=>{e.next(n)},error:n=>{this.isClosed=!0,e.error(n)},complete:()=>{this.isClosed=!0,e.complete()},useCancellable:n=>{this.cancellable=n}})}catch(n){this.isClosed=!0,e.error(n)}}get closed(){return this.isClosed}unsubscribe(){var e;(e=this.cancellable)==null||e.cancel(),this.isClosed=!0}};function q(){}function ze(r){let{next:e,error:t,complete:n}=r;return{next:e?e.bind(r):q,error:t?t.bind(r):q,complete:n?n.bind(r):q}}var w=class{constructor(e,t){this.executor=e;this.decorator=t}subscribe(e,t,n){let i=ze(typeof e!="object"||e===null?{next:e,error:t,complete:n}:e);return new Q(this.decorator(i),this.executor)}[ue](){return this}};Symbol.observable;var fe={timeout:1e4},pe={retryJitter:200,minRetryDelay:5e3,maxRetryDelay:125e3,exponentialBase:5,randomRetry:!0},ce={batchSize:1e3,maxBatchBytes:5e7,flushInterval:6e4,writeFailed:function(){},writeSuccess:function(){},writeRetrySkipped:function(){},maxRetries:5,maxRetryTime:18e4,maxBufferLines:32e3,retryJitter:200,minRetryDelay:5e3,maxRetryDelay:125e3,exponentialBase:2,gzipThreshold:1e3,randomRetry:!0};function j(r,e){return function(t){let n="",i=0,s=0;for(;s=0&&(n+=t.substring(i,s),n+=e[a],i=s+1),s++}return i==0?t:(i'"'+t(n)+'"'}var T={measurement:j(`, +\r `,["\\,","\\ ","\\n","\\r","\\t"]),quoted:Ve('"\\',['\\"',"\\\\"]),tag:j(`, = +\r `,["\\,","\\ ","\\=","\\n","\\r","\\t"])};var _="000000000",Y=!1;function ke(r){return Y=r&&process&&typeof process.hrtime=="function"}ke(!0);var de,U,me=Date.now(),J=0;function X(){if(Y){let r=process.hrtime(),e=Date.now();U?(r[0]=r[0]-U[0],r[1]=r[1]-U[1],r[1]<0&&(r[0]-=1,r[1]+=1e9),e=de+r[0]*1e3+Math.floor(r[1]/1e6)):(U=r,de=e);let t=String(r[1]%1e6);return String(e)+_.substr(0,6-t.length)+t}else{let r=Date.now();r!==me?(me=r,J=0):J++;let e=String(J);return String(r)+_.substr(0,6-e.length)+e}}function he(){if(Y){let r=process.hrtime(),e=String(Math.trunc(r[1]/1e3)%1e3);return String(Date.now())+_.substr(0,3-e.length)+e}else return String(Date.now())+_.substr(0,3)}function ge(){return String(Date.now())}function ye(){return String(Math.floor(Date.now()/1e3))}var be={s:ye,ms:ge,us:he,ns:X,seconds:ye,millis:ge,micros:he,nanos:X},xe={s:r=>`${Math.floor(r.getTime()/1e3)}`,ms:r=>`${r.getTime()}`,us:r=>`${r.getTime()}000`,ns:r=>`${r.getTime()}000000`};function Re(r){return r===void 0?X():typeof r=="string"?r.length>0?r:void 0:r instanceof Date?`${r.getTime()}000000`:String(typeof r=="number"?Math.floor(r):r)}var We={error(r,e){console.error("ERROR: "+r,e||"")},warn(r,e){console.warn("WARN: "+r,e||"")}},B=We,g={error(r,e){B.error(r,e)},warn(r,e){B.warn(r,e)}};function fr(r){let e=B;return B=r,e}var $=Symbol("FLUX_VALUE"),m=class{constructor(e){this.fluxValue=e}toString(){return this.fluxValue}[$](){return this.fluxValue}};function Ne(r){return typeof r=="object"&&typeof r[$]=="function"}function v(r){if(r==null)return"";r=r.toString();let e,t=0;function n(){e===void 0&&(e=r.substring(0,t))}for(;t="0"&&i<="9"||i=="-")){if(i==="."){n=!0;continue}return`float(v: "${t}")`}return n?t:t+".0"}function dr(r){return new m(Te(r))}function Ce(r){let e=String(r),t=e.startsWith("-"),n=t?e.substring(1):e;if(n.length===0||n.length>19)throw new Error(`not a flux integer: ${e}`);for(let i of n)if(i<"0"||i>"9")throw new Error(`not a flux integer: ${e}`);if(n.length===19){if(t&&n>"9223372036854775808")throw new Error(`flux integer out of bounds: ${e}`);if(!t&&n>"9223372036854775807")throw new Error(`flux integer out of bounds: ${e}`)}return e}function mr(r){return new m(Ce(r))}function He(r){return`time(v: "${v(r)}")`}function hr(r){return new m(He(r))}function gr(r){return new m(`duration(v: "${v(r)}")`)}function Se(r){return r instanceof RegExp?r.toString():new RegExp(r).toString()}function yr(r){return new m(Se(r))}function br(r){return r==="true"||r==="false"?new m(r):new m((!!r).toString())}function we(r){return new m(String(r))}function G(r){if(r===void 0)return"";if(r===null)return"null";if(typeof r=="boolean")return r.toString();if(typeof r=="string")return`"${v(r)}"`;if(typeof r=="number")return Number.isSafeInteger(r)?Ce(r):Te(r);if(typeof r=="object"){if(typeof r[$]=="function")return r[$]();if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return Se(r);if(Array.isArray(r))return`[${r.map(G).join(",")}]`}else if(typeof r=="bigint")return`${r}.0`;return G(r.toString())}function xr(r,...e){if(r.length==1&&e.length===0)return we(r[0]);let t=new Array(r.length+e.length),n=0;for(let i=0;i=9223372036854776e3)throw new Error(`invalid integer value for field '${e}': '${t}'!`);return this.fields[e]=`${Math.floor(n)}i`,this}uintField(e,t){if(typeof t=="number"){if(isNaN(t)||t<0||t>Number.MAX_SAFE_INTEGER)throw new Error(`uint value for field '${e}' out of range: ${t}`);this.fields[e]=`${Math.floor(t)}u`}else{let n=String(t);for(let i=0;i57)throw new Error(`uint value has an unsupported character at pos ${i}: ${t}`)}if(n.length>20||n.length===20&&n.localeCompare("18446744073709551615")>0)throw new Error(`uint value for field '${e}' out of range: ${n}`);this.fields[e]=`${n}u`}return this}floatField(e,t){let n;if(typeof t=="number"?n=t:n=parseFloat(t),!isFinite(n))throw new Error(`invalid float value for field '${e}': ${t}`);return this.fields[e]=String(n),this}stringField(e,t){return t!=null&&(typeof t!="string"&&(t=String(t)),this.fields[e]=T.quoted(t)),this}timestamp(e){return this.time=e,this}toLineProtocol(e){if(!this.name)return;let t="";if(Object.keys(this.fields).sort().forEach(a=>{if(a){let o=this.fields[a];t.length>0&&(t+=","),t+=`${T.tag(a)}=${o}`}}),t.length===0)return;let n="",i=e&&e.defaultTags?{...e.defaultTags,...this.tags}:this.tags;Object.keys(i).sort().forEach(a=>{if(a){let o=i[a];o&&(n+=",",n+=`${T.tag(a)}=${T.tag(o)}`)}});let s=this.time;return e&&e.convertTime?s=e.convertTime(s):s=Re(s),`${T.measurement(this.name)}${n} ${t}${s!==void 0?" "+s:""}`}toString(){let e=this.toLineProtocol(void 0);return e||`invalid point: ${JSON.stringify(this,void 0)}`}};var K=class{constructor(e){this.options={...pe,...e},this.success()}nextDelay(e,t){let n=ae(e);if(n&&n>0)return n+Math.round(Math.random()*this.options.retryJitter);if(t&&t>0){if(this.options.randomRetry){let s=Math.max(this.options.minRetryDelay,1),a=s*this.options.exponentialBase;for(let o=1;o=this.options.maxRetryDelay){a=this.options.maxRetryDelay;break}return s+Math.round(Math.random()*(a-s)+Math.random()*this.options.retryJitter)}let i=Math.max(this.options.minRetryDelay,1);for(let s=1;s=this.options.maxRetryDelay){i=this.options.maxRetryDelay;break}return i+Math.round(Math.random()*this.options.retryJitter)}else this.currentDelay?this.currentDelay=Math.min(Math.max(this.currentDelay*this.options.exponentialBase,1)+Math.round(Math.random()*this.options.retryJitter),this.options.maxRetryDelay):this.currentDelay=this.options.minRetryDelay+Math.round(Math.random()*this.options.retryJitter);return this.currentDelay}success(){this.currentDelay=void 0}};function Oe(r){return new K(r)}function qe(r){let e,t=r,n=r;for(;n.next;)n.next.expires{}){this.maxLines=e;this.retryLines=t;this.onShrink=n;this.size=0;this.closed=!1;this._timeoutHandle=void 0}addLines(e,t,n,i){if(this.closed||!e.length)return;let s=Date.now()+n;if(ithis.maxLines){let f=this.size,l=f*.7;do{let[p,c]=qe(this.first);this.size-=p.lines.length,c?c.next=p.next:(this.first=p.next,this.first&&this.scheduleRetry(this.first.retryTime-Date.now())),p.next=void 0,this.onShrink(p)}while(this.first&&this.size+e.length>l);g.error(`RetryBuffer: ${f-this.size} oldest lines removed to keep buffer size under the limit of ${this.maxLines} lines.`)}let a={lines:e,retryCount:t,retryTime:s,expires:i},o=this.first,u;for(;;){if(!o||o.retryTime>s){a.next=o,u?u.next=a:(this.first=a,this.scheduleRetry(s-Date.now()));break}u=o,o=o.next}this.size+=e.length}removeLines(){if(this.first){let e=this.first;return this.first=this.first.next,e.next=void 0,this.size-=e.lines.length,e}}scheduleRetry(e){this._timeoutHandle&&clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{let t=this.removeLines();t?this.retryLines(t.lines,t.retryCount,t.expires).catch(()=>{}).finally(()=>{this.first&&this.scheduleRetry(this.first.retryTime-Date.now())}):this._timeoutHandle=void 0},Math.max(e,0))}async flush(){let e;for(;e=this.removeLines();)await this.retryLines(e.lines,e.retryCount,e.expires)}close(){return this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this.closed=!0,this.size}};function Z(r){let e=r.length;for(let t=0;t=128&&n<=2047?e++:n>=2048&&n<=65535?n>=55296&&n<=57343?e++:e+=2:e+=3)}return e}var ee=class{constructor(e,t,n,i){this.maxChunkRecords=e;this.maxBatchBytes=t;this.flushFn=n;this.scheduleSend=i;this.length=0;this.bytes=-1;this.lines=new Array(e)}add(e){let t=Z(e);this.length===0?this.scheduleSend():this.bytes+t+1>=this.maxBatchBytes&&this.flush().catch(n=>{}),this.lines[this.length]=e,this.length++,this.bytes+=t+1,(this.length>=this.maxChunkRecords||this.bytes>=this.maxBatchBytes)&&this.flush().catch(n=>{})}flush(){let e=this.reset();return e.length>0?this.flushFn(e):Promise.resolve()}reset(){let e=this.lines.slice(0,this.length);return this.length=0,this.bytes=-1,e}},A=class{constructor(e,t,n,i,s){this.transport=e;this.closed=!1;this._timeoutHandle=void 0;this.path=`/api/v2/write?org=${encodeURIComponent(t)}&bucket=${encodeURIComponent(n)}&precision=${i}`,s!=null&&s.consistency&&(this.path+=`&consistency=${encodeURIComponent(s.consistency)}`),this.writeOptions={...ce,...s},this.currentTime=be[i],this.dateToProtocolTimestamp=xe[i],this.writeOptions.defaultTags&&this.useDefaultTags(this.writeOptions.defaultTags),this.sendOptions={method:"POST",headers:{"content-type":"text/plain; charset=utf-8",...s==null?void 0:s.headers},gzipThreshold:this.writeOptions.gzipThreshold};let a=()=>{this.writeOptions.flushInterval>0&&(this._clearFlushTimeout(),this.closed||(this._timeoutHandle=setTimeout(()=>this.sendBatch(this.writeBuffer.reset(),this.writeOptions.maxRetries).catch(o=>{}),this.writeOptions.flushInterval)))};this.writeBuffer=new ee(this.writeOptions.batchSize,this.writeOptions.maxBatchBytes,o=>(this._clearFlushTimeout(),this.sendBatch(o,this.writeOptions.maxRetries)),a),this.sendBatch=this.sendBatch.bind(this),this.retryStrategy=Oe(this.writeOptions),this.retryBuffer=new O(this.writeOptions.maxBufferLines,this.sendBatch,this.writeOptions.writeRetrySkipped)}sendBatch(e,t,n=Date.now()+this.writeOptions.maxRetryTime){let i=this,s=i.writeOptions.maxRetries+1-t;if(!this.closed&&e.length>0){if(n<=Date.now()){let a=new Error("Max retry time exceeded."),o=i.writeOptions.writeFailed.call(i,a,e,s,n);return o||(g.error(`Write to InfluxDB failed (attempt: ${s}).`,a),Promise.reject(a))}return new Promise((a,o)=>{let u,f={responseStarted(l,p){u=p},error(l){let p=i.writeOptions.writeFailed.call(i,l,e,s,n);if(p){p.then(a,o);return}if(l instanceof h&&l.json&&typeof l.json.error=="string"&&l.json.error.includes("hinted handoff queue not empty")){g.warn("Write to InfluxDB returns: "+l.json.error),u=204,f.complete();return}if(!i.closed&&t>0&&(!(l instanceof h)||l.statusCode>=429)){g.warn(`Write to InfluxDB failed (attempt: ${s}).`,l),i.retryBuffer.addLines(e,t-1,i.retryStrategy.nextDelay(l,s),n),o(l);return}g.error("Write to InfluxDB failed.",l),o(l)},complete(){if(u==204||u==null)i.writeOptions.writeSuccess.call(i,e),i.retryStrategy.success(),a();else{let l=`204 HTTP response status code expected, but ${u} returned`,p=new h(u,l,void 0,"0");p.message=l,f.error(p)}}};this.transport.send(this.path,e.join(` +`),this.sendOptions,f)})}else return Promise.resolve()}_clearFlushTimeout(){this._timeoutHandle!==void 0&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0)}writeRecord(e){if(this.closed)throw new Error("writeApi: already closed!");this.writeBuffer.add(e)}writeRecords(e){if(this.closed)throw new Error("writeApi: already closed!");for(let t=0;t{let t=this.retryBuffer.close();t&&g.error(`Retry buffer closed with ${t} items that were not written to InfluxDB!`,null),this.closed=!0})}dispose(){return this._clearFlushTimeout(),this.closed=!0,this.retryBuffer.close()+this.writeBuffer.length}useDefaultTags(e){return this.defaultTags=e,this}convertTime(e){return e===void 0?this.currentTime():typeof e=="string"?e.length>0?e:void 0:e instanceof Date?this.dateToProtocolTimestamp(e):String(typeof e=="number"?Math.floor(e):e)}};import{parse as Pe}from"url";import*as Fe from"http";import*as Le from"https";import{Buffer as re}from"buffer";import{Buffer as Ae}from"buffer";var Qe={concat(r,e){return Ae.concat([r,e])},toUtf8String(r,e,t){return r.toString("utf-8",e,t)},copy(r,e,t){let n=Ae.allocUnsafe(t-e);return r.copy(n,0,e,t),n}},Ee=Qe;import M from"zlib";function te(r={}){let e=0,t={next:n=>{if(e===0&&r.next&&n!==null&&n!==void 0)return r.next(n)},error:n=>{e===0&&(e=1,r.error&&r.error(n))},complete:()=>{e===0&&(e=2,r.complete&&r.complete())},responseStarted:(n,i)=>{r.responseStarted&&r.responseStarted(n,i)}};return r.useCancellable&&(t.useCancellable=r.useCancellable.bind(r)),r.useResume&&(t.useResume=r.useResume.bind(r)),t}var De="1.33.1";import{pipeline as je}from"stream";var Je={flush:M.constants.Z_SYNC_FLUSH,finishFlush:M.constants.Z_SYNC_FLUSH},Xe=re.allocUnsafe(0),ne=class{constructor(){this.cancelled=!1}cancel(){this.cancelled=!0,this.resume&&(this.resume(),this.resume=void 0)}isCancelled(){return this.cancelled}},ie=class{constructor(e){this.chunkCombiner=Ee;var u,f,l,p,c,d,D;let{url:t,proxyUrl:n,token:i,transportOptions:s,...a}=e,o=Pe(n||t);if(this.token=i,this.defaultOptions={...fe,...a,...s,port:o.port,protocol:o.protocol,hostname:o.hostname},this.contextPath=n?t:(u=o.path)!=null?u:"",this.contextPath.endsWith("/")&&(this.contextPath=this.contextPath.substring(0,this.contextPath.length-1)),Object.keys(this.defaultOptions).forEach(se=>this.defaultOptions[se]===void 0&&delete this.defaultOptions[se]),this.contextPath.endsWith("/api/v2")&&(g.warn(`Please remove '/api/v2' context path from InfluxDB base url, using ${o.protocol}//${o.hostname}:${o.port} !`),this.contextPath=""),o.protocol==="http:")this.requestApi=(p=(l=(f=this.defaultOptions["follow-redirects"])==null?void 0:f.http)==null?void 0:l.request)!=null?p:Fe.request;else if(o.protocol==="https:")this.requestApi=(D=(d=(c=this.defaultOptions["follow-redirects"])==null?void 0:c.https)==null?void 0:d.request)!=null?D:Le.request;else throw new Error(`Unsupported protocol "${o.protocol} in URL: "${e.url}"`);this.headers={"User-Agent":`influxdb-client-js/${De}`,...e.headers},n&&(this.headers.Host=Pe(t).host)}send(e,t,n,i){let s=new ne;i&&i.useCancellable&&i.useCancellable(s),this.createRequestMessage(e,t,n,a=>{this._request(a,s,i)},a=>(i==null?void 0:i.error)&&i.error(a))}request(e,t,n,i){t?typeof t!="string"&&(t=JSON.stringify(t)):t="";let s=Xe,a,o;return new Promise((u,f)=>{this.send(e,t,n,{responseStarted(l,p){i&&i(l,p),a=String(l["content-type"]),o=p},next:l=>{s=re.concat([s,l])},complete:()=>{var p,c;let l=(c=(p=n.headers)==null?void 0:p.accept)!=null?c:a;try{o===204&&u(void 0),l.includes("json")?s.length?u(JSON.parse(s.toString("utf8"))):u(void 0):l.includes("text")||l.startsWith("application/csv")?u(s.toString("utf8")):u(s)}catch(d){f(d)}},error:l=>{f(l)}})})}async*iterate(e,t,n){var l;let i,s;function a(p){i=p,s(p)}let o=await new Promise((p,c)=>{s=c,this.createRequestMessage(e,t,n,p,a)});(l=o.signal)!=null&&l.addEventListener&&o.signal.addEventListener("abort",()=>{a(new b)});let u=await new Promise((p,c)=>{s=c;let d=this.requestApi(o,p);d.on("timeout",()=>a(new x)),d.on("error",a),d.write(o.body),d.end()}),f=await new Promise((p,c)=>{s=c,this._prepareResponse(u,p,a)});for await(let p of f){if(i)throw i;yield p}}createRequestMessage(e,t,n,i,s){let a=re.from(t,"utf-8"),o={"content-type":"application/json; charset=utf-8",...this.headers};this.token&&(o.authorization="Token "+this.token);let u={...this.defaultOptions,path:this.contextPath+e,method:n.method,headers:{...o,...n.headers}};if(n.signal&&(u.signal=n.signal),n.gzipThreshold!==void 0&&n.gzipThreshold{if(f)return s(f);u.headers["content-encoding"]="gzip",u.body=l,i(u)});return}u.body=a,u.headers["content-length"]=u.body.length,i(u)}_prepareResponse(e,t,n){var o;e.on("aborted",()=>{n(new b)}),e.on("error",n);let i=(o=e.statusCode)!=null?o:600,s=e.headers["content-encoding"],a;if(s==="gzip"?(a=M.createGunzip(Je),a=je(e,a,u=>u&&n(u))):a=e,i>=300){let u="",f=String(e.headers["content-type"]).startsWith("application/json");a.on("data",l=>{u+=l.toString(),!f&&u.length>1e3&&(u=u.slice(0,1e3),e.resume())}),a.on("end",()=>{u===""&&!!e.headers["x-influxdb-error"]&&(u=e.headers["x-influxdb-error"].toString()),n(new h(i,e.statusMessage,u,e.headers["retry-after"],e.headers["content-type"]))})}else t(a)}_request(e,t,n){var a;let i=te(n);if(t.isCancelled()){i.complete();return}(a=e.signal)!=null&&a.addEventListener&&e.signal.addEventListener("abort",()=>{i.error(new b)});let s=this.requestApi(e,o=>{if(t.isCancelled()){o.resume(),i.complete();return}i.responseStarted(o.headers,o.statusCode),this._prepareResponse(o,u=>{u.on("data",f=>{if(t.isCancelled())o.resume();else if(i.next(f)===!1){if(!i.useResume){i.error(new Error("Unable to pause, useResume is not configured!")),o.resume();return}o.pause();let l=()=>{o.resume()};t.resume=l,i.useResume(l)}}),u.on("end",i.complete)},i.error)});typeof s.setTimeout=="function"&&e.timeout&&s.setTimeout(e.timeout),s.on("timeout",()=>{i.error(new x)}),s.on("error",o=>{i.error(o)}),e.body&&s.write(e.body),s.end()}},Ie=ie;var Ue={header:!0,delimiter:",",quoteChar:'"',commentPrefix:"#",annotations:["datatype","group","default"]},E=class{constructor(e,t,n){this.transport=e;this.createCSVResponse=t;this.options=typeof n=="string"?{org:n}:n}with(e){return new E(this.transport,this.createCSVResponse,{...this.options,...e})}response(e){let{org:t,type:n,gzip:i,headers:s}=this.options,a=`/api/v2/query?org=${encodeURIComponent(t)}`,o=JSON.stringify(this.decorateRequest({query:e.toString(),dialect:Ue,type:n})),u={method:"POST",headers:{"content-type":"application/json; encoding=utf-8","accept-encoding":i?"gzip":"identity",...s}};return this.createCSVResponse(f=>this.transport.send(a,o,u,f),()=>this.transport.iterate(a,o,u))}iterateLines(e){return this.response(e).iterateLines()}iterateRows(e){return this.response(e).iterateRows()}lines(e){return this.response(e).lines()}rows(e){return this.response(e).rows()}queryLines(e,t){return this.response(e).consumeLines(t)}queryRows(e,t){return this.response(e).consumeRows(t)}collectRows(e,t){return this.response(e).collectRows(t)}collectLines(e){return this.response(e).collectLines()}queryRaw(e){let{org:t,type:n,gzip:i,headers:s}=this.options;return this.transport.request(`/api/v2/query?org=${encodeURIComponent(t)}`,JSON.stringify(this.decorateRequest({query:e.toString(),dialect:Ue,type:n})),{method:"POST",headers:{accept:"text/csv","accept-encoding":i?"gzip":"identity","content-type":"application/json; encoding=utf-8",...s}})}decorateRequest(e){var t;return typeof this.options.now=="function"&&(e.now=this.options.now()),e.type=(t=this.options.type)!=null?t:"flux",e}},_e=E;function Ye(r,e){return e.toObject(r)}var z=class{constructor(e,t,n){this.executor=e;this.iterableResultExecutor=t;this.chunkCombiner=n}iterateLines(){return k(this.iterableResultExecutor())}iterateRows(){return le(k(this.iterableResultExecutor()))}lines(){return new w(this.executor,e=>C(e,this.chunkCombiner))}rows(){return new w(this.executor,e=>C(H({next(t,n){e.next({values:t,tableMeta:n})},error(t){e.error(t)},complete(){e.complete()}}),this.chunkCombiner))}consumeLines(e){this.executor(C(e,this.chunkCombiner))}consumeRows(e){this.executor(C(H(e),this.chunkCombiner))}collectRows(e=Ye){let t=[];return new Promise((n,i)=>{this.consumeRows({next(s,a){let o=e.call(this,s,a);o!==void 0&&t.push(o)},error(s){i(s)},complete(){n(t)}})})}collectLines(){let e=[];return new Promise((t,n)=>{this.consumeLines({next(i){e.push(i)},error(i){n(i)},complete(){t(e)}})})}};var V=class{constructor(e){var n;if(typeof e=="string")this._options={url:e};else if(e!==null&&typeof e=="object")this._options=e;else throw new y("No url or configuration specified!");let t=this._options.url;if(typeof t!="string")throw new y("No url specified!");t.endsWith("/")&&(this._options.url=t.substring(0,t.length-1)),this.transport=(n=this._options.transport)!=null?n:new Ie(this._options),this.processCSVResponse=(i,s)=>new z(i,s,this.transport.chunkCombiner)}getWriteApi(e,t,n="ns",i){return new A(this.transport,e,t,n,i!=null?i:this._options.writeOptions)}getQueryApi(e){return new _e(this.transport,this.processCSVResponse,e)}};export{b as AbortError,fe as DEFAULT_ConnectionOptions,pe as DEFAULT_RetryDelayStrategyOptions,ce as DEFAULT_WriteOptions,$ as FLUX_VALUE,h as HttpError,y as IllegalArgumentError,V as InfluxDB,R as LineSplitter,g as Log,ve as Point,x as RequestTimedOutError,oe as UNKNOWN_COLUMN,at as canRetryHttpCall,C as chunksToLines,k as chunksToLinesIterable,We as consoleLogger,Re as convertTimeToNanos,st as createFluxTableColumn,I as createFluxTableMetaData,P as createTextDecoderCombiner,be as currentTime,xe as dateToProtocolTimestamp,T as escape,xr as flux,br as fluxBool,hr as fluxDateTime,gr as fluxDuration,we as fluxExpression,dr as fluxFloat,mr as fluxInteger,yr as fluxRegExp,cr as fluxString,ae as getRetryDelay,$e as isStatusCodeRetriable,le as linesToRowsIterable,H as linesToTables,L as newFluxTableColumn,Te as sanitizeFloat,Ce as sanitizeInteger,ct as serializeDateTimeAsDate,dt as serializeDateTimeAsNumber,mt as serializeDateTimeAsString,fr as setLogger,Ft as stringToLines,ue as symbolObservable,G as toFluxValue,S as typeSerializers,ke as useProcessHrtime}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/index.mjs.gz b/software/flow/node_modules/@influxdata/influxdb-client/dist/index.mjs.gz new file mode 100644 index 0000000000000000000000000000000000000000..9178edce2a26743b90f840a88b783948b060913f GIT binary patch literal 10404 zcmV;VC|lPbiwFP!000021GRl?d)qd$@aMC?Lgr=_vVs*kc5YN?9mla7cN077OVh6F z6Vno8v!O|qAQL+>|NA>LxDcdhCGGCp=cz-2z+f;K%nbu*S|sBIEj+{`Bs*Nw=VC;Jh{xT zdbxVgO*=_naA@f<`H(YR6-r7rPG`3WmL(E!)C8QY<_1(GLG?v(5zxWd#S4rC9p{lpU%#P z(bSy)fVF`)hsPBmKfVrTn}co_YOJoE;pg=cJoz)M9(i)i_#6gVKYy-d*Y>*r!GzgeB1f@$oKM6jk z(WEl~aENc#F9bj2qPPaSS}(5a1)FmsWZ^dEdH|E6C%c^Xd6pqTq0SCHIVVYY5%W%- zc4i>}WE}&w6Nyfe<{cpJG`cJ@K3Q>qGq9U7g|VbCk*Pw^E0K=VU{2(TC3Pb&&u%r# z;Iy)pu!MOUU%4}Ho?k^mp)>PJS!-obGFgNm?(SS*lL5>6y39l7zMer}+?5rQZnu3- z5;kC(N06T-psF>n>dD>oCGLDoFDL{0`jMGgoLc>t zEE1|EpSWga#r;}wS;FiwYpOMF@{Q0+gBa>e%TU}V>h$wMc%P1|hCBsA1L`Jo(}9 zHsbN5)0joUQZ_|43wvv7Efsn#!5AWM7{Xdg4F=Uh!j@uTA(g-{Zfj3@Py) zf{?Y+Nc7e`-&F{NUVEj;=;Nrgdd_j_Rg(s&YD`9s<42_0NTmwNl&Djw_;I}$Mx3ky z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@{9 zIi%i{H$&04uCt%w7C|S?i~%0XU$U9;aWswW+>RPB3`g5%z*lU17va~y>7?nKo(~7N?suFf*U3pSeL~_ISM;1xVc=Xq&2ZuV%1`jlSY@qsIp8<5jyKR91>g zsdN(ISig8hS^iD?RRy;cijiL*LoGcNd-xZsIqIPX_9Jh#ix&qaFOb6nl36~#pnZPx zBN1#$`?0TgcDGL69)H|UlZ2BpF!8L~_v(bBPC?W4#)R6hwMPd`7PvPc}6PzPln(@ezljTHNFidx0Y(HrXn(N(aw zSOiO{ISa=GM1)C{M_=V-7Hqp#rUx*lxfC3FkD*wTXiMM|o80$R-jTwt@B6L>Kh5O# zT(Q)ytWO^`R~8a4y7TeCTocWH#L_(7)ps+pBPsxieWbg~fTgK%AuuBjg~l7YNVOdP O?f(JCKm,\n chunkCombiner?: ChunkCombiner\n): CommunicationObserver {\n const chunks = chunkCombiner ?? createTextDecoderCombiner()\n let previous: Uint8Array | undefined\n let finished = false\n let quoted = false\n let paused = false\n let resumeChunks: (() => void) | undefined\n\n function bufferReceived(chunk: Uint8Array): void {\n let index: number\n let start = 0\n if (previous) {\n // inspect the whole remaining data upon empty chunk\n // empty chunk signalizes to restart of receiving\n index = chunk.length === 0 ? 0 : (previous as Uint8Array).length\n chunk = chunks.concat(previous, chunk)\n } else {\n index = 0\n }\n while (index < chunk.length) {\n const c = chunk[index]\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n // do not emmit more lines if the processing is already finished\n if (finished) {\n return\n }\n paused = target.next(chunks.toUtf8String(chunk, start, end)) === false\n start = index + 1\n if (paused) {\n break\n }\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < chunk.length) {\n previous = chunks.copy(chunk, start, chunk.length)\n } else {\n previous = undefined\n }\n if (paused) {\n if (target.useResume) {\n target.useResume(() => {\n paused = false\n bufferReceived(new Uint8Array(0))\n })\n return\n }\n retVal.error(new Error('Unable to pause, useResume is not configured!'))\n paused = false // consume remaining data\n }\n if (resumeChunks) {\n resumeChunks()\n resumeChunks = undefined\n }\n }\n\n const retVal: CommunicationObserver = {\n next(chunk: Uint8Array): boolean {\n if (!finished) {\n try {\n bufferReceived(chunk)\n return !paused\n } catch (e) {\n this.error(e as Error)\n }\n }\n return true\n },\n error(error: Error): void {\n if (!finished) {\n finished = true\n target.error(error)\n }\n },\n complete(): void {\n if (!finished) {\n if (previous) {\n target.next(chunks.toUtf8String(previous, 0, previous.length))\n }\n finished = true\n target.complete()\n }\n },\n }\n if (target.useCancellable) {\n retVal.useCancellable = (cancellable: Cancellable) => {\n target.useCancellable &&\n target.useCancellable({\n cancel(): void {\n cancellable.cancel()\n previous = undefined // do not emit more lines\n retVal.complete()\n },\n isCancelled(): boolean {\n return cancellable.isCancelled()\n },\n })\n }\n }\n if (target.useResume) {\n retVal.useResume = (x: () => void) => {\n resumeChunks = x\n }\n }\n\n return retVal\n}\n","import {ChunkCombiner, createTextDecoderCombiner} from './chunkCombiner'\n\n/**\n * ChunksToLinesIterable is a transformation that accepts\n * an iterable of Uint8Array instances and returns iterable of lines.\n * @param source - iterable of transport buffers\n * @param chunkCombiner - chunk combiner\n * @returns iterable of lines\n */\nexport async function* chunksToLinesIterable(\n source: AsyncIterable,\n chunkCombiner?: ChunkCombiner\n): AsyncIterableIterator {\n const chunks = chunkCombiner ?? createTextDecoderCombiner()\n let previous: Uint8Array | undefined\n let quoted = false\n\n for await (let chunk of source) {\n let index: number\n let start = 0\n if (previous) {\n index = previous.length\n chunk = chunks.concat(previous, chunk)\n } else {\n index = 0\n }\n while (index < chunk.length) {\n const c = chunk[index]\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n yield chunks.toUtf8String(chunk, start, end)\n start = index + 1\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < chunk.length) {\n previous = chunks.copy(chunk, start, chunk.length)\n } else {\n previous = undefined\n }\n }\n if (previous) {\n yield chunks.toUtf8String(previous, 0, previous.length)\n }\n}\n","/**\n * Optimized tokenizer of a single CSV line.\n */\nexport class LineSplitter {\n /** returned value when reused */\n reusedValues: string[]\n /** last length of elements in */\n lastSplitLength: number\n private _reuse = false\n\n /**\n * Reuse returned array between consecutive calls.\n */\n get reuse(): boolean {\n return this._reuse\n }\n set reuse(val: boolean) {\n if (val && !this.reusedValues) {\n this.reusedValues = new Array(10)\n }\n this._reuse = val\n }\n\n /**\n * Sets the reuse flag and returns this.\n */\n withReuse(): LineSplitter {\n this.reuse = true\n return this\n }\n\n /**\n * Splits the supplied line to elements that are separated by\n * comma with values possibly escaped within double quotes (\"value\")\n * @param line - line\n * @returns array of splitted parts\n */\n splitLine(line: string | undefined | null): string[] {\n if (line === null || line === undefined) {\n this.lastSplitLength = 0\n return []\n }\n let quoteCount = 0\n let startIndex = 0\n const values = this._reuse ? this.reusedValues : []\n let count = 0\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (c === ',') {\n if (quoteCount % 2 === 0) {\n const val = this.getValue(line, startIndex, i, quoteCount)\n if (this._reuse) {\n values[count++] = val\n } else {\n values.push(val)\n }\n startIndex = i + 1\n quoteCount = 0\n }\n } else if (c === '\"') {\n quoteCount++\n }\n }\n const val = this.getValue(line, startIndex, line.length, quoteCount)\n if (this._reuse) {\n values[count] = val\n this.lastSplitLength = count + 1\n } else {\n values.push(val)\n this.lastSplitLength = values.length\n }\n\n return values\n }\n\n private getValue(\n line: string,\n start: number,\n end: number,\n quoteCount: number\n ): string {\n if (start === line.length) {\n return ''\n } else if (quoteCount === 0) {\n return line.substring(start, end)\n } else if (quoteCount === 2) {\n return line.substring(start + 1, end - 1)\n } else {\n // quoteCount >= 4\n return line.substring(start + 1, end - 1).replace(/\"\"/gi, '\"')\n }\n }\n}\n","/**\n * Type of query result column, see {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport type ColumnType =\n | 'boolean'\n | 'unsignedLong'\n | 'long'\n | 'double'\n | 'string'\n | 'base64Binary'\n | 'dateTime:RFC3339'\n | 'duration'\n | string\n\n/**\n * FluxTableColumn describes {@link http://bit.ly/flux-spec#table | flux table} column.\n */\nexport interface FluxTableColumn {\n /**\n * Label (e.g., \"_start\", \"_stop\", \"_time\").\n */\n label: string\n\n /**\n * The data type of column (e.g., \"string\", \"long\", \"dateTime:RFC3339\").\n */\n dataType: ColumnType\n\n /**\n * Boolean flag indicating if the column is a part of the table's group key.\n */\n group: boolean\n\n /**\n * Default value to be used for rows whose string value is an empty string.\n */\n defaultValue: string\n\n /**\n * Index of this column in a row array.\n */\n index: number\n\n /**\n * Get returns a JavaScript object of this column in the supplied result row, using default deserializers.\n * @param row - a data row\n * @returns column value\n */\n get: (row: string[]) => any\n}\n\nconst identity = (x: string): any => x\n\n/**\n * A dictionary of serializers of particular types returned by a flux query.\n * See {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport const typeSerializers: Record any> = {\n boolean: (x: string): any => (x === '' ? null : x === 'true'),\n unsignedLong: (x: string): any => (x === '' ? null : +x),\n long: (x: string): any => (x === '' ? null : +x),\n double(x: string): any {\n switch (x) {\n case '':\n return null\n case '+Inf':\n return Number.POSITIVE_INFINITY\n case '-Inf':\n return Number.NEGATIVE_INFINITY\n default:\n return +x\n }\n },\n string: identity,\n base64Binary: identity,\n duration: (x: string): any => (x === '' ? null : x),\n 'dateTime:RFC3339': (x: string): any => (x === '' ? null : x),\n}\n\n/**\n * FluxTableColumn implementation.\n */\nclass FluxTableColumnImpl implements FluxTableColumn {\n label: string\n dataType: ColumnType\n group: boolean\n defaultValue: string\n index: number\n public get(row: string[]): any {\n let val = row[this.index]\n if ((val === '' || val === undefined) && this.defaultValue) {\n val = this.defaultValue\n }\n return (typeSerializers[this.dataType] ?? identity)(val)\n }\n}\nexport const UNKNOWN_COLUMN: FluxTableColumn = Object.freeze({\n label: '',\n dataType: '',\n group: false,\n defaultValue: '',\n index: Number.MAX_SAFE_INTEGER,\n get: () => undefined,\n})\n\n/**\n * Creates a new flux table column.\n * @returns column instance\n */\nexport function newFluxTableColumn(): FluxTableColumn {\n return new FluxTableColumnImpl()\n}\n\n/**\n * Creates a flux table column from a partial FluxTableColumn.\n * @param object - source object\n * @returns column instance\n */\nexport function createFluxTableColumn(\n object: Partial\n): FluxTableColumn {\n const retVal = new FluxTableColumnImpl()\n retVal.label = String(object.label)\n retVal.dataType = object.dataType as ColumnType\n retVal.group = Boolean(object.group)\n retVal.defaultValue = object.defaultValue ?? ''\n retVal.index = object.index ?? 0\n return retVal\n}\n","/**\n * Strategy for calculating retry delays.\n */\nexport interface RetryDelayStrategy {\n /**\n * Returns delay for a next retry\n * @param error - reason for retrying\n * @param failedAttempts - a count of already failed attempts, 1 being the first\n * @returns milliseconds to wait before retrying\n */\n nextDelay(error?: Error, failedAttempts?: number): number\n /** Implementation should reset its state, this is mandatory to call upon success. */\n success(): void\n}\n\n/**\n * Interface for errors to inform that an associated operation can be retried.\n */\nexport interface RetriableDecision {\n /**\n * Informs whether this can be retried.\n */\n canRetry(): boolean\n /**\n * Get the delay in milliseconds to retry the action.\n * @returns 0 to let the implementation decide, miliseconds delay otherwise\n */\n retryAfter(): number\n}\n\nconst retriableStatusCodes = [404, 408, 425, 429, 500, 502, 503, 504]\n/** isStatusCodeRetriable checks whether the supplied HTTP status code is retriable. */\nexport function isStatusCodeRetriable(statusCode: number): boolean {\n return retriableStatusCodes.includes(statusCode)\n}\n\n/** IllegalArgumentError is thrown when illegal argument is supplied. */\nexport class IllegalArgumentError extends Error {\n /* istanbul ignore next */\n constructor(message: string) {\n super(message)\n this.name = 'IllegalArgumentError'\n Object.setPrototypeOf(this, IllegalArgumentError.prototype)\n }\n}\n\n/**\n * A general HTTP error.\n */\nexport class HttpError extends Error implements RetriableDecision {\n private _retryAfter: number\n /** application error code, when available */\n public code: string | undefined\n /** json error response */\n public json: any\n\n /* istanbul ignore next because of super() not being covered*/\n constructor(\n readonly statusCode: number,\n readonly statusMessage: string | undefined,\n readonly body?: string,\n retryAfter?: string | undefined | null,\n readonly contentType?: string | undefined | null,\n message?: string\n ) {\n super()\n Object.setPrototypeOf(this, HttpError.prototype)\n if (message) {\n this.message = message\n } else if (body) {\n if (contentType?.startsWith('application/json')) {\n try {\n this.json = JSON.parse(body)\n this.message = this.json.message\n this.code = this.json.code\n } catch (e) {\n // silently ignore, body string is still available\n }\n }\n if (!this.message) {\n this.message = `${statusCode} ${statusMessage} : ${body}`\n }\n } else {\n this.message = `${statusCode} ${statusMessage}`\n }\n this.name = 'HttpError'\n this.setRetryAfter(retryAfter)\n }\n\n private setRetryAfter(retryAfter?: string | undefined | null): void {\n if (typeof retryAfter === 'string') {\n // try to parse the supplied number as milliseconds\n if (/^[0-9]+$/.test(retryAfter)) {\n this._retryAfter = parseInt(retryAfter)\n } else {\n this._retryAfter = 0\n }\n } else {\n this._retryAfter = 0\n }\n }\n\n canRetry(): boolean {\n return isStatusCodeRetriable(this.statusCode)\n }\n retryAfter(): number {\n return this._retryAfter\n }\n}\n\n//see https://nodejs.org/api/errors.html\nconst RETRY_CODES = [\n 'ECONNRESET',\n 'ENOTFOUND',\n 'ESOCKETTIMEDOUT',\n 'ETIMEDOUT',\n 'ECONNREFUSED',\n 'EHOSTUNREACH',\n 'EPIPE',\n]\n\n/**\n * Tests the error in order to know if an HTTP call can be retried.\n * @param error - error to test\n * @returns true for a retriable error\n */\nexport function canRetryHttpCall(error: any): boolean {\n if (!error) {\n return false\n } else if (typeof (error as any).canRetry === 'function') {\n return !!((error as any).canRetry as () => boolean)()\n } else if ((error as any).code && RETRY_CODES.includes((error as any).code)) {\n return true\n }\n return false\n}\n\n/**\n * Gets retry delay from the supplied error, possibly using random number up to retryJitter.\n */\nexport function getRetryDelay(error?: Error, retryJitter?: number): number {\n if (!error) {\n return 0\n } else {\n let retVal\n if (typeof (error as any).retryAfter === 'function') {\n return ((error as any).retryAfter as () => number)()\n } else {\n retVal = 0\n }\n if (retryJitter && retryJitter > 0) {\n return retVal + Math.round(Math.random() * retryJitter)\n } else {\n return retVal\n }\n }\n}\n\n/** RequestTimedOutError indicates request timeout in the communication with the server */\nexport class RequestTimedOutError extends Error implements RetriableDecision {\n /* istanbul ignore next because of super() not being covered */\n constructor() {\n super()\n Object.setPrototypeOf(this, RequestTimedOutError.prototype)\n this.name = 'RequestTimedOutError'\n this.message = 'Request timed out'\n }\n canRetry(): boolean {\n return true\n }\n retryAfter(): number {\n return 0\n }\n}\n\n/** AbortError indicates that the communication with the server was aborted */\nexport class AbortError extends Error implements RetriableDecision {\n /* istanbul ignore next because of super() not being covered */\n constructor() {\n super()\n this.name = 'AbortError'\n Object.setPrototypeOf(this, AbortError.prototype)\n this.message = 'Response aborted'\n }\n canRetry(): boolean {\n return true\n }\n retryAfter(): number {\n return 0\n }\n}\n","import {\n FluxTableColumn,\n UNKNOWN_COLUMN,\n typeSerializers,\n} from './FluxTableColumn'\nimport {IllegalArgumentError} from '../errors'\n\n/**\n * serializeDateTimeAsDate changes type serializers to return JavaScript Date instances\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsDate(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : new Date(Date.parse(x))\n}\n/**\n * serializeDateTimeAsNumber changes type serializers to return milliseconds since epoch\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsNumber(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : Date.parse(x)\n}\n/**\n * serializeDateTimeAsString changes type serializers to return string values\n * for `dateTime:RFC3339` query result data type. Empty value is converted to null.\n */\nexport function serializeDateTimeAsString(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : x\n}\n\n/**\n * Represents metadata of a {@link http://bit.ly/flux-spec#table | flux table}.\n */\nexport interface FluxTableMetaData {\n /**\n * Table columns.\n */\n columns: Array\n\n /**\n * Gets columns by name\n * @param label - column label\n * @param errorOnMissingColumn - throw error on missing column (by default), return UNKNOWN_COLUMN when false\n * @returns table column\n * @throws IllegalArgumentError if column is not found\n **/\n column(label: string, errorOnMissingColumn?: boolean): FluxTableColumn\n\n /**\n * Creates an object out of the supplied row with the help of column descriptors.\n * @param row - a row with data for each column\n */\n toObject(row: string[]): {[key: string]: any}\n\n /**\n * Gets column values out of the supplied row.\n * @param row - a row with data for each column\n * @param column - column name\n * @returns column value, undefined for unknown column\n */\n get(row: string[], column: string): any\n}\n\n/**\n * FluxTableMetaData Implementation.\n */\nclass FluxTableMetaDataImpl implements FluxTableMetaData {\n columns: Array\n constructor(columns: FluxTableColumn[]) {\n columns.forEach((col, i) => (col.index = i))\n this.columns = columns\n }\n column(label: string, errorOnMissingColumn = true): FluxTableColumn {\n for (let i = 0; i < this.columns.length; i++) {\n const col = this.columns[i]\n if (col.label === label) return col\n }\n if (errorOnMissingColumn) {\n throw new IllegalArgumentError(`Column ${label} not found!`)\n }\n return UNKNOWN_COLUMN\n }\n toObject(row: string[]): {[key: string]: any} {\n const acc: any = {}\n for (let i = 0; i < this.columns.length && i < row.length; i++) {\n const column = this.columns[i]\n acc[column.label] = column.get(row)\n }\n return acc\n }\n get(row: string[], column: string): any {\n return this.column(column, false).get(row)\n }\n}\n\n/**\n * Created FluxTableMetaData from the columns supplied.\n * @param columns - columns\n * @returns - instance\n */\nexport function createFluxTableMetaData(\n columns: FluxTableColumn[]\n): FluxTableMetaData {\n return new FluxTableMetaDataImpl(columns)\n}\n\n/** Wraps values and associated metadata of a query result row */\nexport interface Row {\n values: string[]\n tableMeta: FluxTableMetaData\n}\n","import {CommunicationObserver} from './CommunicationObserver'\nimport {LineSplitter} from './LineSplitter'\nimport {FluxResultObserver} from './FluxResultObserver'\nimport {\n FluxTableColumn,\n ColumnType,\n newFluxTableColumn,\n} from './FluxTableColumn'\nimport {FluxTableMetaData, createFluxTableMetaData} from './FluxTableMetaData'\n\n/**\n * LinesToTables creates a transformation that accepts (flux) annotated CSV lines\n * and emits rows together with table metadata.\n */\nexport function linesToTables(\n consumer: FluxResultObserver\n): CommunicationObserver {\n const splitter = new LineSplitter().withReuse()\n let columns: FluxTableColumn[] | undefined\n let expectMeta = true\n let firstColumnIndex = 0\n let lastMeta: FluxTableMetaData\n const retVal: CommunicationObserver = {\n error(error: Error): void {\n consumer.error(error)\n },\n next(line: string): void | boolean {\n if (line === '') {\n expectMeta = true\n columns = undefined\n } else {\n const values = splitter.splitLine(line)\n const size = splitter.lastSplitLength\n if (expectMeta) {\n // create columns\n if (!columns) {\n columns = new Array(size)\n for (let i = 0; i < size; i++) {\n columns[i] = newFluxTableColumn()\n }\n }\n if (!values[0].startsWith('#')) {\n // fill in column names\n if (values[0] === '') {\n firstColumnIndex = 1\n columns = columns.slice(1)\n } else {\n firstColumnIndex = 0\n }\n for (let i = firstColumnIndex; i < size; i++) {\n columns[i - firstColumnIndex].label = values[i]\n }\n lastMeta = createFluxTableMetaData(columns)\n expectMeta = false\n } else if (values[0] === '#datatype') {\n for (let i = 1; i < size; i++) {\n columns[i].dataType = values[i] as ColumnType\n }\n } else if (values[0] === '#default') {\n for (let i = 1; i < size; i++) {\n columns[i].defaultValue = values[i]\n }\n } else if (values[0] === '#group') {\n for (let i = 1; i < size; i++) {\n columns[i].group = values[i][0] === 't'\n }\n }\n } else {\n return consumer.next(values.slice(firstColumnIndex, size), lastMeta)\n }\n }\n return true\n },\n complete(): void {\n consumer.complete()\n },\n }\n if (consumer.useCancellable) {\n retVal.useCancellable = consumer.useCancellable.bind(consumer)\n }\n if (consumer.useResume) {\n retVal.useResume = consumer.useResume.bind(consumer)\n }\n return retVal\n}\n","import {LineSplitter} from './LineSplitter'\nimport {\n FluxTableColumn,\n ColumnType,\n newFluxTableColumn,\n} from './FluxTableColumn'\nimport {\n FluxTableMetaData,\n createFluxTableMetaData,\n Row,\n} from './FluxTableMetaData'\n\n/**\n * LinesToRowsIterable is a transformation that accepts\n * an iterable of flux annotated CSV lines and returns\n * an iterable of rows (row values and table metadata).\n */\nexport async function* linesToRowsIterable(\n source: AsyncIterable\n): AsyncIterableIterator {\n const splitter = new LineSplitter().withReuse()\n let columns: FluxTableColumn[] | undefined\n let expectMeta = true\n let firstColumnIndex = 0\n let lastMeta: FluxTableMetaData | undefined = undefined\n for await (const line of source) {\n if (line === '') {\n expectMeta = true\n columns = undefined\n } else {\n const values = splitter.splitLine(line)\n const size = splitter.lastSplitLength\n if (expectMeta) {\n // create columns\n if (!columns) {\n columns = new Array(size)\n for (let i = 0; i < size; i++) {\n columns[i] = newFluxTableColumn()\n }\n }\n if (!values[0].startsWith('#')) {\n // fill in column names\n if (values[0] === '') {\n firstColumnIndex = 1\n columns = columns.slice(1)\n } else {\n firstColumnIndex = 0\n }\n for (let i = firstColumnIndex; i < size; i++) {\n columns[i - firstColumnIndex].label = values[i]\n }\n lastMeta = createFluxTableMetaData(columns)\n expectMeta = false\n } else if (values[0] === '#datatype') {\n for (let i = 1; i < size; i++) {\n columns[i].dataType = values[i] as ColumnType\n }\n } else if (values[0] === '#default') {\n for (let i = 1; i < size; i++) {\n columns[i].defaultValue = values[i]\n }\n } else if (values[0] === '#group') {\n for (let i = 1; i < size; i++) {\n columns[i].group = values[i][0] === 't'\n }\n }\n } else {\n yield {\n values: values.slice(firstColumnIndex, size),\n tableMeta:\n lastMeta as unknown as FluxTableMetaData /* never undefined */,\n }\n }\n }\n }\n}\n","import {CommunicationObserver} from './CommunicationObserver'\n\n/**\n * StringToLines is a transformation that emmits strings for each CSV\n * line in the supplied source string.\n * @param source - source string\n * @param target - target to emmit CSV lines to\n * @returns communication obrver to accept Uint8Arrays\n */\nexport function stringToLines(\n source: string,\n target: CommunicationObserver\n): void {\n let quoted = false\n let start = 0\n let index = 0\n\n while (index < source.length) {\n const c = source.charCodeAt(index)\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end =\n index > 0 && source.charCodeAt(index - 1) === 13 ? index - 1 : index\n // do not emmit more lines if the processing is already finished\n target.next(source.substring(start, end))\n start = index + 1\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < index) {\n target.next(source.substring(start, index))\n }\n target.complete()\n}\n","/* Observable interop typing. Taken from https://github.com/ReactiveX/rxjs */\n\n/* Note: This will add Symbol.observable globally for all TypeScript users */\ndeclare global {\n interface SymbolConstructor {\n readonly observable: symbol\n }\n}\n\n/** Symbol.observable or a string \"\\@\\@observable\". Used for interop */\nexport const symbolObservable = (():\n | typeof Symbol.observable\n | '@@observable' =>\n (typeof Symbol === 'function' && Symbol.observable) || '@@observable')()\n","import {\n Observable,\n Observer,\n ObserverComplete,\n ObserverError,\n ObserverNext,\n Subscription,\n symbolObservable,\n} from '../observable'\nimport {CommunicationObserver} from '../results/CommunicationObserver'\nimport {Cancellable} from '../results/Cancellable'\n\n/** APIExecutor executes the API and passes its response to the supplied consumer */\nexport type APIExecutor = (consumer: CommunicationObserver) => void\n\ntype Decorator = (observer: Observer) => Observer\n\nclass QuerySubscription implements Subscription {\n private cancellable?: Cancellable\n private isClosed = false\n\n public constructor(observer: Observer, executor: APIExecutor) {\n try {\n executor({\n next: (value) => {\n observer.next(value)\n },\n error: (e) => {\n this.isClosed = true\n observer.error(e)\n },\n complete: () => {\n this.isClosed = true\n observer.complete()\n },\n useCancellable: (c) => {\n this.cancellable = c\n },\n })\n } catch (e) {\n this.isClosed = true\n observer.error(e)\n }\n }\n\n public get closed(): boolean {\n return this.isClosed\n }\n\n public unsubscribe(): void {\n this.cancellable?.cancel()\n this.isClosed = true\n }\n}\n\nfunction noop(): void {}\n\nfunction completeObserver(observer: Partial>): Observer {\n const {next, error, complete} = observer\n\n return {\n next: next ? next.bind(observer) : noop,\n error: error ? error.bind(observer) : noop,\n complete: complete ? complete.bind(observer) : noop,\n }\n}\n\nexport default class ObservableQuery implements Observable {\n public constructor(\n private readonly executor: APIExecutor,\n private readonly decorator: Decorator\n ) {}\n\n public subscribe(\n observerOrNext?: Partial> | ObserverNext,\n error?: ObserverError,\n complete?: ObserverComplete\n ): Subscription {\n const observer = completeObserver(\n typeof observerOrNext !== 'object' || observerOrNext === null\n ? {next: observerOrNext, error, complete}\n : observerOrNext\n )\n\n return new QuerySubscription(this.decorator(observer), this.executor)\n }\n\n public [symbolObservable](): this {\n return this\n }\n\n // this makes sure we satisfy the interface, while using a possibly polyfilled\n // [symbolObservable] above for the actual implementation\n public declare [Symbol.observable]: () => this\n}\n","import {Transport} from './transport'\nimport WriteApi from './WriteApi'\n\n/**\n * Option for the communication with InfluxDB server.\n */\nexport interface ConnectionOptions {\n /** base URL */\n url: string\n /** authentication token */\n token?: string\n /**\n * socket timeout, 10000 milliseconds by default in node.js\n * @defaultValue 10000\n */\n timeout?: number\n /**\n * TransportOptions supply extra options for the transport layer, they differ between node.js and browser/deno.\n * Node.js transport accepts options specified in {@link https://nodejs.org/api/http.html#http_http_request_options_callback | http.request } or\n * {@link https://nodejs.org/api/https.html#https_https_request_options_callback | https.request }. For example, an `agent` property can be set to\n * {@link https://www.npmjs.com/package/proxy-http-agent | setup HTTP/HTTPS proxy }, {@link https://nodejs.org/api/tls.html#tls_tls_connect_options_callback | rejectUnauthorized }\n * property can disable TLS server certificate verification. Additionally,\n * {@link https://github.com/follow-redirects/follow-redirects | follow-redirects } property can be also specified\n * in order to follow redirects in node.js.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | fetch } is used under the hood in browser/deno.\n * For example,\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | redirect } property can be set to 'error' to abort request if a redirect occurs.\n */\n transportOptions?: {[key: string]: any}\n /**\n * Default HTTP headers to send with every request.\n */\n headers?: Record\n /**\n * Full HTTP web proxy URL including schema, for example http://your-proxy:8080.\n */\n proxyUrl?: string\n}\n\n/** default connection options */\nexport const DEFAULT_ConnectionOptions: Partial = {\n timeout: 10000,\n}\n\n/**\n * Options that configure strategy for retrying failed requests.\n */\nexport interface RetryDelayStrategyOptions {\n /** add `random(retryJitter)` milliseconds delay when retrying HTTP calls */\n retryJitter: number\n /** minimum delay when retrying write (milliseconds) */\n minRetryDelay: number\n /** maximum delay when retrying write (milliseconds) */\n maxRetryDelay: number\n /** base for the exponential retry delay */\n exponentialBase: number\n /**\n * randomRetry indicates whether the next retry delay is deterministic (false) or random (true).\n * The deterministic delay starts with `minRetryDelay * exponentialBase` and it is multiplied\n * by `exponentialBase` until it exceeds `maxRetryDelay`.\n * When random is `true`, the next delay is computed as a random number between next retry attempt (upper)\n * and the lower number in the deterministic sequence. `random(retryJitter)` is added to every returned value.\n */\n randomRetry: boolean\n}\n\n/**\n * Options that configure strategy for retrying failed InfluxDB write operations.\n */\nexport interface WriteRetryOptions extends RetryDelayStrategyOptions {\n /**\n * WriteFailed is called to inform about write errors.\n * @param this - the instance of the API that failed\n * @param error - write error\n * @param lines - failed lines\n * @param attempt - count of already failed attempts to write the lines (1 ... maxRetries+1)\n * @param expires - expiration time for the lines to be retried in millis since epoch\n * @returns a Promise to force the API to use it as a result of the flush operation,\n * void/undefined to continue with default retry mechanism\n */\n writeFailed(\n this: WriteApi,\n error: Error,\n lines: Array,\n attempt: number,\n expires: number\n ): Promise | void\n\n /**\n * WriteSuccess is informed about successfully written lines.\n * @param this - the instance of the API in use\n * @param lines - written lines\n */\n writeSuccess(this: WriteApi, lines: Array): void\n\n /**\n * WriteRetrySkipped is informed about lines that were removed from the retry buffer\n * to keep the size of the retry buffer under the configured limit (maxBufferLines).\n * @param entry - lines that were skipped\n */\n writeRetrySkipped(entry: {lines: Array; expires: number}): void\n\n /** max count of retries after the first write fails */\n maxRetries: number\n /** max time (millis) that can be spent with retries */\n maxRetryTime: number\n /** the maximum size of retry-buffer (in lines) */\n maxBufferLines: number\n}\n\n/**\n * Options used by {@link WriteApi} .\n */\nexport interface WriteOptions extends WriteRetryOptions {\n /** max number of records/lines to send in a batch */\n batchSize: number\n /** delay between data flushes in milliseconds, at most `batch size` records are sent during flush */\n flushInterval: number\n /** default tags, unescaped */\n defaultTags?: Record\n /** HTTP headers that will be sent with every write request */\n headers?: {[key: string]: string}\n /** When specified, write bodies larger than the threshold are gzipped */\n gzipThreshold?: number\n /** max size of a batch in bytes */\n maxBatchBytes: number\n /** InfluxDB Enterprise write consistency as explained in https://docs.influxdata.com/enterprise_influxdb/v1.9/concepts/clustering/#write-consistency */\n consistency?: 'any' | 'one' | 'quorum' | 'all'\n}\n\n/** default RetryDelayStrategyOptions */\nexport const DEFAULT_RetryDelayStrategyOptions = {\n retryJitter: 200,\n minRetryDelay: 5000,\n maxRetryDelay: 125000,\n exponentialBase: 5,\n randomRetry: true,\n}\n\n/** default writeOptions */\nexport const DEFAULT_WriteOptions: WriteOptions = {\n batchSize: 1000,\n maxBatchBytes: 50_000_000, // default max batch size in the cloud\n flushInterval: 60000,\n writeFailed: function () {},\n writeSuccess: function () {},\n writeRetrySkipped: function () {},\n maxRetries: 5,\n maxRetryTime: 180_000,\n maxBufferLines: 32_000,\n // a copy of DEFAULT_RetryDelayStrategyOptions, so that DEFAULT_WriteOptions could be tree-shaken\n retryJitter: 200,\n minRetryDelay: 5000,\n maxRetryDelay: 125000,\n exponentialBase: 2,\n gzipThreshold: 1000,\n randomRetry: true,\n}\n\n/**\n * Options used by {@link InfluxDB} .\n */\nexport interface ClientOptions extends ConnectionOptions {\n /** supplies and overrides default writing options */\n writeOptions?: Partial\n /** specifies custom transport */\n transport?: Transport\n}\n\n/**\n * Timestamp precision used in write operations.\n * See {@link https://docs.influxdata.com/influxdb/latest/api/#operation/PostWrite }\n */\nexport type WritePrecisionType = 'ns' | 'us' | 'ms' | 's'\n","function createEscaper(\n characters: string,\n replacements: string[]\n): (value: string) => string {\n return function (value: string): string {\n let retVal = ''\n let from = 0\n let i = 0\n while (i < value.length) {\n const found = characters.indexOf(value[i])\n if (found >= 0) {\n retVal += value.substring(from, i)\n retVal += replacements[found]\n from = i + 1\n }\n i++\n }\n if (from == 0) {\n return value\n } else if (from < value.length) {\n retVal += value.substring(from, value.length)\n }\n return retVal\n }\n}\nfunction createQuotedEscaper(\n characters: string,\n replacements: string[]\n): (value: string) => string {\n const escaper = createEscaper(characters, replacements)\n return (value: string): string => '\"' + escaper(value) + '\"'\n}\n\n/**\n * Provides functions escape specific parts in InfluxDB line protocol.\n */\nexport const escape = {\n /**\n * Measurement escapes measurement names.\n */\n measurement: createEscaper(', \\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\n', '\\\\r', '\\\\t']),\n /**\n * Quoted escapes quoted values, such as database names.\n */\n quoted: createQuotedEscaper('\"\\\\', ['\\\\\"', '\\\\\\\\']),\n\n /**\n * TagEscaper escapes tag keys, tag values, and field keys.\n */\n tag: createEscaper(', =\\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\=', '\\\\n', '\\\\r', '\\\\t']),\n}\n","declare let process: any\nconst zeroPadding = '000000000'\nlet useHrTime = false\n\nexport function useProcessHrtime(use: boolean): boolean {\n /* istanbul ignore else */\n if (!process.env.BUILD_BROWSER) {\n return (useHrTime = use && process && typeof process.hrtime === 'function')\n } else {\n return false\n }\n}\nuseProcessHrtime(true) // preffer node\n\nlet startHrMillis: number | undefined = undefined\nlet startHrTime: [number, number] | undefined = undefined\nlet lastMillis = Date.now()\nlet stepsInMillis = 0\nfunction nanos(): string {\n if (!process.env.BUILD_BROWSER && useHrTime) {\n const hrTime = process.hrtime() as [number, number]\n let millis = Date.now()\n if (!startHrTime) {\n startHrTime = hrTime\n startHrMillis = millis\n } else {\n hrTime[0] = hrTime[0] - startHrTime[0]\n hrTime[1] = hrTime[1] - startHrTime[1]\n // istanbul ignore next \"cannot mock system clock, manually reviewed\"\n if (hrTime[1] < 0) {\n hrTime[0] -= 1\n hrTime[1] += 1000_000_000\n }\n millis =\n (startHrMillis as number) +\n hrTime[0] * 1000 +\n Math.floor(hrTime[1] / 1000_000)\n }\n const nanos = String(hrTime[1] % 1000_000)\n return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n } else {\n const millis = Date.now()\n if (millis !== lastMillis) {\n lastMillis = millis\n stepsInMillis = 0\n } else {\n stepsInMillis++\n }\n const nanos = String(stepsInMillis)\n return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n }\n}\n\nfunction micros(): string {\n if (!process.env.BUILD_BROWSER && useHrTime) {\n const hrTime = process.hrtime() as [number, number]\n const micros = String(Math.trunc(hrTime[1] / 1000) % 1000)\n return (\n String(Date.now()) + zeroPadding.substr(0, 3 - micros.length) + micros\n )\n } else {\n return String(Date.now()) + zeroPadding.substr(0, 3)\n }\n}\nfunction millis(): string {\n return String(Date.now())\n}\nfunction seconds(): string {\n return String(Math.floor(Date.now() / 1000))\n}\n\n/**\n * Exposes functions that creates strings that represent a timestamp that\n * can be used in the line protocol. Micro and nano timestamps are emulated\n * depending on the js platform in use.\n */\nexport const currentTime = {\n s: seconds as () => string,\n ms: millis as () => string,\n us: micros as () => string,\n ns: nanos as () => string,\n seconds: seconds as () => string,\n millis: millis as () => string,\n micros: micros as () => string,\n nanos: nanos as () => string,\n}\n\n/**\n * dateToProtocolTimestamp provides converters for JavaScript Date to InfluxDB Write Protocol Timestamp. Keys are supported precisions.\n */\nexport const dateToProtocolTimestamp = {\n s: (d: Date): string => `${Math.floor(d.getTime() / 1000)}`,\n ms: (d: Date): string => `${d.getTime()}`,\n us: (d: Date): string => `${d.getTime()}000`,\n ns: (d: Date): string => `${d.getTime()}000000`,\n}\n\n/**\n * convertTimeToNanos converts Point's timestamp to a string.\n * @param value - supported timestamp value\n * @returns line protocol value\n */\nexport function convertTimeToNanos(\n value: string | number | Date | undefined\n): string | undefined {\n if (value === undefined) {\n return nanos()\n } else if (typeof value === 'string') {\n return value.length > 0 ? value : undefined\n } else if (value instanceof Date) {\n return `${value.getTime()}000000`\n } else if (typeof value === 'number') {\n return String(Math.floor(value))\n } else {\n return String(value)\n }\n}\n","/**\n * Logging interface.\n */\nexport interface Logger {\n error(message: string, err?: any): void\n warn(message: string, err?: any): void\n}\n\n/**\n * Logger that logs to console.out\n */\nexport const consoleLogger: Logger = {\n error(message, error) {\n // eslint-disable-next-line no-console\n console.error('ERROR: ' + message, error ? error : '')\n },\n warn(message, error) {\n // eslint-disable-next-line no-console\n console.warn('WARN: ' + message, error ? error : '')\n },\n}\nlet provider: Logger = consoleLogger\n\nexport const Log: Logger = {\n error(message, error) {\n provider.error(message, error)\n },\n warn(message, error) {\n provider.warn(message, error)\n },\n}\n\n/**\n * Sets custom logger.\n * @param logger - logger to use\n * @returns previous logger\n */\nexport function setLogger(logger: Logger): Logger {\n const previous = provider\n provider = logger\n return previous\n}\n","/** Property that offers a function that returns flux-sanitized value of an object. */\nexport const FLUX_VALUE = Symbol('FLUX_VALUE')\n\n/**\n * A flux parameter can print its (sanitized) flux value.\n */\nexport interface FluxParameterLike {\n [FLUX_VALUE](): string\n}\n\n/**\n * Represents a parameterized query.\n */\nexport interface ParameterizedQuery {\n /**\n * Returns flux query with sanitized parameters.\n */\n toString(): string\n}\n\nclass FluxParameter implements FluxParameterLike, ParameterizedQuery {\n constructor(private fluxValue: string) {}\n toString(): string {\n return this.fluxValue\n }\n [FLUX_VALUE](): string {\n return this.fluxValue\n }\n}\n\n/**\n * Checks if the supplied object is FluxParameterLike\n * @param value - any value\n * @returns true if it is\n */\nfunction isFluxParameterLike(value: any): boolean {\n return typeof value === 'object' && typeof value[FLUX_VALUE] === 'function'\n}\n\n/**\n * Escapes content of the supplied string so it can be wrapped into double qoutes\n * to become a [flux string literal](https://docs.influxdata.com/flux/latest/spec/lexical-elements/#string-literals).\n * @param value - string value\n * @returns sanitized string\n */\nfunction sanitizeString(value: any): string {\n if (value === null || value === undefined) return ''\n value = value.toString()\n let retVal: any = undefined\n let i = 0\n function prepareRetVal(): void {\n if (retVal === undefined) {\n retVal = value.substring(0, i)\n }\n }\n for (; i < value.length; i++) {\n const c = value.charAt(i)\n switch (c) {\n case '\\r':\n prepareRetVal()\n retVal += '\\\\r'\n break\n case '\\n':\n prepareRetVal()\n retVal += '\\\\n'\n break\n case '\\t':\n prepareRetVal()\n retVal += '\\\\t'\n break\n case '\"':\n case '\\\\':\n prepareRetVal()\n retVal = retVal + '\\\\' + c\n break\n case '$':\n // escape ${\n if (i + 1 < value.length && value.charAt(i + 1) === '{') {\n prepareRetVal()\n i++\n retVal += '\\\\${'\n break\n }\n // append $\n if (retVal != undefined) {\n retVal += c\n }\n break\n default:\n if (retVal != undefined) {\n retVal += c\n }\n }\n }\n if (retVal !== undefined) {\n return retVal\n }\n return value\n}\n\n/**\n * Creates a flux string literal.\n */\nexport function fluxString(value: any): FluxParameterLike {\n return new FluxParameter(`\"${sanitizeString(value)}\"`)\n}\n\n/**\n * Sanitizes float value to avoid injections.\n * @param value - InfluxDB float literal\n * @returns sanitized float value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeFloat(value: any): string {\n const val = Number(value)\n if (!isFinite(val)) {\n if (typeof value === 'number') {\n return `float(v: \"${val}\")`\n }\n throw new Error(`not a flux float: ${value}`)\n }\n // try to return a flux float literal if possible\n // https://docs.influxdata.com/flux/latest/data-types/basic/float/#float-syntax\n const strVal = val.toString()\n let hasDot = false\n for (const c of strVal) {\n if ((c >= '0' && c <= '9') || c == '-') continue\n if (c === '.') {\n hasDot = true\n continue\n }\n return `float(v: \"${strVal}\")`\n }\n return hasDot ? strVal : strVal + '.0'\n}\n/**\n * Creates a flux float literal.\n */\nexport function fluxFloat(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeFloat(value))\n}\n\n/**\n * Sanitizes integer value to avoid injections.\n * @param value - InfluxDB integer literal\n * @returns sanitized integer value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeInteger(value: any): string {\n // https://docs.influxdata.com/flux/latest/data-types/basic/int/\n // Min value: -9223372036854775808\n // Max value: 9223372036854775807\n // \"9223372036854775807\".length === 19\n const strVal = String(value)\n const negative = strVal.startsWith('-')\n const val = negative ? strVal.substring(1) : strVal\n if (val.length === 0 || val.length > 19) {\n throw new Error(`not a flux integer: ${strVal}`)\n }\n for (const c of val) {\n if (c < '0' || c > '9') throw new Error(`not a flux integer: ${strVal}`)\n }\n if (val.length === 19) {\n if (negative && val > '9223372036854775808') {\n throw new Error(`flux integer out of bounds: ${strVal}`)\n }\n if (!negative && val > '9223372036854775807') {\n throw new Error(`flux integer out of bounds: ${strVal}`)\n }\n }\n return strVal\n}\n\n/**\n * Creates a flux integer literal.\n */\nexport function fluxInteger(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeInteger(value))\n}\n\nfunction sanitizeDateTime(value: any): string {\n return `time(v: \"${sanitizeString(value)}\")`\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDateTime(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeDateTime(value))\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDuration(value: any): FluxParameterLike {\n return new FluxParameter(`duration(v: \"${sanitizeString(value)}\")`)\n}\n\nfunction sanitizeRegExp(value: any): string {\n if (value instanceof RegExp) {\n return value.toString()\n }\n return new RegExp(value).toString()\n}\n\n/**\n * Creates flux regexp literal out of a regular expression. See\n * https://docs.influxdata.com/flux/latest/data-types/basic/regexp/#regular-expression-syntax\n * for details.\n */\nexport function fluxRegExp(value: any): FluxParameterLike {\n // let the server decide if a regexp can be parsed\n return new FluxParameter(sanitizeRegExp(value))\n}\n\n/**\n * Creates flux boolean literal.\n */\nexport function fluxBool(value: any): FluxParameterLike {\n if (value === 'true' || value === 'false') {\n return new FluxParameter(value)\n }\n return new FluxParameter((!!value).toString())\n}\n\n/**\n * Assumes that the supplied value is flux expression or literal that does not need sanitizing.\n *\n * @param value - any value\n * @returns the supplied value as-is\n */\nexport function fluxExpression(value: any): FluxParameterLike {\n return new FluxParameter(String(value))\n}\n\n/**\n * Escapes content of the supplied parameter so that it can be safely embedded into flux query.\n * @param value - parameter value\n * @returns sanitized flux value or an empty string if it cannot be converted\n */\nexport function toFluxValue(value: any): string {\n if (value === undefined) {\n return ''\n } else if (value === null) {\n return 'null'\n } else if (typeof value === 'boolean') {\n return value.toString()\n } else if (typeof value === 'string') {\n return `\"${sanitizeString(value)}\"`\n } else if (typeof value === 'number') {\n if (Number.isSafeInteger(value)) {\n return sanitizeInteger(value)\n }\n return sanitizeFloat(value)\n } else if (typeof value === 'object') {\n if (typeof value[FLUX_VALUE] === 'function') {\n return value[FLUX_VALUE]()\n } else if (value instanceof Date) {\n return value.toISOString()\n } else if (value instanceof RegExp) {\n return sanitizeRegExp(value)\n } else if (Array.isArray(value)) {\n return `[${value.map(toFluxValue).join(',')}]`\n }\n } else if (typeof value === 'bigint') {\n return `${value}.0`\n }\n // use toString value for unrecognized object, symbol\n return toFluxValue(value.toString())\n}\n\n/**\n * Flux is a tagged template that sanitizes supplied parameters\n * to avoid injection attacks in flux.\n */\nexport function flux(\n strings: TemplateStringsArray,\n ...values: any\n): ParameterizedQuery {\n if (strings.length == 1 && values.length === 0) {\n return fluxExpression(strings[0]) // the simplest case\n }\n const parts = new Array(strings.length + values.length)\n let partIndex = 0\n for (let i = 0; i < strings.length; i++) {\n const text = strings[i]\n parts[partIndex++] = text\n if (i < values.length) {\n const val = values[i]\n let sanitized: string\n if (\n text.endsWith('\"') &&\n i + 1 < strings.length &&\n strings[i + 1].startsWith('\"')\n ) {\n // parameter is wrapped into flux double quotes\n sanitized = sanitizeString(val)\n } else {\n sanitized = toFluxValue(val)\n if (sanitized === '') {\n // do not allow to insert empty strings, unless it is FluxParameterLike\n if (!isFluxParameterLike(val)) {\n throw new Error(\n `Unsupported parameter literal '${val}' at index: ${i}, type: ${typeof val}`\n )\n }\n }\n }\n parts[partIndex++] = sanitized\n } else if (i < strings.length - 1) {\n throw new Error('Too few parameters supplied!')\n }\n }\n // return flux expression so that flux can be embedded into another flux as-is\n return fluxExpression(parts.join(''))\n}\n","import {convertTimeToNanos} from './util/currentTime'\nimport {escape} from './util/escape'\n\n/**\n * Settings that control the way of how a {@link Point} is serialized\n * to a protocol line.\n */\nexport interface PointSettings {\n /** default tags to add to every point */\n defaultTags?: {[key: string]: string}\n /** convertTime serializes Point's timestamp to a line protocol value */\n convertTime?: (\n value: string | number | Date | undefined\n ) => string | undefined\n}\n\n/**\n * Point defines values of a single measurement.\n */\nexport class Point {\n private name: string\n private tags: {[key: string]: string} = {}\n /** escaped field values */\n public fields: {[key: string]: string} = {}\n private time: string | number | Date | undefined\n\n /**\n * Create a new Point with specified a measurement name.\n *\n * @param measurementName - the measurement name\n */\n constructor(measurementName?: string) {\n if (measurementName) this.name = measurementName\n }\n\n /**\n * Sets point's measurement.\n *\n * @param name - measurement name\n * @returns this\n */\n public measurement(name: string): Point {\n this.name = name\n return this\n }\n\n /**\n * Adds a tag. The caller has to ensure that both name and value are not empty\n * and do not end with backslash.\n *\n * @param name - tag name\n * @param value - tag value\n * @returns this\n */\n public tag(name: string, value: string): Point {\n this.tags[name] = value\n return this\n }\n\n /**\n * Adds a boolean field.\n *\n * @param field - field name\n * @param value - field value\n * @returns this\n */\n public booleanField(name: string, value: boolean | any): Point {\n this.fields[name] = value ? 'T' : 'F'\n return this\n }\n\n /**\n * Adds an integer field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN or out of int64 range value is supplied\n */\n public intField(name: string, value: number | any): Point {\n let val: number\n if (typeof value === 'number') {\n val = value\n } else {\n val = parseInt(String(value))\n }\n if (isNaN(val) || val <= -9223372036854776e3 || val >= 9223372036854776e3) {\n throw new Error(`invalid integer value for field '${name}': '${value}'!`)\n }\n this.fields[name] = `${Math.floor(val)}i`\n return this\n }\n\n /**\n * Adds an unsigned integer field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN out of range value is supplied\n */\n public uintField(name: string, value: number | any): Point {\n if (typeof value === 'number') {\n if (isNaN(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {\n throw new Error(`uint value for field '${name}' out of range: ${value}`)\n }\n this.fields[name] = `${Math.floor(value as number)}u`\n } else {\n const strVal = String(value)\n for (let i = 0; i < strVal.length; i++) {\n const code = strVal.charCodeAt(i)\n if (code < 48 || code > 57) {\n throw new Error(\n `uint value has an unsupported character at pos ${i}: ${value}`\n )\n }\n }\n if (\n strVal.length > 20 ||\n (strVal.length === 20 &&\n strVal.localeCompare('18446744073709551615') > 0)\n ) {\n throw new Error(\n `uint value for field '${name}' out of range: ${strVal}`\n )\n }\n this.fields[name] = `${strVal}u`\n }\n return this\n }\n\n /**\n * Adds a number field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN/Infinity/-Infinity is supplied\n */\n public floatField(name: string, value: number | any): Point {\n let val: number\n if (typeof value === 'number') {\n val = value\n } else {\n val = parseFloat(value)\n }\n if (!isFinite(val)) {\n throw new Error(`invalid float value for field '${name}': ${value}`)\n }\n\n this.fields[name] = String(val)\n return this\n }\n\n /**\n * Adds a string field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n */\n public stringField(name: string, value: string | any): Point {\n if (value !== null && value !== undefined) {\n if (typeof value !== 'string') value = String(value)\n this.fields[name] = escape.quoted(value)\n }\n return this\n }\n\n /**\n * Sets point timestamp. Timestamp can be specified as a Date (preferred), number, string\n * or an undefined value. An undefined value instructs to assign a local timestamp using\n * the client's clock. An empty string can be used to let the server assign\n * the timestamp. A number value represents time as a count of time units since epoch, the\n * exact time unit then depends on the {@link InfluxDB.getWriteApi | precision} of the API\n * that writes the point.\n *\n * Beware that the current time in nanoseconds can't precisely fit into a JS number,\n * which can hold at most 2^53 integer number. Nanosecond precision numbers are thus supplied as\n * a (base-10) string. An application can also use ES2020 BigInt to represent nanoseconds,\n * BigInt's `toString()` returns the required high-precision string.\n *\n * Note that InfluxDB requires the timestamp to fit into int64 data type.\n *\n * @param value - point time\n * @returns this\n */\n public timestamp(value: Date | number | string | undefined): Point {\n this.time = value\n return this\n }\n\n /**\n * Creates an InfluxDB protocol line out of this instance.\n * @param settings - settings control serialization of a point timestamp and can also add default tags,\n * nanosecond timestamp precision is used when no `settings` or no `settings.convertTime` is supplied.\n * @returns an InfluxDB protocol line out of this instance\n */\n public toLineProtocol(settings?: Partial): string | undefined {\n if (!this.name) return undefined\n let fieldsLine = ''\n Object.keys(this.fields)\n .sort()\n .forEach((x) => {\n if (x) {\n const val = this.fields[x]\n if (fieldsLine.length > 0) fieldsLine += ','\n fieldsLine += `${escape.tag(x)}=${val}`\n }\n })\n if (fieldsLine.length === 0) return undefined // no fields present\n let tagsLine = ''\n const tags =\n settings && settings.defaultTags\n ? {...settings.defaultTags, ...this.tags}\n : this.tags\n Object.keys(tags)\n .sort()\n .forEach((x) => {\n if (x) {\n const val = tags[x]\n if (val) {\n tagsLine += ','\n tagsLine += `${escape.tag(x)}=${escape.tag(val)}`\n }\n }\n })\n let time = this.time\n if (settings && settings.convertTime) {\n time = settings.convertTime(time)\n } else {\n time = convertTimeToNanos(time)\n }\n\n return `${escape.measurement(this.name)}${tagsLine} ${fieldsLine}${\n time !== undefined ? ' ' + time : ''\n }`\n }\n\n toString(): string {\n const line = this.toLineProtocol(undefined)\n return line ? line : `invalid point: ${JSON.stringify(this, undefined)}`\n }\n}\n","import {getRetryDelay, RetryDelayStrategy} from '../errors'\nimport {\n RetryDelayStrategyOptions,\n DEFAULT_RetryDelayStrategyOptions,\n} from '../options'\n\n/**\n * Applies a variant of exponential backoff with initial and max delay and a random\n * jitter delay. It also respects `retry delay` when specified together with an error.\n */\nexport class RetryStrategyImpl implements RetryDelayStrategy {\n options: RetryDelayStrategyOptions\n currentDelay: number | undefined\n\n constructor(options?: Partial) {\n this.options = {...DEFAULT_RetryDelayStrategyOptions, ...options}\n this.success()\n }\n\n nextDelay(error?: Error, failedAttempts?: number): number {\n const delay = getRetryDelay(error)\n if (delay && delay > 0) {\n return delay + Math.round(Math.random() * this.options.retryJitter)\n } else {\n if (failedAttempts && failedAttempts > 0) {\n // compute delay\n if (this.options.randomRetry) {\n // random delay between deterministic delays\n let delay = Math.max(this.options.minRetryDelay, 1)\n let nextDelay = delay * this.options.exponentialBase\n for (let i = 1; i < failedAttempts; i++) {\n delay = nextDelay\n nextDelay = nextDelay * this.options.exponentialBase\n if (nextDelay >= this.options.maxRetryDelay) {\n nextDelay = this.options.maxRetryDelay\n break\n }\n }\n return (\n delay +\n Math.round(\n Math.random() * (nextDelay - delay) +\n Math.random() * this.options.retryJitter\n )\n )\n }\n // deterministric delay otherwise\n let delay = Math.max(this.options.minRetryDelay, 1)\n for (let i = 1; i < failedAttempts; i++) {\n delay = delay * this.options.exponentialBase\n if (delay >= this.options.maxRetryDelay) {\n delay = this.options.maxRetryDelay\n break\n }\n }\n return delay + Math.round(Math.random() * this.options.retryJitter)\n } else if (this.currentDelay) {\n this.currentDelay = Math.min(\n Math.max(this.currentDelay * this.options.exponentialBase, 1) +\n Math.round(Math.random() * this.options.retryJitter),\n this.options.maxRetryDelay\n )\n } else {\n this.currentDelay =\n this.options.minRetryDelay +\n Math.round(Math.random() * this.options.retryJitter)\n }\n return this.currentDelay\n }\n }\n success(): void {\n this.currentDelay = undefined\n }\n}\n\n/**\n * Creates a new instance of retry strategy.\n * @param options - retry options\n * @returns retry strategy implementation\n */\nexport function createRetryDelayStrategy(\n options?: Partial\n): RetryDelayStrategy {\n return new RetryStrategyImpl(options)\n}\n","import {Log} from '../util/logger'\n\ninterface RetryItem {\n lines: string[]\n retryCount: number\n retryTime: number\n expires: number\n next?: RetryItem\n}\n\ntype FindShrinkCandidateResult = [found: RetryItem, parent?: RetryItem]\n\nfunction findShrinkCandidate(first: RetryItem): FindShrinkCandidateResult {\n let parent = undefined\n let found = first\n let currentParent = first\n while (currentParent.next) {\n if (currentParent.next.expires < found.expires) {\n parent = currentParent\n found = currentParent.next\n }\n currentParent = currentParent.next\n }\n return [found, parent]\n}\n\n/**\n * Retries lines up to a limit of max buffer size.\n */\nexport default class RetryBuffer {\n first?: RetryItem\n size = 0\n closed = false\n private _timeoutHandle: any = undefined\n\n constructor(\n private maxLines: number,\n private retryLines: (\n lines: string[],\n retryCountdown: number,\n started: number\n ) => Promise,\n private onShrink: (entry: {\n lines: string[]\n retryCount: number\n expires: number\n }) => void = () => undefined\n ) {}\n\n addLines(\n lines: string[],\n retryCount: number,\n delay: number,\n expires: number\n ): void {\n if (this.closed) return\n if (!lines.length) return\n let retryTime = Date.now() + delay\n if (expires < retryTime) {\n retryTime = expires\n }\n // ensure at most maxLines are in the Buffer\n if (this.first && this.size + lines.length > this.maxLines) {\n const origSize = this.size\n const newSize = origSize * 0.7 // reduce to 70 %\n do {\n // remove \"oldest\" item\n const [found, parent] = findShrinkCandidate(this.first)\n this.size -= found.lines.length\n if (parent) {\n parent.next = found.next\n } else {\n this.first = found.next\n if (this.first) {\n this.scheduleRetry(this.first.retryTime - Date.now())\n }\n }\n found.next = undefined\n this.onShrink(found)\n } while (this.first && this.size + lines.length > newSize)\n Log.error(\n `RetryBuffer: ${\n origSize - this.size\n } oldest lines removed to keep buffer size under the limit of ${\n this.maxLines\n } lines.`\n )\n }\n const toAdd: RetryItem = {\n lines,\n retryCount,\n retryTime,\n expires,\n }\n // insert sorted according to retryTime\n let current: RetryItem | undefined = this.first\n let parent = undefined\n for (;;) {\n if (!current || current.retryTime > retryTime) {\n toAdd.next = current\n if (parent) {\n parent.next = toAdd\n } else {\n this.first = toAdd\n this.scheduleRetry(retryTime - Date.now())\n }\n break\n }\n parent = current\n current = current.next\n }\n this.size += lines.length\n }\n\n removeLines(): RetryItem | undefined {\n if (this.first) {\n const toRetry = this.first\n this.first = this.first.next\n toRetry.next = undefined\n this.size -= toRetry.lines.length\n return toRetry\n }\n return undefined\n }\n\n scheduleRetry(delay: number): void {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle)\n }\n this._timeoutHandle = setTimeout(() => {\n const toRetry = this.removeLines()\n if (toRetry) {\n this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n .catch(() => {\n /* error is already logged, it must be caught */\n })\n .finally(() => {\n // schedule next retry execution\n if (this.first) {\n this.scheduleRetry(this.first.retryTime - Date.now())\n }\n })\n } else {\n this._timeoutHandle = undefined\n }\n }, Math.max(delay, 0))\n }\n\n async flush(): Promise {\n let toRetry\n while ((toRetry = this.removeLines())) {\n await this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n }\n }\n\n close(): number {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle)\n this._timeoutHandle = undefined\n }\n this.closed = true\n return this.size\n }\n}\n","/**\n * Utf8Length returns an expected length of a string when UTF-8 encoded.\n * @param s - input string\n * @returns expected count of bytes\n */\nexport default function utf8Length(s: string): number {\n let retVal = s.length\n // extends the size with code points (https://en.wikipedia.org/wiki/UTF-8#Encoding)\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i)\n /* istanbul ignore else - JS does not count with 4-bytes UNICODE characters at the moment */\n if (code < 0x80) {\n continue\n } else if (code >= 0x80 && code <= 0x7ff) {\n retVal++\n } else if (code >= 0x800 && code <= 0xffff) {\n if (code >= 0xd800 && code <= 0xdfff) {\n // node.js represents unicode characters above 0xffff by two UTF-16 surrogate halves\n // see https://en.wikipedia.org/wiki/UTF-8#Codepage_layout\n retVal++\n } else {\n retVal += 2\n }\n } else {\n // never happens in node.js 14, the situation can vary in the futures or in deno/browsers\n retVal += 3\n }\n }\n return retVal\n}\n","import WriteApi from '../WriteApi'\nimport {\n DEFAULT_WriteOptions,\n WriteOptions,\n WritePrecisionType,\n} from '../options'\nimport {Transport, SendOptions} from '../transport'\nimport {Headers} from '../results'\nimport {Log} from '../util/logger'\nimport {HttpError, RetryDelayStrategy} from '../errors'\nimport {Point} from '../Point'\nimport {currentTime, dateToProtocolTimestamp} from '../util/currentTime'\nimport {createRetryDelayStrategy} from './retryStrategy'\nimport RetryBuffer from './RetryBuffer'\nimport utf8Length from '../util/utf8Length'\n\nclass WriteBuffer {\n length = 0\n bytes = -1\n lines: string[]\n\n constructor(\n private maxChunkRecords: number,\n private maxBatchBytes: number,\n private flushFn: (lines: string[]) => Promise,\n private scheduleSend: () => void\n ) {\n this.lines = new Array(maxChunkRecords)\n }\n\n add(record: string): void {\n const size = utf8Length(record)\n if (this.length === 0) {\n this.scheduleSend()\n } else if (this.bytes + size + 1 >= this.maxBatchBytes) {\n // the new size already exceeds maxBatchBytes, send it\n this.flush().catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n })\n }\n this.lines[this.length] = record\n this.length++\n this.bytes += size + 1\n if (\n this.length >= this.maxChunkRecords ||\n this.bytes >= this.maxBatchBytes\n ) {\n this.flush().catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n })\n }\n }\n flush(): Promise {\n const lines = this.reset()\n if (lines.length > 0) {\n return this.flushFn(lines)\n } else {\n return Promise.resolve()\n }\n }\n reset(): string[] {\n const retVal = this.lines.slice(0, this.length)\n this.length = 0\n this.bytes = -1 // lines are joined with \\n\n return retVal\n }\n}\n\nexport default class WriteApiImpl implements WriteApi {\n public path: string\n\n private writeBuffer: WriteBuffer\n private closed = false\n private writeOptions: WriteOptions\n private sendOptions: SendOptions\n private _timeoutHandle: any = undefined\n private currentTime: () => string\n private dateToProtocolTimestamp: (d: Date) => string\n\n retryBuffer: RetryBuffer\n retryStrategy: RetryDelayStrategy\n\n constructor(\n private transport: Transport,\n org: string,\n bucket: string,\n precision: WritePrecisionType,\n writeOptions?: Partial\n ) {\n this.path = `/api/v2/write?org=${encodeURIComponent(\n org\n )}&bucket=${encodeURIComponent(bucket)}&precision=${precision}`\n if (writeOptions?.consistency) {\n this.path += `&consistency=${encodeURIComponent(\n writeOptions.consistency\n )}`\n }\n this.writeOptions = {\n ...DEFAULT_WriteOptions,\n ...writeOptions,\n }\n this.currentTime = currentTime[precision]\n this.dateToProtocolTimestamp = dateToProtocolTimestamp[precision]\n if (this.writeOptions.defaultTags) {\n this.useDefaultTags(this.writeOptions.defaultTags)\n }\n this.sendOptions = {\n method: 'POST',\n headers: {\n 'content-type': 'text/plain; charset=utf-8',\n ...writeOptions?.headers,\n },\n gzipThreshold: this.writeOptions.gzipThreshold,\n }\n\n const scheduleNextSend = (): void => {\n if (this.writeOptions.flushInterval > 0) {\n this._clearFlushTimeout()\n /* istanbul ignore else manually reviewed, hard to reproduce */\n if (!this.closed) {\n this._timeoutHandle = setTimeout(\n () =>\n this.sendBatch(\n this.writeBuffer.reset(),\n this.writeOptions.maxRetries\n ).catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n }),\n this.writeOptions.flushInterval\n )\n }\n }\n }\n // write buffer\n this.writeBuffer = new WriteBuffer(\n this.writeOptions.batchSize,\n this.writeOptions.maxBatchBytes,\n (lines) => {\n this._clearFlushTimeout()\n return this.sendBatch(lines, this.writeOptions.maxRetries)\n },\n scheduleNextSend\n )\n this.sendBatch = this.sendBatch.bind(this)\n // retry buffer\n this.retryStrategy = createRetryDelayStrategy(this.writeOptions)\n this.retryBuffer = new RetryBuffer(\n this.writeOptions.maxBufferLines,\n this.sendBatch,\n this.writeOptions.writeRetrySkipped\n )\n }\n\n sendBatch(\n lines: string[],\n retryAttempts: number,\n expires: number = Date.now() + this.writeOptions.maxRetryTime\n ): Promise {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self: WriteApiImpl = this\n const failedAttempts = self.writeOptions.maxRetries + 1 - retryAttempts\n if (!this.closed && lines.length > 0) {\n if (expires <= Date.now()) {\n const error = new Error('Max retry time exceeded.')\n const onRetry = self.writeOptions.writeFailed.call(\n self,\n error,\n lines,\n failedAttempts,\n expires\n )\n if (onRetry) {\n return onRetry\n }\n Log.error(\n `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n error\n )\n return Promise.reject(error)\n }\n return new Promise((resolve, reject) => {\n let responseStatusCode: number | undefined\n const callbacks = {\n responseStarted(_headers: Headers, statusCode?: number): void {\n responseStatusCode = statusCode\n },\n error(error: Error): void {\n // call the writeFailed listener and check if we can retry\n const onRetry = self.writeOptions.writeFailed.call(\n self,\n error,\n lines,\n failedAttempts,\n expires\n )\n if (onRetry) {\n onRetry.then(resolve, reject)\n return\n }\n // ignore informational message about the state of InfluxDB\n // enterprise cluster, if present\n if (\n error instanceof HttpError &&\n error.json &&\n typeof error.json.error === 'string' &&\n error.json.error.includes('hinted handoff queue not empty')\n ) {\n Log.warn('Write to InfluxDB returns: ' + error.json.error)\n responseStatusCode = 204\n callbacks.complete()\n return\n }\n // retry if possible\n if (\n !self.closed &&\n retryAttempts > 0 &&\n (!(error instanceof HttpError) ||\n (error as HttpError).statusCode >= 429)\n ) {\n Log.warn(\n `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n error\n )\n self.retryBuffer.addLines(\n lines,\n retryAttempts - 1,\n self.retryStrategy.nextDelay(error, failedAttempts),\n expires\n )\n reject(error)\n return\n }\n Log.error(`Write to InfluxDB failed.`, error)\n reject(error)\n },\n complete(): void {\n // older implementations of transport do not report status code\n if (responseStatusCode == 204 || responseStatusCode == undefined) {\n self.writeOptions.writeSuccess.call(self, lines)\n self.retryStrategy.success()\n resolve()\n } else {\n const message = `204 HTTP response status code expected, but ${responseStatusCode} returned`\n const error = new HttpError(\n responseStatusCode,\n message,\n undefined,\n '0'\n )\n error.message = message\n callbacks.error(error)\n }\n },\n }\n this.transport.send(\n this.path,\n lines.join('\\n'),\n this.sendOptions,\n callbacks\n )\n })\n } else {\n return Promise.resolve()\n }\n }\n\n private _clearFlushTimeout(): void {\n if (this._timeoutHandle !== undefined) {\n clearTimeout(this._timeoutHandle)\n this._timeoutHandle = undefined\n }\n }\n\n writeRecord(record: string): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n this.writeBuffer.add(record)\n }\n writeRecords(records: ArrayLike): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n for (let i = 0; i < records.length; i++) {\n this.writeBuffer.add(records[i])\n }\n }\n writePoint(point: Point): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n const line = point.toLineProtocol(this)\n if (line) this.writeBuffer.add(line)\n }\n writePoints(points: ArrayLike): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n for (let i = 0; i < points.length; i++) {\n const line = points[i].toLineProtocol(this)\n if (line) this.writeBuffer.add(line)\n }\n }\n async flush(withRetryBuffer?: boolean): Promise {\n await this.writeBuffer.flush()\n if (withRetryBuffer) {\n return await this.retryBuffer.flush()\n }\n }\n close(): Promise {\n const retVal = this.writeBuffer.flush().finally(() => {\n const remaining = this.retryBuffer.close()\n if (remaining) {\n Log.error(\n `Retry buffer closed with ${remaining} items that were not written to InfluxDB!`,\n null\n )\n }\n this.closed = true\n })\n return retVal\n }\n dispose(): number {\n this._clearFlushTimeout()\n this.closed = true\n return this.retryBuffer.close() + this.writeBuffer.length\n }\n\n // PointSettings\n defaultTags: {[key: string]: string} | undefined\n useDefaultTags(tags: {[key: string]: string}): WriteApi {\n this.defaultTags = tags\n return this\n }\n convertTime(value: string | number | Date | undefined): string | undefined {\n if (value === undefined) {\n return this.currentTime()\n } else if (typeof value === 'string') {\n return value.length > 0 ? value : undefined\n } else if (value instanceof Date) {\n return this.dateToProtocolTimestamp(value)\n } else if (typeof value === 'number') {\n return String(Math.floor(value))\n } else {\n return String(value)\n }\n }\n}\n","import {ConnectionOptions, DEFAULT_ConnectionOptions} from '../../options'\nimport {parse} from 'url'\nimport * as http from 'http'\nimport * as https from 'https'\nimport {Buffer} from 'buffer'\nimport {RequestTimedOutError, AbortError, HttpError} from '../../errors'\nimport {Transport, SendOptions} from '../../transport'\nimport {\n Cancellable,\n ChunkCombiner,\n CommunicationObserver,\n Headers,\n ResponseStartedFn,\n} from '../../results'\nimport nodeChunkCombiner from './nodeChunkCombiner'\nimport zlib from 'zlib'\nimport completeCommunicationObserver from '../completeCommunicationObserver'\nimport {CLIENT_LIB_VERSION} from '../version'\nimport {Log} from '../../util/logger'\nimport {pipeline, Readable} from 'stream'\n\nconst zlibOptions = {\n flush: zlib.constants.Z_SYNC_FLUSH,\n finishFlush: zlib.constants.Z_SYNC_FLUSH,\n}\nconst emptyBuffer = Buffer.allocUnsafe(0)\n\nclass CancellableImpl implements Cancellable {\n private cancelled = false\n public resume?: () => void\n cancel(): void {\n this.cancelled = true\n if (this.resume) {\n this.resume()\n this.resume = undefined\n }\n }\n isCancelled(): boolean {\n return this.cancelled\n }\n}\n\n/**\n * Transport layer on top of node http or https library.\n */\nexport class NodeHttpTransport implements Transport {\n /* required transport member */\n readonly chunkCombiner: ChunkCombiner = nodeChunkCombiner\n\n private defaultOptions: {[key: string]: any}\n private requestApi: (\n options: http.RequestOptions,\n callback: (res: http.IncomingMessage) => void\n ) => http.ClientRequest\n private contextPath: string\n private token?: string\n private headers: Record\n /**\n * Creates a node transport using for the client options supplied.\n * @param connectionOptions - connection options\n */\n constructor(connectionOptions: ConnectionOptions) {\n const {\n url: _url,\n proxyUrl,\n token,\n transportOptions,\n ...nodeSupportedOptions\n } = connectionOptions\n const url = parse(proxyUrl || _url)\n this.token = token\n this.defaultOptions = {\n ...DEFAULT_ConnectionOptions,\n ...nodeSupportedOptions,\n ...transportOptions,\n port: url.port,\n protocol: url.protocol,\n hostname: url.hostname,\n }\n this.contextPath = proxyUrl ? _url : url.path ?? ''\n if (this.contextPath.endsWith('/')) {\n this.contextPath = this.contextPath.substring(\n 0,\n this.contextPath.length - 1\n )\n }\n // remove all undefined field to avoid node validation errors\n // https://github.com/influxdata/influxdb-client-js/issues/380\n Object.keys(this.defaultOptions).forEach(\n (key) =>\n this.defaultOptions[key] === undefined &&\n delete this.defaultOptions[key]\n )\n // https://github.com/influxdata/influxdb-client-js/issues/263\n // don't allow /api/v2 suffix to avoid future problems\n if (this.contextPath.endsWith('/api/v2')) {\n Log.warn(\n `Please remove '/api/v2' context path from InfluxDB base url, using ${url.protocol}//${url.hostname}:${url.port} !`\n )\n this.contextPath = ''\n }\n\n if (url.protocol === 'http:') {\n this.requestApi =\n this.defaultOptions['follow-redirects']?.http?.request ?? http.request\n } else if (url.protocol === 'https:') {\n this.requestApi =\n this.defaultOptions['follow-redirects']?.https?.request ?? https.request\n } else {\n throw new Error(\n `Unsupported protocol \"${url.protocol} in URL: \"${connectionOptions.url}\"`\n )\n }\n this.headers = {\n 'User-Agent': `influxdb-client-js/${CLIENT_LIB_VERSION}`,\n ...connectionOptions.headers,\n }\n if (proxyUrl) {\n this.headers['Host'] = parse(_url).host as string\n }\n }\n\n /**\n * Sends data to server and receives communication events via communication callbacks.\n *\n * @param path - HTTP request path\n * @param body - message body\n * @param headers - HTTP headers\n * @param method - HTTP method\n * @param callbacks - communication callbacks\n */\n send(\n path: string,\n body: string,\n options: SendOptions,\n callbacks?: Partial>\n ): void {\n const cancellable = new CancellableImpl()\n if (callbacks && callbacks.useCancellable)\n callbacks.useCancellable(cancellable)\n this.createRequestMessage(\n path,\n body,\n options,\n (message: {[key: string]: any}) => {\n this._request(message, cancellable, callbacks)\n },\n /* istanbul ignore next - hard to simulate failure, manually reviewed */\n (err: Error) => callbacks?.error && callbacks.error(err)\n )\n }\n\n /**\n * Sends data to the server and receives decoded result. The type of the result depends on\n * response's content-type (deserialized json, text).\n \n * @param path - HTTP path\n * @param requestBody - request body\n * @param options - send options\n * @returns Promise of response body\n */\n request(\n path: string,\n body: any,\n options: SendOptions,\n responseStarted?: ResponseStartedFn\n ): Promise {\n if (!body) {\n body = ''\n } else if (typeof body !== 'string') {\n body = JSON.stringify(body)\n }\n let buffer = emptyBuffer\n let contentType: string\n let responseStatusCode: number | undefined\n return new Promise((resolve, reject) => {\n this.send(path, body as string, options, {\n responseStarted(headers: Headers, statusCode?: number) {\n if (responseStarted) {\n responseStarted(headers, statusCode)\n }\n contentType = String(headers['content-type'])\n responseStatusCode = statusCode\n },\n next: (data: Uint8Array): void => {\n buffer = Buffer.concat([buffer, data])\n },\n complete: (): void => {\n const responseType = options.headers?.accept ?? contentType\n try {\n if (responseStatusCode === 204) {\n // ignore body of NO_CONTENT response\n resolve(undefined)\n }\n if (responseType.includes('json')) {\n if (buffer.length) {\n resolve(JSON.parse(buffer.toString('utf8')))\n } else {\n resolve(undefined)\n }\n } else if (\n responseType.includes('text') ||\n responseType.startsWith('application/csv')\n ) {\n resolve(buffer.toString('utf8'))\n } else {\n resolve(buffer)\n }\n } catch (e) {\n reject(e)\n }\n },\n error: (e: Error): void => {\n reject(e)\n },\n })\n })\n }\n\n async *iterate(\n path: string,\n body: string,\n options: SendOptions\n ): AsyncIterableIterator {\n let terminationError: Error | undefined = undefined\n let nestedReject: (e: Error) => void\n function wrapReject(error: Error) {\n terminationError = error\n nestedReject(error)\n }\n const requestMessage = await new Promise>(\n (resolve, reject) => {\n nestedReject = reject\n this.createRequestMessage(path, body, options, resolve, wrapReject)\n }\n )\n if (requestMessage.signal?.addEventListener) {\n ;(requestMessage.signal as AbortSignal).addEventListener('abort', () => {\n wrapReject(new AbortError())\n })\n }\n const response = await new Promise(\n (resolve, reject) => {\n nestedReject = reject\n const req = this.requestApi(requestMessage, resolve)\n req.on('timeout', () => wrapReject(new RequestTimedOutError()))\n req.on('error', wrapReject)\n\n req.write(requestMessage.body)\n req.end()\n }\n )\n const res = await new Promise((resolve, reject) => {\n nestedReject = reject\n this._prepareResponse(response, resolve, wrapReject)\n })\n for await (const chunk of res) {\n if (terminationError) {\n throw terminationError\n }\n yield chunk\n }\n }\n /**\n * Creates configuration for a specific request.\n *\n * @param path - API path starting with '/' and containing also query parameters\n * @param body - request body, will be utf-8 encoded\n * @returns a configuration object that is suitable for making the request\n */\n private createRequestMessage(\n path: string,\n body: string,\n sendOptions: SendOptions,\n resolve: (req: http.RequestOptions) => void,\n reject: (err: Error) => void\n ): void {\n const bodyBuffer = Buffer.from(body, 'utf-8')\n const headers: {[key: string]: any} = {\n 'content-type': 'application/json; charset=utf-8',\n ...this.headers,\n }\n if (this.token) {\n headers.authorization = 'Token ' + this.token\n }\n const options: {[key: string]: any} = {\n ...this.defaultOptions,\n path: this.contextPath + path,\n method: sendOptions.method,\n headers: {\n ...headers,\n ...sendOptions.headers,\n },\n }\n if (sendOptions.signal) {\n options.signal = sendOptions.signal\n }\n if (\n sendOptions.gzipThreshold !== undefined &&\n sendOptions.gzipThreshold < bodyBuffer.length\n ) {\n zlib.gzip(bodyBuffer, (err, res) => {\n /* istanbul ignore next - hard to simulate failure, manually reviewed */\n if (err) {\n return reject(err)\n }\n options.headers['content-encoding'] = 'gzip'\n options.body = res\n resolve(options)\n })\n return\n }\n options.body = bodyBuffer\n options.headers['content-length'] = options.body.length\n resolve(options)\n }\n\n private _prepareResponse(\n res: http.IncomingMessage,\n resolve: (res: Readable) => void,\n reject: (err: Error) => void\n ) {\n res.on('aborted', () => {\n reject(new AbortError())\n })\n res.on('error', reject)\n /* istanbul ignore next statusCode is optional in http.IncomingMessage */\n const statusCode = res.statusCode ?? 600\n const contentEncoding = res.headers['content-encoding']\n let responseData\n if (contentEncoding === 'gzip') {\n responseData = zlib.createGunzip(zlibOptions)\n responseData = pipeline(res, responseData, (e) => e && reject(e))\n } else {\n responseData = res\n }\n if (statusCode >= 300) {\n let body = ''\n const isJson = String(res.headers['content-type']).startsWith(\n 'application/json'\n )\n responseData.on('data', (s) => {\n body += s.toString()\n if (!isJson && body.length > 1000) {\n body = body.slice(0, 1000)\n res.resume()\n }\n })\n responseData.on('end', () => {\n if (body === '' && !!res.headers['x-influxdb-error']) {\n body = res.headers['x-influxdb-error'].toString()\n }\n reject(\n new HttpError(\n statusCode,\n res.statusMessage,\n body,\n res.headers['retry-after'],\n res.headers['content-type']\n )\n )\n })\n } else {\n resolve(responseData)\n }\n }\n\n private _request(\n requestMessage: {[key: string]: any},\n cancellable: CancellableImpl,\n callbacks?: Partial>\n ): void {\n const listeners = completeCommunicationObserver(callbacks)\n if (cancellable.isCancelled()) {\n listeners.complete()\n return\n }\n if (requestMessage.signal?.addEventListener) {\n ;(requestMessage.signal as AbortSignal).addEventListener('abort', () => {\n listeners.error(new AbortError())\n })\n }\n const req = this.requestApi(requestMessage, (res: http.IncomingMessage) => {\n /* istanbul ignore next - hard to simulate failure, manually reviewed */\n if (cancellable.isCancelled()) {\n res.resume()\n listeners.complete()\n return\n }\n listeners.responseStarted(res.headers, res.statusCode)\n this._prepareResponse(\n res,\n (responseData) => {\n responseData.on('data', (data) => {\n if (cancellable.isCancelled()) {\n res.resume()\n } else {\n if (listeners.next(data) === false) {\n // pause processing, the consumer signalizes that\n // it is not able to receive more data\n if (!listeners.useResume) {\n listeners.error(\n new Error('Unable to pause, useResume is not configured!')\n )\n res.resume()\n return\n }\n res.pause()\n const resume = () => {\n res.resume()\n }\n cancellable.resume = resume\n listeners.useResume(resume)\n }\n }\n })\n responseData.on('end', listeners.complete)\n },\n listeners.error\n )\n })\n // Support older Nodes which don't allow `timeout` in the\n // request options\n /* istanbul ignore else support older node versions */\n if (typeof req.setTimeout === 'function' && requestMessage.timeout) {\n req.setTimeout(requestMessage.timeout)\n }\n\n req.on('timeout', () => {\n listeners.error(new RequestTimedOutError())\n })\n req.on('error', (error) => {\n listeners.error(error)\n })\n\n /* istanbul ignore else support older node versions */\n if (requestMessage.body) {\n req.write(requestMessage.body)\n }\n req.end()\n }\n}\nexport default NodeHttpTransport\n","import {Buffer} from 'buffer'\nimport {ChunkCombiner} from '../../results'\n\nconst nodeChunkCombiner: ChunkCombiner = {\n concat(first: Uint8Array, second: Uint8Array): Uint8Array {\n return Buffer.concat([first, second])\n },\n toUtf8String(chunk: Uint8Array, start: number, end: number): string {\n return (chunk as Buffer).toString('utf-8', start, end)\n },\n copy(chunk: Uint8Array, start: number, end: number): Uint8Array {\n const retVal = Buffer.allocUnsafe(end - start)\n ;(chunk as Buffer).copy(retVal, 0, start, end)\n return retVal\n },\n}\n\nexport default nodeChunkCombiner\n","import {CommunicationObserver, Headers} from '../results'\n\ntype CompleteObserver = Omit<\n Required>,\n 'useCancellable' | 'useResume'\n> &\n Pick, 'useResume' | 'useCancellable'>\n\nexport default function completeCommunicationObserver(\n callbacks: Partial> = {}\n): CompleteObserver {\n let state = 0\n const retVal: CompleteObserver = {\n next: (data: any): void | boolean => {\n if (\n state === 0 &&\n callbacks.next &&\n data !== null &&\n data !== undefined\n ) {\n return callbacks.next(data)\n }\n },\n error: (error: Error): void => {\n /* istanbul ignore else propagate error at most once */\n if (state === 0) {\n state = 1\n /* istanbul ignore else safety check */\n if (callbacks.error) callbacks.error(error)\n }\n },\n complete: (): void => {\n if (state === 0) {\n state = 2\n /* istanbul ignore else safety check */\n if (callbacks.complete) callbacks.complete()\n }\n },\n responseStarted: (headers: Headers, statusCode?: number): void => {\n if (callbacks.responseStarted)\n callbacks.responseStarted(headers, statusCode)\n },\n }\n if (callbacks.useCancellable) {\n retVal.useCancellable = callbacks.useCancellable.bind(callbacks)\n }\n if (callbacks.useResume) {\n retVal.useResume = callbacks.useResume.bind(callbacks)\n }\n return retVal\n}\n","export const CLIENT_LIB_VERSION = '1.33.1'\n","import {Observable} from '../observable'\nimport QueryApi, {QueryOptions} from '../QueryApi'\nimport {Transport} from '../transport'\nimport {\n CommunicationObserver,\n FluxResultObserver,\n FluxTableMetaData,\n Row,\n AnnotatedCSVResponse,\n IterableResultExecutor,\n} from '../results'\nimport {ParameterizedQuery} from '../query/flux'\nimport {APIExecutor} from '../results/ObservableQuery'\n\nconst DEFAULT_dialect: any = {\n header: true,\n delimiter: ',',\n quoteChar: '\"',\n commentPrefix: '#',\n annotations: ['datatype', 'group', 'default'],\n}\n\nexport class QueryApiImpl implements QueryApi {\n private options: QueryOptions\n constructor(\n private transport: Transport,\n private createCSVResponse: (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ) => AnnotatedCSVResponse,\n org: string | QueryOptions\n ) {\n this.options = typeof org === 'string' ? {org} : org\n }\n\n with(options: Partial): QueryApi {\n return new QueryApiImpl(this.transport, this.createCSVResponse, {\n ...this.options,\n ...options,\n })\n }\n\n response(query: string | ParameterizedQuery): AnnotatedCSVResponse {\n const {org, type, gzip, headers} = this.options\n const path = `/api/v2/query?org=${encodeURIComponent(org)}`\n const body = JSON.stringify(\n this.decorateRequest({\n query: query.toString(),\n dialect: DEFAULT_dialect,\n type,\n })\n )\n const options = {\n method: 'POST',\n headers: {\n 'content-type': 'application/json; encoding=utf-8',\n 'accept-encoding': gzip ? 'gzip' : 'identity',\n ...headers,\n },\n }\n return this.createCSVResponse(\n (consumer) => this.transport.send(path, body, options, consumer),\n () => this.transport.iterate(path, body, options)\n )\n }\n\n iterateLines(query: string | ParameterizedQuery): AsyncIterable {\n return this.response(query).iterateLines()\n }\n iterateRows(query: string | ParameterizedQuery): AsyncIterable {\n return this.response(query).iterateRows()\n }\n lines(query: string | ParameterizedQuery): Observable {\n return this.response(query).lines()\n }\n\n rows(query: string | ParameterizedQuery): Observable {\n return this.response(query).rows()\n }\n\n queryLines(\n query: string | ParameterizedQuery,\n consumer: CommunicationObserver\n ): void {\n return this.response(query).consumeLines(consumer)\n }\n\n queryRows(\n query: string | ParameterizedQuery,\n consumer: FluxResultObserver\n ): void {\n return this.response(query).consumeRows(consumer)\n }\n\n collectRows(\n query: string | ParameterizedQuery,\n rowMapper?: (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined\n ): Promise> {\n return this.response(query).collectRows(rowMapper)\n }\n\n collectLines(query: string | ParameterizedQuery): Promise> {\n return this.response(query).collectLines()\n }\n\n queryRaw(query: string | ParameterizedQuery): Promise {\n const {org, type, gzip, headers} = this.options\n return this.transport.request(\n `/api/v2/query?org=${encodeURIComponent(org)}`,\n JSON.stringify(\n this.decorateRequest({\n query: query.toString(),\n dialect: DEFAULT_dialect,\n type,\n })\n ),\n {\n method: 'POST',\n headers: {\n accept: 'text/csv',\n 'accept-encoding': gzip ? 'gzip' : 'identity',\n 'content-type': 'application/json; encoding=utf-8',\n ...headers,\n },\n }\n )\n }\n\n private decorateRequest(request: any): any {\n if (typeof this.options.now === 'function') {\n request.now = this.options.now()\n }\n // https://docs.influxdata.com/influxdb/latest/api/#operation/PostQuery requires type\n request.type = this.options.type ?? 'flux'\n return request\n }\n}\n\nexport default QueryApiImpl\n","import {\n CommunicationObserver,\n FluxResultObserver,\n FluxTableMetaData,\n Row,\n linesToTables,\n ChunkCombiner,\n chunksToLines,\n chunksToLinesIterable,\n linesToRowsIterable,\n} from '../results'\nimport {Observable} from '../observable'\nimport {\n AnnotatedCSVResponse,\n IterableResultExecutor,\n} from './AnnotatedCSVResponse'\nimport ObservableQuery, {APIExecutor} from './ObservableQuery'\n\nexport function defaultRowMapping(\n values: string[],\n tableMeta: FluxTableMetaData\n): Record {\n return tableMeta.toObject(values)\n}\n\n/**\n * AnnotatedCsvResponseImpl is an implementation AnnotatedCsvResponse\n * that uses the supplied executor to supply a response data stream.\n */\nexport class AnnotatedCSVResponseImpl implements AnnotatedCSVResponse {\n constructor(\n private executor: APIExecutor,\n private iterableResultExecutor: IterableResultExecutor,\n private chunkCombiner: ChunkCombiner\n ) {}\n iterateLines(): AsyncIterable {\n return chunksToLinesIterable(this.iterableResultExecutor())\n }\n iterateRows(): AsyncIterable {\n return linesToRowsIterable(\n chunksToLinesIterable(this.iterableResultExecutor())\n )\n }\n lines(): Observable {\n return new ObservableQuery(this.executor, (observer) =>\n chunksToLines(observer, this.chunkCombiner)\n )\n }\n\n rows(): Observable {\n return new ObservableQuery(this.executor, (observer) => {\n return chunksToLines(\n linesToTables({\n next(values, tableMeta) {\n observer.next({values, tableMeta})\n },\n error(e) {\n observer.error(e)\n },\n complete() {\n observer.complete()\n },\n }),\n this.chunkCombiner\n )\n })\n }\n\n consumeLines(consumer: CommunicationObserver): void {\n this.executor(chunksToLines(consumer, this.chunkCombiner))\n }\n\n consumeRows(consumer: FluxResultObserver): void {\n this.executor(chunksToLines(linesToTables(consumer), this.chunkCombiner))\n }\n\n collectRows(\n rowMapper: (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined = defaultRowMapping as (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined\n ): Promise> {\n const retVal: Array = []\n return new Promise((resolve, reject) => {\n this.consumeRows({\n next(values: string[], tableMeta: FluxTableMetaData): void {\n const toAdd = rowMapper.call(this, values, tableMeta)\n if (toAdd !== undefined) {\n retVal.push(toAdd)\n }\n },\n error(error: Error): void {\n reject(error)\n },\n complete(): void {\n resolve(retVal)\n },\n })\n })\n }\n\n collectLines(): Promise> {\n const retVal: Array = []\n return new Promise((resolve, reject) => {\n this.consumeLines({\n next(line: string): void {\n retVal.push(line)\n },\n error(error: Error): void {\n reject(error)\n },\n complete(): void {\n resolve(retVal)\n },\n })\n })\n }\n}\n","import WriteApi from './WriteApi'\nimport {ClientOptions, WriteOptions, WritePrecisionType} from './options'\nimport WriteApiImpl from './impl/WriteApiImpl'\nimport {IllegalArgumentError} from './errors'\nimport {Transport} from './transport'\n// replaced by ./impl/browser/FetchTransport in browser builds\nimport TransportImpl from './impl/node/NodeHttpTransport'\nimport QueryApi, {QueryOptions} from './QueryApi'\nimport QueryApiImpl from './impl/QueryApiImpl'\nimport {\n AnnotatedCSVResponse,\n APIExecutor,\n IterableResultExecutor,\n} from './results'\nimport {AnnotatedCSVResponseImpl} from './results/AnnotatedCSVResponseImpl'\n\n/**\n * InfluxDB entry point that configures communication with InfluxDB server\n * and provide APIs to write and query data.\n */\nexport default class InfluxDB {\n private _options: ClientOptions\n readonly transport: Transport\n readonly processCSVResponse: (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ) => AnnotatedCSVResponse\n\n /**\n * Creates influxdb client options from an options object or url.\n * @param options - client options\n */\n constructor(options: ClientOptions | string) {\n if (typeof options === 'string') {\n this._options = {url: options}\n } else if (options !== null && typeof options === 'object') {\n this._options = options\n } else {\n throw new IllegalArgumentError('No url or configuration specified!')\n }\n const url = this._options.url\n if (typeof url !== 'string')\n throw new IllegalArgumentError('No url specified!')\n if (url.endsWith('/')) this._options.url = url.substring(0, url.length - 1)\n this.transport = this._options.transport ?? new TransportImpl(this._options)\n this.processCSVResponse = (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ): AnnotatedCSVResponse =>\n new AnnotatedCSVResponseImpl(\n executor,\n iterableResultExecutor,\n this.transport.chunkCombiner\n )\n }\n\n /**\n * Creates WriteApi for the supplied organization and bucket. BEWARE that returned instances must be closed\n * in order to flush the remaining data and close already scheduled retry executions.\n *\n * @remarks\n * Use {@link WriteOptions} to customize retry strategy options, data chunking\n * and flushing options. See {@link DEFAULT_WriteOptions} to see the defaults.\n *\n * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/write.mjs | write example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/writeAdvanced.mjs | writeAdvanced example},\n * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example}.\n *\n * @param org - Specifies the destination organization for writes. Takes either the ID or Name interchangeably.\n * @param bucket - The destination bucket for writes.\n * @param precision - Timestamp precision for line items.\n * @param writeOptions - Custom write options.\n * @returns WriteApi instance\n */\n getWriteApi(\n org: string,\n bucket: string,\n precision: WritePrecisionType = 'ns',\n writeOptions?: Partial\n ): WriteApi {\n return new WriteApiImpl(\n this.transport,\n org,\n bucket,\n precision,\n writeOptions ?? this._options.writeOptions\n )\n }\n\n /**\n * Creates QueryApi for the supplied organization .\n *\n * @remarks\n * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/query.ts | query.ts example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/queryWithParams.mjs | queryWithParams.mjs example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/rxjs-query.ts | rxjs-query.ts example},\n * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example},\n *\n * @param org - organization or query options\n * @returns QueryApi instance\n */\n getQueryApi(org: string | QueryOptions): QueryApi {\n return new QueryApiImpl(this.transport, this.processCSVResponse, org)\n }\n}\n"],"mappings":"AA2CO,SAASA,GAA2C,CACzD,IAAMC,EAAU,IAAI,YAAY,OAAO,EACvC,MAAO,CACL,OAAOC,EAAmBC,EAAgC,CACxD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ombiner","decoder","first","second","retVal","chunk","start","end","chunksToLines","target","chunkCombiner","chunks","createTextDecoderCombiner","previous","finished","quoted","paused","resumeChunks","bufferReceived","chunk","index","start","c","end","retVal","e","error","cancellable","x","chunksToLinesIterable","source","chunkCombiner","chunks","createTextDecoderCombiner","previous","quoted","chunk","index","start","c","end","LineSplitter","val","line","quoteCount","startIndex","values","count","i","c","start","end","identity","x","typeSerializers","FluxTableColumnImpl","row","_a","val","UNKNOWN_COLUMN","newFluxTableColumn","createFluxTableColumn","object","_b","retVal","retriableStatusCodes","isStatusCodeRetriable","statusCode","IllegalArgumentError","message","HttpError","statusMessage","body","retryAfter","contentType","e","RETRY_CODES","canRetryHttpCall","error","getRetryDelay","retryJitter","retVal","RequestTimedOutError","AbortError","serializeDateTimeAsDate","typeSerializers","x","serializeDateTimeAsNumber","serializeDateTimeAsString","FluxTableMetaDataImpl","columns","col","i","label","errorOnMissingColumn","IllegalArgumentError","UNKNOWN_COLUMN","row","acc","column","createFluxTableMetaData","linesToTables","consumer","splitter","LineSplitter","columns","expectMeta","firstColumnIndex","lastMeta","retVal","error","line","values","size","i","newFluxTableColumn","createFluxTableMetaData","linesToRowsIterable","source","splitter","LineSplitter","columns","expectMeta","firstColumnIndex","lastMeta","line","values","size","i","newFluxTableColumn","createFluxTableMetaData","stringToLines","source","target","quoted","start","index","c","end","symbolObservable","QuerySubscription","observer","executor","value","e","c","_a","noop","completeObserver","next","error","complete","ObservableQuery","decorator","observerOrNext","symbolObservable","DEFAULT_ConnectionOptions","DEFAULT_RetryDelayStrategyOptions","DEFAULT_WriteOptions","createEscaper","characters","replacements","value","retVal","from","i","found","createQuotedEscaper","escaper","escape","zeroPadding","useHrTime","useProcessHrtime","use","startHrMillis","startHrTime","lastMillis","stepsInMillis","nanos","hrTime","millis","micros","seconds","currentTime","dateToProtocolTimestamp","d","convertTimeToNanos","value","consoleLogger","message","error","provider","Log","setLogger","logger","previous","FLUX_VALUE","FluxParameter","fluxValue","isFluxParameterLike","value","sanitizeString","retVal","i","prepareRetVal","c","fluxString","sanitizeFloat","val","strVal","hasDot","fluxFloat","sanitizeInteger","negative","fluxInteger","sanitizeDateTime","fluxDateTime","fluxDuration","sanitizeRegExp","fluxRegExp","fluxBool","fluxExpression","toFluxValue","flux","strings","values","parts","partIndex","text","sanitized","Point","measurementName","name","value","val","strVal","code","escape","settings","fieldsLine","x","tagsLine","tags","time","convertTimeToNanos","line","RetryStrategyImpl","options","DEFAULT_RetryDelayStrategyOptions","error","failedAttempts","delay","getRetryDelay","nextDelay","i","createRetryDelayStrategy","findShrinkCandidate","first","parent","found","currentParent","RetryBuffer","maxLines","retryLines","onShrink","lines","retryCount","delay","expires","retryTime","origSize","newSize","Log","toAdd","current","toRetry","utf8Length","s","retVal","i","code","WriteBuffer","maxChunkRecords","maxBatchBytes","flushFn","scheduleSend","record","size","utf8Length","_e","lines","retVal","WriteApiImpl","transport","org","bucket","precision","writeOptions","DEFAULT_WriteOptions","currentTime","dateToProtocolTimestamp","scheduleNextSend","createRetryDelayStrategy","RetryBuffer","retryAttempts","expires","self","failedAttempts","error","onRetry","Log","resolve","reject","responseStatusCode","callbacks","_headers","statusCode","HttpError","message","records","i","point","line","points","withRetryBuffer","remaining","tags","value","parse","http","https","Buffer","Buffer","nodeChunkCombiner","first","second","chunk","start","end","retVal","nodeChunkCombiner_default","zlib","completeCommunicationObserver","callbacks","state","retVal","data","error","headers","statusCode","CLIENT_LIB_VERSION","pipeline","zlibOptions","zlib","emptyBuffer","Buffer","CancellableImpl","NodeHttpTransport","connectionOptions","nodeChunkCombiner_default","_a","_b","_c","_d","_e","_f","_g","_url","proxyUrl","token","transportOptions","nodeSupportedOptions","url","parse","DEFAULT_ConnectionOptions","key","Log","CLIENT_LIB_VERSION","path","body","options","callbacks","cancellable","message","err","responseStarted","buffer","contentType","responseStatusCode","resolve","reject","headers","statusCode","data","responseType","e","terminationError","nestedReject","wrapReject","error","requestMessage","AbortError","response","req","RequestTimedOutError","res","chunk","sendOptions","bodyBuffer","contentEncoding","responseData","isJson","s","HttpError","listeners","completeCommunicationObserver","resume","NodeHttpTransport_default","DEFAULT_dialect","QueryApiImpl","transport","createCSVResponse","org","options","query","type","gzip","headers","path","body","consumer","rowMapper","request","_a","QueryApiImpl_default","defaultRowMapping","values","tableMeta","AnnotatedCSVResponseImpl","executor","iterableResultExecutor","chunkCombiner","chunksToLinesIterable","linesToRowsIterable","ObservableQuery","observer","chunksToLines","linesToTables","e","consumer","rowMapper","retVal","resolve","reject","toAdd","error","line","InfluxDB","options","_a","IllegalArgumentError","url","NodeHttpTransport_default","executor","iterableResultExecutor","AnnotatedCSVResponseImpl","org","bucket","precision","writeOptions","WriteApiImpl","QueryApiImpl_default"]} \ No newline at end of file diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js b/software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js new file mode 100644 index 0000000..1c0e369 --- /dev/null +++ b/software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js @@ -0,0 +1,6 @@ +"use strict";var influxdb=(()=>{var k=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var Pe=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},Fe=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of De(e))!Ee.call(r,i)&&i!==t&&k(r,i,{get:()=>e[i],enumerable:!(n=Ae(e,i))||n.enumerable});return r};var Le=r=>Fe(k({},"__esModule",{value:!0}),r);var nt={};Pe(nt,{AbortError:()=>x,DEFAULT_ConnectionOptions:()=>We,DEFAULT_RetryDelayStrategyOptions:()=>Y,DEFAULT_WriteOptions:()=>Z,FLUX_VALUE:()=>D,HttpError:()=>m,IllegalArgumentError:()=>y,InfluxDB:()=>U,LineSplitter:()=>b,Log:()=>p,Point:()=>ue,RequestTimedOutError:()=>v,UNKNOWN_COLUMN:()=>Q,canRetryHttpCall:()=>Be,chunksToLines:()=>R,chunksToLinesIterable:()=>M,consoleLogger:()=>Te,convertTimeToNanos:()=>se,createFluxTableColumn:()=>Ie,createFluxTableMetaData:()=>A,createTextDecoderCombiner:()=>g,currentTime:()=>ne,dateToProtocolTimestamp:()=>ie,escape:()=>w,flux:()=>et,fluxBool:()=>Ze,fluxDateTime:()=>Ge,fluxDuration:()=>Ke,fluxExpression:()=>oe,fluxFloat:()=>qe,fluxInteger:()=>Je,fluxRegExp:()=>Ye,fluxString:()=>je,getRetryDelay:()=>j,isStatusCodeRetriable:()=>pe,linesToRowsIterable:()=>J,linesToTables:()=>V,newFluxTableColumn:()=>S,sanitizeFloat:()=>ae,sanitizeInteger:()=>le,serializeDateTimeAsDate:()=>Me,serializeDateTimeAsNumber:()=>_e,serializeDateTimeAsString:()=>Ve,setLogger:()=>Ne,stringToLines:()=>ze,symbolObservable:()=>X,toFluxValue:()=>H,typeSerializers:()=>C,useProcessHrtime:()=>we});function g(){let r=new TextDecoder("utf-8");return{concat(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n},copy(e,t,n){let i=new Uint8Array(n-t);return i.set(e.subarray(t,n)),i},toUtf8String(e,t,n){return r.decode(e.subarray(t,n))}}}function R(r,e){let t=e!=null?e:g(),n,i=!1,s=!1,o=!1,a;function f(l){let c,d=0;for(n?(c=l.length===0?0:n.length,l=t.concat(n,l)):c=0;c0&&l[c-1]===13?c-1:c;if(i)return;if(o=r.next(t.toUtf8String(l,d,$))===!1,d=c+1,o)break}}else T===34&&(s=!s);c++}if(d{o=!1,f(new Uint8Array(0))});return}u.error(new Error("Unable to pause, useResume is not configured!")),o=!1}a&&(a(),a=void 0)}let u={next(l){if(!i)try{return f(l),!o}catch(c){this.error(c)}return!0},error(l){i||(i=!0,r.error(l))},complete(){i||(n&&r.next(t.toUtf8String(n,0,n.length)),i=!0,r.complete())}};return r.useCancellable&&(u.useCancellable=l=>{r.useCancellable&&r.useCancellable({cancel(){l.cancel(),n=void 0,u.complete()},isCancelled(){return l.isCancelled()}})}),r.useResume&&(u.useResume=l=>{a=l}),u}async function*M(r,e){let t=e!=null?e:g(),n,i=!1;for await(let s of r){let o,a=0;for(n?(o=n.length,s=t.concat(n,s)):o=0;o0&&s[o-1]===13?o-1:o;yield t.toUtf8String(s,a,u),a=o+1}}else f===34&&(i=!i);o++}ar,C={boolean:r=>r===""?null:r==="true",unsignedLong:r=>r===""?null:+r,long:r=>r===""?null:+r,double(r){switch(r){case"":return null;case"+Inf":return Number.POSITIVE_INFINITY;case"-Inf":return Number.NEGATIVE_INFINITY;default:return+r}},string:N,base64Binary:N,duration:r=>r===""?null:r,"dateTime:RFC3339":r=>r===""?null:r},_=class{get(e){var n;let t=e[this.index];return(t===""||t===void 0)&&this.defaultValue&&(t=this.defaultValue),((n=C[this.dataType])!=null?n:N)(t)}},Q=Object.freeze({label:"",dataType:"",group:!1,defaultValue:"",index:Number.MAX_SAFE_INTEGER,get:()=>{}});function S(){return new _}function Ie(r){var t,n;let e=new _;return e.label=String(r.label),e.dataType=r.dataType,e.group=Boolean(r.group),e.defaultValue=(t=r.defaultValue)!=null?t:"",e.index=(n=r.index)!=null?n:0,e}var Ue=[404,408,425,429,500,502,503,504];function pe(r){return Ue.includes(r)}var y=class extends Error{constructor(e){super(e),this.name="IllegalArgumentError",Object.setPrototypeOf(this,y.prototype)}},m=class extends Error{constructor(t,n,i,s,o,a){super();this.statusCode=t;this.statusMessage=n;this.body=i;this.contentType=o;if(Object.setPrototypeOf(this,m.prototype),a)this.message=a;else if(i){if(o!=null&&o.startsWith("application/json"))try{this.json=JSON.parse(i),this.message=this.json.message,this.code=this.json.code}catch(f){}this.message||(this.message=`${t} ${n} : ${i}`)}else this.message=`${t} ${n}`;this.name="HttpError",this.setRetryAfter(s)}setRetryAfter(t){typeof t=="string"?/^[0-9]+$/.test(t)?this._retryAfter=parseInt(t):this._retryAfter=0:this._retryAfter=0}canRetry(){return pe(this.statusCode)}retryAfter(){return this._retryAfter}},$e=["ECONNRESET","ENOTFOUND","ESOCKETTIMEDOUT","ETIMEDOUT","ECONNREFUSED","EHOSTUNREACH","EPIPE"];function Be(r){if(r){if(typeof r.canRetry=="function")return!!r.canRetry();if(r.code&&$e.includes(r.code))return!0}else return!1;return!1}function j(r,e){if(r){let t;return typeof r.retryAfter=="function"?r.retryAfter():(t=0,e&&e>0?t+Math.round(Math.random()*e):t)}else return 0}var v=class extends Error{constructor(){super(),Object.setPrototypeOf(this,v.prototype),this.name="RequestTimedOutError",this.message="Request timed out"}canRetry(){return!0}retryAfter(){return 0}},x=class extends Error{constructor(){super(),this.name="AbortError",Object.setPrototypeOf(this,x.prototype),this.message="Response aborted"}canRetry(){return!0}retryAfter(){return 0}};function Me(){C["dateTime:RFC3339"]=r=>r===""?null:new Date(Date.parse(r))}function _e(){C["dateTime:RFC3339"]=r=>r===""?null:Date.parse(r)}function Ve(){C["dateTime:RFC3339"]=r=>r===""?null:r}var q=class{constructor(e){e.forEach((t,n)=>t.index=n),this.columns=e}column(e,t=!0){for(let n=0;n0&&r.charCodeAt(i-1)===13?i-1:i;e.next(r.substring(n,o)),n=i+1}}else s===34&&(t=!t);i++}ntypeof Symbol=="function"&&Symbol.observable||"@@observable")();var K=class{constructor(e,t){this.isClosed=!1;try{t({next:n=>{e.next(n)},error:n=>{this.isClosed=!0,e.error(n)},complete:()=>{this.isClosed=!0,e.complete()},useCancellable:n=>{this.cancellable=n}})}catch(n){this.isClosed=!0,e.error(n)}}get closed(){return this.isClosed}unsubscribe(){var e;(e=this.cancellable)==null||e.cancel(),this.isClosed=!0}};function G(){}function He(r){let{next:e,error:t,complete:n}=r;return{next:e?e.bind(r):G,error:t?t.bind(r):G,complete:n?n.bind(r):G}}var O=class{constructor(e,t){this.executor=e;this.decorator=t}subscribe(e,t,n){let i=He(typeof e!="object"||e===null?{next:e,error:t,complete:n}:e);return new K(this.decorator(i),this.executor)}[X](){return this}};Symbol.observable;var We={timeout:1e4},Y={retryJitter:200,minRetryDelay:5e3,maxRetryDelay:125e3,exponentialBase:5,randomRetry:!0},Z={batchSize:1e3,maxBatchBytes:5e7,flushInterval:6e4,writeFailed:function(){},writeSuccess:function(){},writeRetrySkipped:function(){},maxRetries:5,maxRetryTime:18e4,maxBufferLines:32e3,retryJitter:200,minRetryDelay:5e3,maxRetryDelay:125e3,exponentialBase:2,gzipThreshold:1e3,randomRetry:!0};function ee(r,e){return function(t){let n="",i=0,s=0;for(;s=0&&(n+=t.substring(i,s),n+=e[o],i=s+1),s++}return i==0?t:(i'"'+t(n)+'"'}var w={measurement:ee(`, +\r `,["\\,","\\ ","\\n","\\r","\\t"]),quoted:ke('"\\',['\\"',"\\\\"]),tag:ee(`, = +\r `,["\\,","\\ ","\\=","\\n","\\r","\\t"])};var xe="000000000";function we(r){return!1}we(!0);var he=Date.now(),te=0;function re(){{let r=Date.now();r!==he?(he=r,te=0):te++;let e=String(te);return String(r)+xe.substr(0,6-e.length)+e}}function ye(){return String(Date.now())+xe.substr(0,3)}function ge(){return String(Date.now())}function be(){return String(Math.floor(Date.now()/1e3))}var ne={s:be,ms:ge,us:ye,ns:re,seconds:be,millis:ge,micros:ye,nanos:re},ie={s:r=>`${Math.floor(r.getTime()/1e3)}`,ms:r=>`${r.getTime()}`,us:r=>`${r.getTime()}000`,ns:r=>`${r.getTime()}000000`};function se(r){return r===void 0?re():typeof r=="string"?r.length>0?r:void 0:r instanceof Date?`${r.getTime()}000000`:String(typeof r=="number"?Math.floor(r):r)}var Te={error(r,e){console.error("ERROR: "+r,e||"")},warn(r,e){console.warn("WARN: "+r,e||"")}},z=Te,p={error(r,e){z.error(r,e)},warn(r,e){z.warn(r,e)}};function Ne(r){let e=z;return z=r,e}var D=Symbol("FLUX_VALUE"),h=class{constructor(e){this.fluxValue=e}toString(){return this.fluxValue}[D](){return this.fluxValue}};function Qe(r){return typeof r=="object"&&typeof r[D]=="function"}function E(r){if(r==null)return"";r=r.toString();let e,t=0;function n(){e===void 0&&(e=r.substring(0,t))}for(;t="0"&&i<="9"||i=="-")){if(i==="."){n=!0;continue}return`float(v: "${t}")`}return n?t:t+".0"}function qe(r){return new h(ae(r))}function le(r){let e=String(r),t=e.startsWith("-"),n=t?e.substring(1):e;if(n.length===0||n.length>19)throw new Error(`not a flux integer: ${e}`);for(let i of n)if(i<"0"||i>"9")throw new Error(`not a flux integer: ${e}`);if(n.length===19){if(t&&n>"9223372036854775808")throw new Error(`flux integer out of bounds: ${e}`);if(!t&&n>"9223372036854775807")throw new Error(`flux integer out of bounds: ${e}`)}return e}function Je(r){return new h(le(r))}function Xe(r){return`time(v: "${E(r)}")`}function Ge(r){return new h(Xe(r))}function Ke(r){return new h(`duration(v: "${E(r)}")`)}function Re(r){return r instanceof RegExp?r.toString():new RegExp(r).toString()}function Ye(r){return new h(Re(r))}function Ze(r){return r==="true"||r==="false"?new h(r):new h((!!r).toString())}function oe(r){return new h(String(r))}function H(r){if(r===void 0)return"";if(r===null)return"null";if(typeof r=="boolean")return r.toString();if(typeof r=="string")return`"${E(r)}"`;if(typeof r=="number")return Number.isSafeInteger(r)?le(r):ae(r);if(typeof r=="object"){if(typeof r[D]=="function")return r[D]();if(r instanceof Date)return r.toISOString();if(r instanceof RegExp)return Re(r);if(Array.isArray(r))return`[${r.map(H).join(",")}]`}else if(typeof r=="bigint")return`${r}.0`;return H(r.toString())}function et(r,...e){if(r.length==1&&e.length===0)return oe(r[0]);let t=new Array(r.length+e.length),n=0;for(let i=0;i=9223372036854776e3)throw new Error(`invalid integer value for field '${e}': '${t}'!`);return this.fields[e]=`${Math.floor(n)}i`,this}uintField(e,t){if(typeof t=="number"){if(isNaN(t)||t<0||t>Number.MAX_SAFE_INTEGER)throw new Error(`uint value for field '${e}' out of range: ${t}`);this.fields[e]=`${Math.floor(t)}u`}else{let n=String(t);for(let i=0;i57)throw new Error(`uint value has an unsupported character at pos ${i}: ${t}`)}if(n.length>20||n.length===20&&n.localeCompare("18446744073709551615")>0)throw new Error(`uint value for field '${e}' out of range: ${n}`);this.fields[e]=`${n}u`}return this}floatField(e,t){let n;if(typeof t=="number"?n=t:n=parseFloat(t),!isFinite(n))throw new Error(`invalid float value for field '${e}': ${t}`);return this.fields[e]=String(n),this}stringField(e,t){return t!=null&&(typeof t!="string"&&(t=String(t)),this.fields[e]=w.quoted(t)),this}timestamp(e){return this.time=e,this}toLineProtocol(e){if(!this.name)return;let t="";if(Object.keys(this.fields).sort().forEach(o=>{if(o){let a=this.fields[o];t.length>0&&(t+=","),t+=`${w.tag(o)}=${a}`}}),t.length===0)return;let n="",i=e&&e.defaultTags?{...e.defaultTags,...this.tags}:this.tags;Object.keys(i).sort().forEach(o=>{if(o){let a=i[o];a&&(n+=",",n+=`${w.tag(o)}=${w.tag(a)}`)}});let s=this.time;return e&&e.convertTime?s=e.convertTime(s):s=se(s),`${w.measurement(this.name)}${n} ${t}${s!==void 0?" "+s:""}`}toString(){let e=this.toLineProtocol(void 0);return e||`invalid point: ${JSON.stringify(this,void 0)}`}};var fe=class{constructor(e){this.options={...Y,...e},this.success()}nextDelay(e,t){let n=j(e);if(n&&n>0)return n+Math.round(Math.random()*this.options.retryJitter);if(t&&t>0){if(this.options.randomRetry){let s=Math.max(this.options.minRetryDelay,1),o=s*this.options.exponentialBase;for(let a=1;a=this.options.maxRetryDelay){o=this.options.maxRetryDelay;break}return s+Math.round(Math.random()*(o-s)+Math.random()*this.options.retryJitter)}let i=Math.max(this.options.minRetryDelay,1);for(let s=1;s=this.options.maxRetryDelay){i=this.options.maxRetryDelay;break}return i+Math.round(Math.random()*this.options.retryJitter)}else this.currentDelay?this.currentDelay=Math.min(Math.max(this.currentDelay*this.options.exponentialBase,1)+Math.round(Math.random()*this.options.retryJitter),this.options.maxRetryDelay):this.currentDelay=this.options.minRetryDelay+Math.round(Math.random()*this.options.retryJitter);return this.currentDelay}success(){this.currentDelay=void 0}};function Ce(r){return new fe(r)}function tt(r){let e,t=r,n=r;for(;n.next;)n.next.expires{}){this.maxLines=e;this.retryLines=t;this.onShrink=n;this.size=0;this.closed=!1;this._timeoutHandle=void 0}addLines(e,t,n,i){if(this.closed||!e.length)return;let s=Date.now()+n;if(ithis.maxLines){let u=this.size,l=u*.7;do{let[c,d]=tt(this.first);this.size-=c.lines.length,d?d.next=c.next:(this.first=c.next,this.first&&this.scheduleRetry(this.first.retryTime-Date.now())),c.next=void 0,this.onShrink(c)}while(this.first&&this.size+e.length>l);p.error(`RetryBuffer: ${u-this.size} oldest lines removed to keep buffer size under the limit of ${this.maxLines} lines.`)}let o={lines:e,retryCount:t,retryTime:s,expires:i},a=this.first,f;for(;;){if(!a||a.retryTime>s){o.next=a,f?f.next=o:(this.first=o,this.scheduleRetry(s-Date.now()));break}f=a,a=a.next}this.size+=e.length}removeLines(){if(this.first){let e=this.first;return this.first=this.first.next,e.next=void 0,this.size-=e.lines.length,e}}scheduleRetry(e){this._timeoutHandle&&clearTimeout(this._timeoutHandle),this._timeoutHandle=setTimeout(()=>{let t=this.removeLines();t?this.retryLines(t.lines,t.retryCount,t.expires).catch(()=>{}).finally(()=>{this.first&&this.scheduleRetry(this.first.retryTime-Date.now())}):this._timeoutHandle=void 0},Math.max(e,0))}async flush(){let e;for(;e=this.removeLines();)await this.retryLines(e.lines,e.retryCount,e.expires)}close(){return this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this.closed=!0,this.size}};function ce(r){let e=r.length;for(let t=0;t=128&&n<=2047?e++:n>=2048&&n<=65535?n>=55296&&n<=57343?e++:e+=2:e+=3)}return e}var de=class{constructor(e,t,n,i){this.maxChunkRecords=e;this.maxBatchBytes=t;this.flushFn=n;this.scheduleSend=i;this.length=0;this.bytes=-1;this.lines=new Array(e)}add(e){let t=ce(e);this.length===0?this.scheduleSend():this.bytes+t+1>=this.maxBatchBytes&&this.flush().catch(n=>{}),this.lines[this.length]=e,this.length++,this.bytes+=t+1,(this.length>=this.maxChunkRecords||this.bytes>=this.maxBatchBytes)&&this.flush().catch(n=>{})}flush(){let e=this.reset();return e.length>0?this.flushFn(e):Promise.resolve()}reset(){let e=this.lines.slice(0,this.length);return this.length=0,this.bytes=-1,e}},F=class{constructor(e,t,n,i,s){this.transport=e;this.closed=!1;this._timeoutHandle=void 0;this.path=`/api/v2/write?org=${encodeURIComponent(t)}&bucket=${encodeURIComponent(n)}&precision=${i}`,s!=null&&s.consistency&&(this.path+=`&consistency=${encodeURIComponent(s.consistency)}`),this.writeOptions={...Z,...s},this.currentTime=ne[i],this.dateToProtocolTimestamp=ie[i],this.writeOptions.defaultTags&&this.useDefaultTags(this.writeOptions.defaultTags),this.sendOptions={method:"POST",headers:{"content-type":"text/plain; charset=utf-8",...s==null?void 0:s.headers},gzipThreshold:this.writeOptions.gzipThreshold};let o=()=>{this.writeOptions.flushInterval>0&&(this._clearFlushTimeout(),this.closed||(this._timeoutHandle=setTimeout(()=>this.sendBatch(this.writeBuffer.reset(),this.writeOptions.maxRetries).catch(a=>{}),this.writeOptions.flushInterval)))};this.writeBuffer=new de(this.writeOptions.batchSize,this.writeOptions.maxBatchBytes,a=>(this._clearFlushTimeout(),this.sendBatch(a,this.writeOptions.maxRetries)),o),this.sendBatch=this.sendBatch.bind(this),this.retryStrategy=Ce(this.writeOptions),this.retryBuffer=new P(this.writeOptions.maxBufferLines,this.sendBatch,this.writeOptions.writeRetrySkipped)}sendBatch(e,t,n=Date.now()+this.writeOptions.maxRetryTime){let i=this,s=i.writeOptions.maxRetries+1-t;if(!this.closed&&e.length>0){if(n<=Date.now()){let o=new Error("Max retry time exceeded."),a=i.writeOptions.writeFailed.call(i,o,e,s,n);return a||(p.error(`Write to InfluxDB failed (attempt: ${s}).`,o),Promise.reject(o))}return new Promise((o,a)=>{let f,u={responseStarted(l,c){f=c},error(l){let c=i.writeOptions.writeFailed.call(i,l,e,s,n);if(c){c.then(o,a);return}if(l instanceof m&&l.json&&typeof l.json.error=="string"&&l.json.error.includes("hinted handoff queue not empty")){p.warn("Write to InfluxDB returns: "+l.json.error),f=204,u.complete();return}if(!i.closed&&t>0&&(!(l instanceof m)||l.statusCode>=429)){p.warn(`Write to InfluxDB failed (attempt: ${s}).`,l),i.retryBuffer.addLines(e,t-1,i.retryStrategy.nextDelay(l,s),n),a(l);return}p.error("Write to InfluxDB failed.",l),a(l)},complete(){if(f==204||f==null)i.writeOptions.writeSuccess.call(i,e),i.retryStrategy.success(),o();else{let l=`204 HTTP response status code expected, but ${f} returned`,c=new m(f,l,void 0,"0");c.message=l,u.error(c)}}};this.transport.send(this.path,e.join(` +`),this.sendOptions,u)})}else return Promise.resolve()}_clearFlushTimeout(){this._timeoutHandle!==void 0&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0)}writeRecord(e){if(this.closed)throw new Error("writeApi: already closed!");this.writeBuffer.add(e)}writeRecords(e){if(this.closed)throw new Error("writeApi: already closed!");for(let t=0;t{let t=this.retryBuffer.close();t&&p.error(`Retry buffer closed with ${t} items that were not written to InfluxDB!`,null),this.closed=!0})}dispose(){return this._clearFlushTimeout(),this.closed=!0,this.retryBuffer.close()+this.writeBuffer.length}useDefaultTags(e){return this.defaultTags=e,this}convertTime(e){return e===void 0?this.currentTime():typeof e=="string"?e.length>0?e:void 0:e instanceof Date?this.dateToProtocolTimestamp(e):String(typeof e=="number"?Math.floor(e):e)}};function me(r={}){let e=0,t={next:n=>{if(e===0&&r.next&&n!==null&&n!==void 0)return r.next(n)},error:n=>{e===0&&(e=1,r.error&&r.error(n))},complete:()=>{e===0&&(e=2,r.complete&&r.complete())},responseStarted:(n,i)=>{r.responseStarted&&r.responseStarted(n,i)}};return r.useCancellable&&(t.useCancellable=r.useCancellable.bind(r)),r.useResume&&(t.useResume=r.useResume.bind(r)),t}function Oe(r){let e={};return r.headers.forEach((t,n)=>{let i=e[n];i===void 0?e[n]=t:Array.isArray(i)?i.push(t):e[n]=[i,t]}),e}var L=class{constructor(e){this.connectionOptions=e;this.chunkCombiner=g();this.requestDecorator=function(){};this.defaultHeaders={"content-type":"application/json; charset=utf-8",...e.headers},this.connectionOptions.token&&(this.defaultHeaders.Authorization="Token "+this.connectionOptions.token),this.url=String(this.connectionOptions.url),this.url.endsWith("/")&&(this.url=this.url.substring(0,this.url.length-1)),this.url.endsWith("/api/v2")&&(this.url=this.url.substring(0,this.url.length-7),p.warn(`Please remove '/api/v2' context path from InfluxDB base url, using ${this.url} !`))}send(e,t,n,i){let s=me(i),o=!1,a=n.signal,f,u=()=>{},l=u;if(i&&i.useCancellable){let c=new AbortController;a||(a=c.signal,n={...n,signal:a}),a.addEventListener("abort",()=>{l()}),i.useCancellable({cancel(){o=!0,c.abort()},isCancelled(){return o||a.aborted}})}this.fetch(e,t,n).then(async c=>{if(i!=null&&i.responseStarted&&s.responseStarted(Oe(c),c.status),await this.throwOnErrorResponse(c),c.body){let d=c.body.getReader(),T;do{if(f&&await f,o)break;if(T=await d.read(),s.next(T.value)===!1){let $=s.useResume;if(!$){let B="Unable to pause, useResume is not configured!";return await d.cancel(B),Promise.reject(new Error(B))}f=new Promise(B=>{l=()=>{B(),f=void 0,l=u},$(l)})}}while(!T.done)}else if(c.arrayBuffer){let d=await c.arrayBuffer();s.next(new Uint8Array(d))}else{let d=await c.text();s.next(new TextEncoder().encode(d))}}).catch(c=>{o||s.error(c)}).finally(()=>s.complete())}async throwOnErrorResponse(e){if(e.status>=300){let t="";try{if(t=await e.text(),!t){let n=e.headers.get("x-influxdb-error");n&&(t=n)}}catch(n){throw p.warn("Unable to receive error body",n),new m(e.status,e.statusText,void 0,e.headers.get("retry-after"),e.headers.get("content-type"))}throw new m(e.status,e.statusText,t,e.headers.get("retry-after"),e.headers.get("content-type"))}}async*iterate(e,t,n){var s;let i=await this.fetch(e,t,n);if(await this.throwOnErrorResponse(i),i.body){let o=i.body.getReader();for(;;){let{value:a,done:f}=await o.read();if(f)break;if((s=n.signal)!=null&&s.aborted)throw await i.body.cancel(),new x;yield a}}else if(i.arrayBuffer){let o=await i.arrayBuffer();yield new Uint8Array(o)}else{let o=await i.text();yield new TextEncoder().encode(o)}}async request(e,t,n,i){var u,l;let s=await this.fetch(e,t,n),{headers:o}=s,a=o.get("content-type")||"";i&&i(Oe(s),s.status),await this.throwOnErrorResponse(s);let f=(l=(u=n.headers)==null?void 0:u.accept)!=null?l:a;if(f.includes("json"))return await s.json();if(f.includes("text")||f.startsWith("application/csv"))return await s.text()}fetch(e,t,n){let{method:i,headers:s,...o}=n,a=`${this.url}${e}`,f={method:i,body:i==="GET"||i==="HEAD"?void 0:typeof t=="string"?t:JSON.stringify(t),headers:{...this.defaultHeaders,...s},credentials:"omit",...this.connectionOptions.transportOptions,...o};return this.requestDecorator(f,n,a),fetch(a,f)}};var Se={header:!0,delimiter:",",quoteChar:'"',commentPrefix:"#",annotations:["datatype","group","default"]},I=class{constructor(e,t,n){this.transport=e;this.createCSVResponse=t;this.options=typeof n=="string"?{org:n}:n}with(e){return new I(this.transport,this.createCSVResponse,{...this.options,...e})}response(e){let{org:t,type:n,gzip:i,headers:s}=this.options,o=`/api/v2/query?org=${encodeURIComponent(t)}`,a=JSON.stringify(this.decorateRequest({query:e.toString(),dialect:Se,type:n})),f={method:"POST",headers:{"content-type":"application/json; encoding=utf-8","accept-encoding":i?"gzip":"identity",...s}};return this.createCSVResponse(u=>this.transport.send(o,a,f,u),()=>this.transport.iterate(o,a,f))}iterateLines(e){return this.response(e).iterateLines()}iterateRows(e){return this.response(e).iterateRows()}lines(e){return this.response(e).lines()}rows(e){return this.response(e).rows()}queryLines(e,t){return this.response(e).consumeLines(t)}queryRows(e,t){return this.response(e).consumeRows(t)}collectRows(e,t){return this.response(e).collectRows(t)}collectLines(e){return this.response(e).collectLines()}queryRaw(e){let{org:t,type:n,gzip:i,headers:s}=this.options;return this.transport.request(`/api/v2/query?org=${encodeURIComponent(t)}`,JSON.stringify(this.decorateRequest({query:e.toString(),dialect:Se,type:n})),{method:"POST",headers:{accept:"text/csv","accept-encoding":i?"gzip":"identity","content-type":"application/json; encoding=utf-8",...s}})}decorateRequest(e){var t;return typeof this.options.now=="function"&&(e.now=this.options.now()),e.type=(t=this.options.type)!=null?t:"flux",e}},ve=I;function rt(r,e){return e.toObject(r)}var W=class{constructor(e,t,n){this.executor=e;this.iterableResultExecutor=t;this.chunkCombiner=n}iterateLines(){return M(this.iterableResultExecutor())}iterateRows(){return J(M(this.iterableResultExecutor()))}lines(){return new O(this.executor,e=>R(e,this.chunkCombiner))}rows(){return new O(this.executor,e=>R(V({next(t,n){e.next({values:t,tableMeta:n})},error(t){e.error(t)},complete(){e.complete()}}),this.chunkCombiner))}consumeLines(e){this.executor(R(e,this.chunkCombiner))}consumeRows(e){this.executor(R(V(e),this.chunkCombiner))}collectRows(e=rt){let t=[];return new Promise((n,i)=>{this.consumeRows({next(s,o){let a=e.call(this,s,o);a!==void 0&&t.push(a)},error(s){i(s)},complete(){n(t)}})})}collectLines(){let e=[];return new Promise((t,n)=>{this.consumeLines({next(i){e.push(i)},error(i){n(i)},complete(){t(e)}})})}};var U=class{constructor(e){var n;if(typeof e=="string")this._options={url:e};else if(e!==null&&typeof e=="object")this._options=e;else throw new y("No url or configuration specified!");let t=this._options.url;if(typeof t!="string")throw new y("No url specified!");t.endsWith("/")&&(this._options.url=t.substring(0,t.length-1)),this.transport=(n=this._options.transport)!=null?n:new L(this._options),this.processCSVResponse=(i,s)=>new W(i,s,this.transport.chunkCombiner)}getWriteApi(e,t,n="ns",i){return new F(this.transport,e,t,n,i!=null?i:this._options.writeOptions)}getQueryApi(e){return new ve(this.transport,this.processCSVResponse,e)}};return Le(nt);})(); +//# sourceMappingURL=influxdb.js.map \ No newline at end of file diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js.gz b/software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js.gz new file mode 100644 index 0000000000000000000000000000000000000000..f09142f26987f638e6022fb71d5801f2af3027ac GIT binary patch literal 9815 zcmV-dCaBpTiwFP!000021GRl=TieL8@aKDeh0)3DNXLz1Alt|hTtZ-ynFKOGG7G~S zgxv;BgyfOh0b=yuZ&mdwS&(J!Jq!S-YG?q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HT`Tu+wY4MuC>!h#+To* zS!!HkmtL#MZ`w%ztJ~n~FI zbg~#V8~OCU6+(#gi`TlA9^tf)HltKs|wyqUzk)5nA6ATt_{5wGTL0u-8UO)L?>Zj#GP1WrAwRtcet?&E#F=H3q zKuL=)_kJ%Q`l4`}e(6iU!6uxC*Ro0nF!4bj{Tzp=pR3g#_R?twO~h()hc}kSzjZ#Y z+-d3c-aMwg*wK+tQ6aSBcXT{#J4{v~Q*9!dF(sKwX0FVrzjG#!GGT7d= zM?d8=_x8$}6QP%fTOZ8*7ch83UYQHE+yuoJ|DIf3HB*hZ#TynTL(O39Uh70 z(=}5*N+yYW@>K(dcDH*)Zpp=W5q=GvXb)7nplh#44b1&58>6%ar=K-2GgbBpdPL@R zeG~;}D*xt`YpBx0SNONgE<3;CcVoZ?=i^Iwzp5iUm2cu@rRV%D3Iw#%v|g3Fs4z^z x`V?xpGdRL8sN`sb8rV;~)hb?`lzd)C^?Z$gs4o~+_-5h1{s%+b^P+}v007w^90&ja literal 0 HcmV?d00001 diff --git a/software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js.map b/software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js.map new file mode 100644 index 0000000..25efa8d --- /dev/null +++ b/software/flow/node_modules/@influxdata/influxdb-client/dist/influxdb.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/results/chunkCombiner.ts","../src/results/chunksToLines.ts","../src/results/chunksToLinesIterable.ts","../src/results/LineSplitter.ts","../src/results/FluxTableColumn.ts","../src/errors.ts","../src/results/FluxTableMetaData.ts","../src/results/linesToTables.ts","../src/results/linesToRowsIterable.ts","../src/results/stringToLines.ts","../src/observable/symbol.ts","../src/results/ObservableQuery.ts","../src/options.ts","../src/util/escape.ts","../src/util/currentTime.ts","../src/util/logger.ts","../src/query/flux.ts","../src/Point.ts","../src/impl/retryStrategy.ts","../src/impl/RetryBuffer.ts","../src/util/utf8Length.ts","../src/impl/WriteApiImpl.ts","../src/impl/completeCommunicationObserver.ts","../src/impl/browser/FetchTransport.ts","../src/impl/QueryApiImpl.ts","../src/results/AnnotatedCSVResponseImpl.ts","../src/InfluxDB.ts"],"sourcesContent":["/**\n * The `@influxdata/influxdb-client` package provides optimized APIs that write or query InfluxDB v2.\n *\n * @remarks\n * The entry point of this package is the {@link @influxdata/influxdb-client#InfluxDB } class. It is\n * initialized with options that tells how to communicate with InfluxDB. The simple usage pattern is:\n *\n * ```\n * import {InfluxDB} = from('@influxdata/influxdb-client')\n * const influxDB = new InfluxDB({\n * url: \"http://localhost:8086\",\n * token: \"your-api-token\"\n * })\n * ```\n *\n * The influxDB object let you create two essential API instances, {@link @influxdata/influxdb-client#InfluxDB.getWriteApi }\n * and {@link @influxdata/influxdb-client#InfluxDB.getQueryApi }. The {@link @influxdata/influxdb-client#WriteApi}\n * asynchronously writes measurement points on background, in batches to optimize network traffic, and with retries\n * upon failures. The {@link @influxdata/influxdb-client#QueryApi} let you execute a flux query against InfluxDB\n * and offers several ways to stream query results.\n *\n * The influxDB object is also used to create more specialized InfluxDB management API instances in\n * {@link @influxdata/influxdb-client-apis# | @influxdata/influxdb-client-apis} .\n *\n * See also {@link https://github.com/influxdata/influxdb-client-js/tree/master/examples | examples} to know more.\n *\n * @packageDocumentation\n */\nexport * from './results'\nexport * from './options'\nexport * from './errors'\nexport * from './util/escape'\nexport * from './util/currentTime'\nexport * from './util/logger'\nexport * from './query'\nexport * from './transport'\nexport * from './observable'\nexport * from './Point'\nexport {default as InfluxDB} from './InfluxDB'\nexport {default as QueryApi, QueryOptions} from './QueryApi'\nexport {default as WriteApi} from './WriteApi'\n","/**\n * ChunkCombiner is a simplified platform-neutral manipulation of Uint8arrays\n * that allows to process text data on the fly. The implementation can be optimized\n * for the target platform (node vs browser).\n */\nexport interface ChunkCombiner {\n /**\n * Concatenates first and second chunk.\n * @param first - first chunk\n * @param second - second chunk\n * @returns first + second\n */\n concat(first: Uint8Array, second: Uint8Array): Uint8Array\n\n /**\n * Converts chunk into a string.\n * @param chunk - chunk\n * @param start - start index\n * @param end - end index\n * @returns string representation of chunk slice\n */\n toUtf8String(chunk: Uint8Array, start: number, end: number): string\n\n /**\n * Creates a new chunk from the supplied chunk.\n * @param chunk - chunk to copy\n * @param start - start index\n * @param end - end index\n * @returns a copy of a chunk slice\n */\n copy(chunk: Uint8Array, start: number, end: number): Uint8Array\n}\n\n// TextDecoder is available since node v8.3.0 and in all modern browsers\ndeclare class TextDecoder {\n constructor(encoding: string)\n decode(chunk: Uint8Array): string\n}\n\n/**\n * Creates a chunk combiner instance that uses UTF-8\n * TextDecoder to decode Uint8Arrays into strings.\n */\nexport function createTextDecoderCombiner(): ChunkCombiner {\n const decoder = new TextDecoder('utf-8')\n return {\n concat(first: Uint8Array, second: Uint8Array): Uint8Array {\n const retVal = new Uint8Array(first.length + second.length)\n retVal.set(first)\n retVal.set(second, first.length)\n return retVal\n },\n copy(chunk: Uint8Array, start: number, end: number): Uint8Array {\n const retVal = new Uint8Array(end - start)\n retVal.set(chunk.subarray(start, end))\n return retVal\n },\n toUtf8String(chunk: Uint8Array, start: number, end: number): string {\n return decoder.decode(chunk.subarray(start, end))\n },\n }\n}\n","import {ChunkCombiner, createTextDecoderCombiner} from './chunkCombiner'\nimport {CommunicationObserver} from './CommunicationObserver'\nimport {Cancellable} from './Cancellable'\n\n/**\n * ChunksToLines is a transformation that accepts Uint8Array instances\n * and emmits strings representing CSV lines.\n * @param target - target to emmit CSV lines to\n * @param chunkCombiner - chunk combiner\n * @returns communication obrver to accept Uint8Arrays\n */\nexport function chunksToLines(\n target: CommunicationObserver,\n chunkCombiner?: ChunkCombiner\n): CommunicationObserver {\n const chunks = chunkCombiner ?? createTextDecoderCombiner()\n let previous: Uint8Array | undefined\n let finished = false\n let quoted = false\n let paused = false\n let resumeChunks: (() => void) | undefined\n\n function bufferReceived(chunk: Uint8Array): void {\n let index: number\n let start = 0\n if (previous) {\n // inspect the whole remaining data upon empty chunk\n // empty chunk signalizes to restart of receiving\n index = chunk.length === 0 ? 0 : (previous as Uint8Array).length\n chunk = chunks.concat(previous, chunk)\n } else {\n index = 0\n }\n while (index < chunk.length) {\n const c = chunk[index]\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n // do not emmit more lines if the processing is already finished\n if (finished) {\n return\n }\n paused = target.next(chunks.toUtf8String(chunk, start, end)) === false\n start = index + 1\n if (paused) {\n break\n }\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < chunk.length) {\n previous = chunks.copy(chunk, start, chunk.length)\n } else {\n previous = undefined\n }\n if (paused) {\n if (target.useResume) {\n target.useResume(() => {\n paused = false\n bufferReceived(new Uint8Array(0))\n })\n return\n }\n retVal.error(new Error('Unable to pause, useResume is not configured!'))\n paused = false // consume remaining data\n }\n if (resumeChunks) {\n resumeChunks()\n resumeChunks = undefined\n }\n }\n\n const retVal: CommunicationObserver = {\n next(chunk: Uint8Array): boolean {\n if (!finished) {\n try {\n bufferReceived(chunk)\n return !paused\n } catch (e) {\n this.error(e as Error)\n }\n }\n return true\n },\n error(error: Error): void {\n if (!finished) {\n finished = true\n target.error(error)\n }\n },\n complete(): void {\n if (!finished) {\n if (previous) {\n target.next(chunks.toUtf8String(previous, 0, previous.length))\n }\n finished = true\n target.complete()\n }\n },\n }\n if (target.useCancellable) {\n retVal.useCancellable = (cancellable: Cancellable) => {\n target.useCancellable &&\n target.useCancellable({\n cancel(): void {\n cancellable.cancel()\n previous = undefined // do not emit more lines\n retVal.complete()\n },\n isCancelled(): boolean {\n return cancellable.isCancelled()\n },\n })\n }\n }\n if (target.useResume) {\n retVal.useResume = (x: () => void) => {\n resumeChunks = x\n }\n }\n\n return retVal\n}\n","import {ChunkCombiner, createTextDecoderCombiner} from './chunkCombiner'\n\n/**\n * ChunksToLinesIterable is a transformation that accepts\n * an iterable of Uint8Array instances and returns iterable of lines.\n * @param source - iterable of transport buffers\n * @param chunkCombiner - chunk combiner\n * @returns iterable of lines\n */\nexport async function* chunksToLinesIterable(\n source: AsyncIterable,\n chunkCombiner?: ChunkCombiner\n): AsyncIterableIterator {\n const chunks = chunkCombiner ?? createTextDecoderCombiner()\n let previous: Uint8Array | undefined\n let quoted = false\n\n for await (let chunk of source) {\n let index: number\n let start = 0\n if (previous) {\n index = previous.length\n chunk = chunks.concat(previous, chunk)\n } else {\n index = 0\n }\n while (index < chunk.length) {\n const c = chunk[index]\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end = index > 0 && chunk[index - 1] === 13 ? index - 1 : index\n yield chunks.toUtf8String(chunk, start, end)\n start = index + 1\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < chunk.length) {\n previous = chunks.copy(chunk, start, chunk.length)\n } else {\n previous = undefined\n }\n }\n if (previous) {\n yield chunks.toUtf8String(previous, 0, previous.length)\n }\n}\n","/**\n * Optimized tokenizer of a single CSV line.\n */\nexport class LineSplitter {\n /** returned value when reused */\n reusedValues: string[]\n /** last length of elements in */\n lastSplitLength: number\n private _reuse = false\n\n /**\n * Reuse returned array between consecutive calls.\n */\n get reuse(): boolean {\n return this._reuse\n }\n set reuse(val: boolean) {\n if (val && !this.reusedValues) {\n this.reusedValues = new Array(10)\n }\n this._reuse = val\n }\n\n /**\n * Sets the reuse flag and returns this.\n */\n withReuse(): LineSplitter {\n this.reuse = true\n return this\n }\n\n /**\n * Splits the supplied line to elements that are separated by\n * comma with values possibly escaped within double quotes (\"value\")\n * @param line - line\n * @returns array of splitted parts\n */\n splitLine(line: string | undefined | null): string[] {\n if (line === null || line === undefined) {\n this.lastSplitLength = 0\n return []\n }\n let quoteCount = 0\n let startIndex = 0\n const values = this._reuse ? this.reusedValues : []\n let count = 0\n for (let i = 0; i < line.length; i++) {\n const c = line[i]\n if (c === ',') {\n if (quoteCount % 2 === 0) {\n const val = this.getValue(line, startIndex, i, quoteCount)\n if (this._reuse) {\n values[count++] = val\n } else {\n values.push(val)\n }\n startIndex = i + 1\n quoteCount = 0\n }\n } else if (c === '\"') {\n quoteCount++\n }\n }\n const val = this.getValue(line, startIndex, line.length, quoteCount)\n if (this._reuse) {\n values[count] = val\n this.lastSplitLength = count + 1\n } else {\n values.push(val)\n this.lastSplitLength = values.length\n }\n\n return values\n }\n\n private getValue(\n line: string,\n start: number,\n end: number,\n quoteCount: number\n ): string {\n if (start === line.length) {\n return ''\n } else if (quoteCount === 0) {\n return line.substring(start, end)\n } else if (quoteCount === 2) {\n return line.substring(start + 1, end - 1)\n } else {\n // quoteCount >= 4\n return line.substring(start + 1, end - 1).replace(/\"\"/gi, '\"')\n }\n }\n}\n","/**\n * Type of query result column, see {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport type ColumnType =\n | 'boolean'\n | 'unsignedLong'\n | 'long'\n | 'double'\n | 'string'\n | 'base64Binary'\n | 'dateTime:RFC3339'\n | 'duration'\n | string\n\n/**\n * FluxTableColumn describes {@link http://bit.ly/flux-spec#table | flux table} column.\n */\nexport interface FluxTableColumn {\n /**\n * Label (e.g., \"_start\", \"_stop\", \"_time\").\n */\n label: string\n\n /**\n * The data type of column (e.g., \"string\", \"long\", \"dateTime:RFC3339\").\n */\n dataType: ColumnType\n\n /**\n * Boolean flag indicating if the column is a part of the table's group key.\n */\n group: boolean\n\n /**\n * Default value to be used for rows whose string value is an empty string.\n */\n defaultValue: string\n\n /**\n * Index of this column in a row array.\n */\n index: number\n\n /**\n * Get returns a JavaScript object of this column in the supplied result row, using default deserializers.\n * @param row - a data row\n * @returns column value\n */\n get: (row: string[]) => any\n}\n\nconst identity = (x: string): any => x\n\n/**\n * A dictionary of serializers of particular types returned by a flux query.\n * See {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }\n */\nexport const typeSerializers: Record any> = {\n boolean: (x: string): any => (x === '' ? null : x === 'true'),\n unsignedLong: (x: string): any => (x === '' ? null : +x),\n long: (x: string): any => (x === '' ? null : +x),\n double(x: string): any {\n switch (x) {\n case '':\n return null\n case '+Inf':\n return Number.POSITIVE_INFINITY\n case '-Inf':\n return Number.NEGATIVE_INFINITY\n default:\n return +x\n }\n },\n string: identity,\n base64Binary: identity,\n duration: (x: string): any => (x === '' ? null : x),\n 'dateTime:RFC3339': (x: string): any => (x === '' ? null : x),\n}\n\n/**\n * FluxTableColumn implementation.\n */\nclass FluxTableColumnImpl implements FluxTableColumn {\n label: string\n dataType: ColumnType\n group: boolean\n defaultValue: string\n index: number\n public get(row: string[]): any {\n let val = row[this.index]\n if ((val === '' || val === undefined) && this.defaultValue) {\n val = this.defaultValue\n }\n return (typeSerializers[this.dataType] ?? identity)(val)\n }\n}\nexport const UNKNOWN_COLUMN: FluxTableColumn = Object.freeze({\n label: '',\n dataType: '',\n group: false,\n defaultValue: '',\n index: Number.MAX_SAFE_INTEGER,\n get: () => undefined,\n})\n\n/**\n * Creates a new flux table column.\n * @returns column instance\n */\nexport function newFluxTableColumn(): FluxTableColumn {\n return new FluxTableColumnImpl()\n}\n\n/**\n * Creates a flux table column from a partial FluxTableColumn.\n * @param object - source object\n * @returns column instance\n */\nexport function createFluxTableColumn(\n object: Partial\n): FluxTableColumn {\n const retVal = new FluxTableColumnImpl()\n retVal.label = String(object.label)\n retVal.dataType = object.dataType as ColumnType\n retVal.group = Boolean(object.group)\n retVal.defaultValue = object.defaultValue ?? ''\n retVal.index = object.index ?? 0\n return retVal\n}\n","/**\n * Strategy for calculating retry delays.\n */\nexport interface RetryDelayStrategy {\n /**\n * Returns delay for a next retry\n * @param error - reason for retrying\n * @param failedAttempts - a count of already failed attempts, 1 being the first\n * @returns milliseconds to wait before retrying\n */\n nextDelay(error?: Error, failedAttempts?: number): number\n /** Implementation should reset its state, this is mandatory to call upon success. */\n success(): void\n}\n\n/**\n * Interface for errors to inform that an associated operation can be retried.\n */\nexport interface RetriableDecision {\n /**\n * Informs whether this can be retried.\n */\n canRetry(): boolean\n /**\n * Get the delay in milliseconds to retry the action.\n * @returns 0 to let the implementation decide, miliseconds delay otherwise\n */\n retryAfter(): number\n}\n\nconst retriableStatusCodes = [404, 408, 425, 429, 500, 502, 503, 504]\n/** isStatusCodeRetriable checks whether the supplied HTTP status code is retriable. */\nexport function isStatusCodeRetriable(statusCode: number): boolean {\n return retriableStatusCodes.includes(statusCode)\n}\n\n/** IllegalArgumentError is thrown when illegal argument is supplied. */\nexport class IllegalArgumentError extends Error {\n /* istanbul ignore next */\n constructor(message: string) {\n super(message)\n this.name = 'IllegalArgumentError'\n Object.setPrototypeOf(this, IllegalArgumentError.prototype)\n }\n}\n\n/**\n * A general HTTP error.\n */\nexport class HttpError extends Error implements RetriableDecision {\n private _retryAfter: number\n /** application error code, when available */\n public code: string | undefined\n /** json error response */\n public json: any\n\n /* istanbul ignore next because of super() not being covered*/\n constructor(\n readonly statusCode: number,\n readonly statusMessage: string | undefined,\n readonly body?: string,\n retryAfter?: string | undefined | null,\n readonly contentType?: string | undefined | null,\n message?: string\n ) {\n super()\n Object.setPrototypeOf(this, HttpError.prototype)\n if (message) {\n this.message = message\n } else if (body) {\n if (contentType?.startsWith('application/json')) {\n try {\n this.json = JSON.parse(body)\n this.message = this.json.message\n this.code = this.json.code\n } catch (e) {\n // silently ignore, body string is still available\n }\n }\n if (!this.message) {\n this.message = `${statusCode} ${statusMessage} : ${body}`\n }\n } else {\n this.message = `${statusCode} ${statusMessage}`\n }\n this.name = 'HttpError'\n this.setRetryAfter(retryAfter)\n }\n\n private setRetryAfter(retryAfter?: string | undefined | null): void {\n if (typeof retryAfter === 'string') {\n // try to parse the supplied number as milliseconds\n if (/^[0-9]+$/.test(retryAfter)) {\n this._retryAfter = parseInt(retryAfter)\n } else {\n this._retryAfter = 0\n }\n } else {\n this._retryAfter = 0\n }\n }\n\n canRetry(): boolean {\n return isStatusCodeRetriable(this.statusCode)\n }\n retryAfter(): number {\n return this._retryAfter\n }\n}\n\n//see https://nodejs.org/api/errors.html\nconst RETRY_CODES = [\n 'ECONNRESET',\n 'ENOTFOUND',\n 'ESOCKETTIMEDOUT',\n 'ETIMEDOUT',\n 'ECONNREFUSED',\n 'EHOSTUNREACH',\n 'EPIPE',\n]\n\n/**\n * Tests the error in order to know if an HTTP call can be retried.\n * @param error - error to test\n * @returns true for a retriable error\n */\nexport function canRetryHttpCall(error: any): boolean {\n if (!error) {\n return false\n } else if (typeof (error as any).canRetry === 'function') {\n return !!((error as any).canRetry as () => boolean)()\n } else if ((error as any).code && RETRY_CODES.includes((error as any).code)) {\n return true\n }\n return false\n}\n\n/**\n * Gets retry delay from the supplied error, possibly using random number up to retryJitter.\n */\nexport function getRetryDelay(error?: Error, retryJitter?: number): number {\n if (!error) {\n return 0\n } else {\n let retVal\n if (typeof (error as any).retryAfter === 'function') {\n return ((error as any).retryAfter as () => number)()\n } else {\n retVal = 0\n }\n if (retryJitter && retryJitter > 0) {\n return retVal + Math.round(Math.random() * retryJitter)\n } else {\n return retVal\n }\n }\n}\n\n/** RequestTimedOutError indicates request timeout in the communication with the server */\nexport class RequestTimedOutError extends Error implements RetriableDecision {\n /* istanbul ignore next because of super() not being covered */\n constructor() {\n super()\n Object.setPrototypeOf(this, RequestTimedOutError.prototype)\n this.name = 'RequestTimedOutError'\n this.message = 'Request timed out'\n }\n canRetry(): boolean {\n return true\n }\n retryAfter(): number {\n return 0\n }\n}\n\n/** AbortError indicates that the communication with the server was aborted */\nexport class AbortError extends Error implements RetriableDecision {\n /* istanbul ignore next because of super() not being covered */\n constructor() {\n super()\n this.name = 'AbortError'\n Object.setPrototypeOf(this, AbortError.prototype)\n this.message = 'Response aborted'\n }\n canRetry(): boolean {\n return true\n }\n retryAfter(): number {\n return 0\n }\n}\n","import {\n FluxTableColumn,\n UNKNOWN_COLUMN,\n typeSerializers,\n} from './FluxTableColumn'\nimport {IllegalArgumentError} from '../errors'\n\n/**\n * serializeDateTimeAsDate changes type serializers to return JavaScript Date instances\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsDate(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : new Date(Date.parse(x))\n}\n/**\n * serializeDateTimeAsNumber changes type serializers to return milliseconds since epoch\n * for 'dateTime:RFC3339' query result data type. Empty value is converted to null.\n * @remarks\n * Please note that the result has millisecond precision whereas InfluxDB returns dateTime\n * in nanosecond precision.\n */\nexport function serializeDateTimeAsNumber(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : Date.parse(x)\n}\n/**\n * serializeDateTimeAsString changes type serializers to return string values\n * for `dateTime:RFC3339` query result data type. Empty value is converted to null.\n */\nexport function serializeDateTimeAsString(): void {\n typeSerializers['dateTime:RFC3339'] = (x: string): any =>\n x === '' ? null : x\n}\n\n/**\n * Represents metadata of a {@link http://bit.ly/flux-spec#table | flux table}.\n */\nexport interface FluxTableMetaData {\n /**\n * Table columns.\n */\n columns: Array\n\n /**\n * Gets columns by name\n * @param label - column label\n * @param errorOnMissingColumn - throw error on missing column (by default), return UNKNOWN_COLUMN when false\n * @returns table column\n * @throws IllegalArgumentError if column is not found\n **/\n column(label: string, errorOnMissingColumn?: boolean): FluxTableColumn\n\n /**\n * Creates an object out of the supplied row with the help of column descriptors.\n * @param row - a row with data for each column\n */\n toObject(row: string[]): {[key: string]: any}\n\n /**\n * Gets column values out of the supplied row.\n * @param row - a row with data for each column\n * @param column - column name\n * @returns column value, undefined for unknown column\n */\n get(row: string[], column: string): any\n}\n\n/**\n * FluxTableMetaData Implementation.\n */\nclass FluxTableMetaDataImpl implements FluxTableMetaData {\n columns: Array\n constructor(columns: FluxTableColumn[]) {\n columns.forEach((col, i) => (col.index = i))\n this.columns = columns\n }\n column(label: string, errorOnMissingColumn = true): FluxTableColumn {\n for (let i = 0; i < this.columns.length; i++) {\n const col = this.columns[i]\n if (col.label === label) return col\n }\n if (errorOnMissingColumn) {\n throw new IllegalArgumentError(`Column ${label} not found!`)\n }\n return UNKNOWN_COLUMN\n }\n toObject(row: string[]): {[key: string]: any} {\n const acc: any = {}\n for (let i = 0; i < this.columns.length && i < row.length; i++) {\n const column = this.columns[i]\n acc[column.label] = column.get(row)\n }\n return acc\n }\n get(row: string[], column: string): any {\n return this.column(column, false).get(row)\n }\n}\n\n/**\n * Created FluxTableMetaData from the columns supplied.\n * @param columns - columns\n * @returns - instance\n */\nexport function createFluxTableMetaData(\n columns: FluxTableColumn[]\n): FluxTableMetaData {\n return new FluxTableMetaDataImpl(columns)\n}\n\n/** Wraps values and associated metadata of a query result row */\nexport interface Row {\n values: string[]\n tableMeta: FluxTableMetaData\n}\n","import {CommunicationObserver} from './CommunicationObserver'\nimport {LineSplitter} from './LineSplitter'\nimport {FluxResultObserver} from './FluxResultObserver'\nimport {\n FluxTableColumn,\n ColumnType,\n newFluxTableColumn,\n} from './FluxTableColumn'\nimport {FluxTableMetaData, createFluxTableMetaData} from './FluxTableMetaData'\n\n/**\n * LinesToTables creates a transformation that accepts (flux) annotated CSV lines\n * and emits rows together with table metadata.\n */\nexport function linesToTables(\n consumer: FluxResultObserver\n): CommunicationObserver {\n const splitter = new LineSplitter().withReuse()\n let columns: FluxTableColumn[] | undefined\n let expectMeta = true\n let firstColumnIndex = 0\n let lastMeta: FluxTableMetaData\n const retVal: CommunicationObserver = {\n error(error: Error): void {\n consumer.error(error)\n },\n next(line: string): void | boolean {\n if (line === '') {\n expectMeta = true\n columns = undefined\n } else {\n const values = splitter.splitLine(line)\n const size = splitter.lastSplitLength\n if (expectMeta) {\n // create columns\n if (!columns) {\n columns = new Array(size)\n for (let i = 0; i < size; i++) {\n columns[i] = newFluxTableColumn()\n }\n }\n if (!values[0].startsWith('#')) {\n // fill in column names\n if (values[0] === '') {\n firstColumnIndex = 1\n columns = columns.slice(1)\n } else {\n firstColumnIndex = 0\n }\n for (let i = firstColumnIndex; i < size; i++) {\n columns[i - firstColumnIndex].label = values[i]\n }\n lastMeta = createFluxTableMetaData(columns)\n expectMeta = false\n } else if (values[0] === '#datatype') {\n for (let i = 1; i < size; i++) {\n columns[i].dataType = values[i] as ColumnType\n }\n } else if (values[0] === '#default') {\n for (let i = 1; i < size; i++) {\n columns[i].defaultValue = values[i]\n }\n } else if (values[0] === '#group') {\n for (let i = 1; i < size; i++) {\n columns[i].group = values[i][0] === 't'\n }\n }\n } else {\n return consumer.next(values.slice(firstColumnIndex, size), lastMeta)\n }\n }\n return true\n },\n complete(): void {\n consumer.complete()\n },\n }\n if (consumer.useCancellable) {\n retVal.useCancellable = consumer.useCancellable.bind(consumer)\n }\n if (consumer.useResume) {\n retVal.useResume = consumer.useResume.bind(consumer)\n }\n return retVal\n}\n","import {LineSplitter} from './LineSplitter'\nimport {\n FluxTableColumn,\n ColumnType,\n newFluxTableColumn,\n} from './FluxTableColumn'\nimport {\n FluxTableMetaData,\n createFluxTableMetaData,\n Row,\n} from './FluxTableMetaData'\n\n/**\n * LinesToRowsIterable is a transformation that accepts\n * an iterable of flux annotated CSV lines and returns\n * an iterable of rows (row values and table metadata).\n */\nexport async function* linesToRowsIterable(\n source: AsyncIterable\n): AsyncIterableIterator {\n const splitter = new LineSplitter().withReuse()\n let columns: FluxTableColumn[] | undefined\n let expectMeta = true\n let firstColumnIndex = 0\n let lastMeta: FluxTableMetaData | undefined = undefined\n for await (const line of source) {\n if (line === '') {\n expectMeta = true\n columns = undefined\n } else {\n const values = splitter.splitLine(line)\n const size = splitter.lastSplitLength\n if (expectMeta) {\n // create columns\n if (!columns) {\n columns = new Array(size)\n for (let i = 0; i < size; i++) {\n columns[i] = newFluxTableColumn()\n }\n }\n if (!values[0].startsWith('#')) {\n // fill in column names\n if (values[0] === '') {\n firstColumnIndex = 1\n columns = columns.slice(1)\n } else {\n firstColumnIndex = 0\n }\n for (let i = firstColumnIndex; i < size; i++) {\n columns[i - firstColumnIndex].label = values[i]\n }\n lastMeta = createFluxTableMetaData(columns)\n expectMeta = false\n } else if (values[0] === '#datatype') {\n for (let i = 1; i < size; i++) {\n columns[i].dataType = values[i] as ColumnType\n }\n } else if (values[0] === '#default') {\n for (let i = 1; i < size; i++) {\n columns[i].defaultValue = values[i]\n }\n } else if (values[0] === '#group') {\n for (let i = 1; i < size; i++) {\n columns[i].group = values[i][0] === 't'\n }\n }\n } else {\n yield {\n values: values.slice(firstColumnIndex, size),\n tableMeta:\n lastMeta as unknown as FluxTableMetaData /* never undefined */,\n }\n }\n }\n }\n}\n","import {CommunicationObserver} from './CommunicationObserver'\n\n/**\n * StringToLines is a transformation that emmits strings for each CSV\n * line in the supplied source string.\n * @param source - source string\n * @param target - target to emmit CSV lines to\n * @returns communication obrver to accept Uint8Arrays\n */\nexport function stringToLines(\n source: string,\n target: CommunicationObserver\n): void {\n let quoted = false\n let start = 0\n let index = 0\n\n while (index < source.length) {\n const c = source.charCodeAt(index)\n if (c === 10) {\n if (!quoted) {\n /* do not emit CR+LR or LF line ending */\n const end =\n index > 0 && source.charCodeAt(index - 1) === 13 ? index - 1 : index\n // do not emmit more lines if the processing is already finished\n target.next(source.substring(start, end))\n start = index + 1\n }\n } else if (c === 34 /* \" */) {\n quoted = !quoted\n }\n index++\n }\n if (start < index) {\n target.next(source.substring(start, index))\n }\n target.complete()\n}\n","/* Observable interop typing. Taken from https://github.com/ReactiveX/rxjs */\n\n/* Note: This will add Symbol.observable globally for all TypeScript users */\ndeclare global {\n interface SymbolConstructor {\n readonly observable: symbol\n }\n}\n\n/** Symbol.observable or a string \"\\@\\@observable\". Used for interop */\nexport const symbolObservable = (():\n | typeof Symbol.observable\n | '@@observable' =>\n (typeof Symbol === 'function' && Symbol.observable) || '@@observable')()\n","import {\n Observable,\n Observer,\n ObserverComplete,\n ObserverError,\n ObserverNext,\n Subscription,\n symbolObservable,\n} from '../observable'\nimport {CommunicationObserver} from '../results/CommunicationObserver'\nimport {Cancellable} from '../results/Cancellable'\n\n/** APIExecutor executes the API and passes its response to the supplied consumer */\nexport type APIExecutor = (consumer: CommunicationObserver) => void\n\ntype Decorator = (observer: Observer) => Observer\n\nclass QuerySubscription implements Subscription {\n private cancellable?: Cancellable\n private isClosed = false\n\n public constructor(observer: Observer, executor: APIExecutor) {\n try {\n executor({\n next: (value) => {\n observer.next(value)\n },\n error: (e) => {\n this.isClosed = true\n observer.error(e)\n },\n complete: () => {\n this.isClosed = true\n observer.complete()\n },\n useCancellable: (c) => {\n this.cancellable = c\n },\n })\n } catch (e) {\n this.isClosed = true\n observer.error(e)\n }\n }\n\n public get closed(): boolean {\n return this.isClosed\n }\n\n public unsubscribe(): void {\n this.cancellable?.cancel()\n this.isClosed = true\n }\n}\n\nfunction noop(): void {}\n\nfunction completeObserver(observer: Partial>): Observer {\n const {next, error, complete} = observer\n\n return {\n next: next ? next.bind(observer) : noop,\n error: error ? error.bind(observer) : noop,\n complete: complete ? complete.bind(observer) : noop,\n }\n}\n\nexport default class ObservableQuery implements Observable {\n public constructor(\n private readonly executor: APIExecutor,\n private readonly decorator: Decorator\n ) {}\n\n public subscribe(\n observerOrNext?: Partial> | ObserverNext,\n error?: ObserverError,\n complete?: ObserverComplete\n ): Subscription {\n const observer = completeObserver(\n typeof observerOrNext !== 'object' || observerOrNext === null\n ? {next: observerOrNext, error, complete}\n : observerOrNext\n )\n\n return new QuerySubscription(this.decorator(observer), this.executor)\n }\n\n public [symbolObservable](): this {\n return this\n }\n\n // this makes sure we satisfy the interface, while using a possibly polyfilled\n // [symbolObservable] above for the actual implementation\n public declare [Symbol.observable]: () => this\n}\n","import {Transport} from './transport'\nimport WriteApi from './WriteApi'\n\n/**\n * Option for the communication with InfluxDB server.\n */\nexport interface ConnectionOptions {\n /** base URL */\n url: string\n /** authentication token */\n token?: string\n /**\n * socket timeout, 10000 milliseconds by default in node.js\n * @defaultValue 10000\n */\n timeout?: number\n /**\n * TransportOptions supply extra options for the transport layer, they differ between node.js and browser/deno.\n * Node.js transport accepts options specified in {@link https://nodejs.org/api/http.html#http_http_request_options_callback | http.request } or\n * {@link https://nodejs.org/api/https.html#https_https_request_options_callback | https.request }. For example, an `agent` property can be set to\n * {@link https://www.npmjs.com/package/proxy-http-agent | setup HTTP/HTTPS proxy }, {@link https://nodejs.org/api/tls.html#tls_tls_connect_options_callback | rejectUnauthorized }\n * property can disable TLS server certificate verification. Additionally,\n * {@link https://github.com/follow-redirects/follow-redirects | follow-redirects } property can be also specified\n * in order to follow redirects in node.js.\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | fetch } is used under the hood in browser/deno.\n * For example,\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | redirect } property can be set to 'error' to abort request if a redirect occurs.\n */\n transportOptions?: {[key: string]: any}\n /**\n * Default HTTP headers to send with every request.\n */\n headers?: Record\n /**\n * Full HTTP web proxy URL including schema, for example http://your-proxy:8080.\n */\n proxyUrl?: string\n}\n\n/** default connection options */\nexport const DEFAULT_ConnectionOptions: Partial = {\n timeout: 10000,\n}\n\n/**\n * Options that configure strategy for retrying failed requests.\n */\nexport interface RetryDelayStrategyOptions {\n /** add `random(retryJitter)` milliseconds delay when retrying HTTP calls */\n retryJitter: number\n /** minimum delay when retrying write (milliseconds) */\n minRetryDelay: number\n /** maximum delay when retrying write (milliseconds) */\n maxRetryDelay: number\n /** base for the exponential retry delay */\n exponentialBase: number\n /**\n * randomRetry indicates whether the next retry delay is deterministic (false) or random (true).\n * The deterministic delay starts with `minRetryDelay * exponentialBase` and it is multiplied\n * by `exponentialBase` until it exceeds `maxRetryDelay`.\n * When random is `true`, the next delay is computed as a random number between next retry attempt (upper)\n * and the lower number in the deterministic sequence. `random(retryJitter)` is added to every returned value.\n */\n randomRetry: boolean\n}\n\n/**\n * Options that configure strategy for retrying failed InfluxDB write operations.\n */\nexport interface WriteRetryOptions extends RetryDelayStrategyOptions {\n /**\n * WriteFailed is called to inform about write errors.\n * @param this - the instance of the API that failed\n * @param error - write error\n * @param lines - failed lines\n * @param attempt - count of already failed attempts to write the lines (1 ... maxRetries+1)\n * @param expires - expiration time for the lines to be retried in millis since epoch\n * @returns a Promise to force the API to use it as a result of the flush operation,\n * void/undefined to continue with default retry mechanism\n */\n writeFailed(\n this: WriteApi,\n error: Error,\n lines: Array,\n attempt: number,\n expires: number\n ): Promise | void\n\n /**\n * WriteSuccess is informed about successfully written lines.\n * @param this - the instance of the API in use\n * @param lines - written lines\n */\n writeSuccess(this: WriteApi, lines: Array): void\n\n /**\n * WriteRetrySkipped is informed about lines that were removed from the retry buffer\n * to keep the size of the retry buffer under the configured limit (maxBufferLines).\n * @param entry - lines that were skipped\n */\n writeRetrySkipped(entry: {lines: Array; expires: number}): void\n\n /** max count of retries after the first write fails */\n maxRetries: number\n /** max time (millis) that can be spent with retries */\n maxRetryTime: number\n /** the maximum size of retry-buffer (in lines) */\n maxBufferLines: number\n}\n\n/**\n * Options used by {@link WriteApi} .\n */\nexport interface WriteOptions extends WriteRetryOptions {\n /** max number of records/lines to send in a batch */\n batchSize: number\n /** delay between data flushes in milliseconds, at most `batch size` records are sent during flush */\n flushInterval: number\n /** default tags, unescaped */\n defaultTags?: Record\n /** HTTP headers that will be sent with every write request */\n headers?: {[key: string]: string}\n /** When specified, write bodies larger than the threshold are gzipped */\n gzipThreshold?: number\n /** max size of a batch in bytes */\n maxBatchBytes: number\n /** InfluxDB Enterprise write consistency as explained in https://docs.influxdata.com/enterprise_influxdb/v1.9/concepts/clustering/#write-consistency */\n consistency?: 'any' | 'one' | 'quorum' | 'all'\n}\n\n/** default RetryDelayStrategyOptions */\nexport const DEFAULT_RetryDelayStrategyOptions = {\n retryJitter: 200,\n minRetryDelay: 5000,\n maxRetryDelay: 125000,\n exponentialBase: 5,\n randomRetry: true,\n}\n\n/** default writeOptions */\nexport const DEFAULT_WriteOptions: WriteOptions = {\n batchSize: 1000,\n maxBatchBytes: 50_000_000, // default max batch size in the cloud\n flushInterval: 60000,\n writeFailed: function () {},\n writeSuccess: function () {},\n writeRetrySkipped: function () {},\n maxRetries: 5,\n maxRetryTime: 180_000,\n maxBufferLines: 32_000,\n // a copy of DEFAULT_RetryDelayStrategyOptions, so that DEFAULT_WriteOptions could be tree-shaken\n retryJitter: 200,\n minRetryDelay: 5000,\n maxRetryDelay: 125000,\n exponentialBase: 2,\n gzipThreshold: 1000,\n randomRetry: true,\n}\n\n/**\n * Options used by {@link InfluxDB} .\n */\nexport interface ClientOptions extends ConnectionOptions {\n /** supplies and overrides default writing options */\n writeOptions?: Partial\n /** specifies custom transport */\n transport?: Transport\n}\n\n/**\n * Timestamp precision used in write operations.\n * See {@link https://docs.influxdata.com/influxdb/latest/api/#operation/PostWrite }\n */\nexport type WritePrecisionType = 'ns' | 'us' | 'ms' | 's'\n","function createEscaper(\n characters: string,\n replacements: string[]\n): (value: string) => string {\n return function (value: string): string {\n let retVal = ''\n let from = 0\n let i = 0\n while (i < value.length) {\n const found = characters.indexOf(value[i])\n if (found >= 0) {\n retVal += value.substring(from, i)\n retVal += replacements[found]\n from = i + 1\n }\n i++\n }\n if (from == 0) {\n return value\n } else if (from < value.length) {\n retVal += value.substring(from, value.length)\n }\n return retVal\n }\n}\nfunction createQuotedEscaper(\n characters: string,\n replacements: string[]\n): (value: string) => string {\n const escaper = createEscaper(characters, replacements)\n return (value: string): string => '\"' + escaper(value) + '\"'\n}\n\n/**\n * Provides functions escape specific parts in InfluxDB line protocol.\n */\nexport const escape = {\n /**\n * Measurement escapes measurement names.\n */\n measurement: createEscaper(', \\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\n', '\\\\r', '\\\\t']),\n /**\n * Quoted escapes quoted values, such as database names.\n */\n quoted: createQuotedEscaper('\"\\\\', ['\\\\\"', '\\\\\\\\']),\n\n /**\n * TagEscaper escapes tag keys, tag values, and field keys.\n */\n tag: createEscaper(', =\\n\\r\\t', ['\\\\,', '\\\\ ', '\\\\=', '\\\\n', '\\\\r', '\\\\t']),\n}\n","declare let process: any\nconst zeroPadding = '000000000'\nlet useHrTime = false\n\nexport function useProcessHrtime(use: boolean): boolean {\n /* istanbul ignore else */\n if (!process.env.BUILD_BROWSER) {\n return (useHrTime = use && process && typeof process.hrtime === 'function')\n } else {\n return false\n }\n}\nuseProcessHrtime(true) // preffer node\n\nlet startHrMillis: number | undefined = undefined\nlet startHrTime: [number, number] | undefined = undefined\nlet lastMillis = Date.now()\nlet stepsInMillis = 0\nfunction nanos(): string {\n if (!process.env.BUILD_BROWSER && useHrTime) {\n const hrTime = process.hrtime() as [number, number]\n let millis = Date.now()\n if (!startHrTime) {\n startHrTime = hrTime\n startHrMillis = millis\n } else {\n hrTime[0] = hrTime[0] - startHrTime[0]\n hrTime[1] = hrTime[1] - startHrTime[1]\n // istanbul ignore next \"cannot mock system clock, manually reviewed\"\n if (hrTime[1] < 0) {\n hrTime[0] -= 1\n hrTime[1] += 1000_000_000\n }\n millis =\n (startHrMillis as number) +\n hrTime[0] * 1000 +\n Math.floor(hrTime[1] / 1000_000)\n }\n const nanos = String(hrTime[1] % 1000_000)\n return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n } else {\n const millis = Date.now()\n if (millis !== lastMillis) {\n lastMillis = millis\n stepsInMillis = 0\n } else {\n stepsInMillis++\n }\n const nanos = String(stepsInMillis)\n return String(millis) + zeroPadding.substr(0, 6 - nanos.length) + nanos\n }\n}\n\nfunction micros(): string {\n if (!process.env.BUILD_BROWSER && useHrTime) {\n const hrTime = process.hrtime() as [number, number]\n const micros = String(Math.trunc(hrTime[1] / 1000) % 1000)\n return (\n String(Date.now()) + zeroPadding.substr(0, 3 - micros.length) + micros\n )\n } else {\n return String(Date.now()) + zeroPadding.substr(0, 3)\n }\n}\nfunction millis(): string {\n return String(Date.now())\n}\nfunction seconds(): string {\n return String(Math.floor(Date.now() / 1000))\n}\n\n/**\n * Exposes functions that creates strings that represent a timestamp that\n * can be used in the line protocol. Micro and nano timestamps are emulated\n * depending on the js platform in use.\n */\nexport const currentTime = {\n s: seconds as () => string,\n ms: millis as () => string,\n us: micros as () => string,\n ns: nanos as () => string,\n seconds: seconds as () => string,\n millis: millis as () => string,\n micros: micros as () => string,\n nanos: nanos as () => string,\n}\n\n/**\n * dateToProtocolTimestamp provides converters for JavaScript Date to InfluxDB Write Protocol Timestamp. Keys are supported precisions.\n */\nexport const dateToProtocolTimestamp = {\n s: (d: Date): string => `${Math.floor(d.getTime() / 1000)}`,\n ms: (d: Date): string => `${d.getTime()}`,\n us: (d: Date): string => `${d.getTime()}000`,\n ns: (d: Date): string => `${d.getTime()}000000`,\n}\n\n/**\n * convertTimeToNanos converts Point's timestamp to a string.\n * @param value - supported timestamp value\n * @returns line protocol value\n */\nexport function convertTimeToNanos(\n value: string | number | Date | undefined\n): string | undefined {\n if (value === undefined) {\n return nanos()\n } else if (typeof value === 'string') {\n return value.length > 0 ? value : undefined\n } else if (value instanceof Date) {\n return `${value.getTime()}000000`\n } else if (typeof value === 'number') {\n return String(Math.floor(value))\n } else {\n return String(value)\n }\n}\n","/**\n * Logging interface.\n */\nexport interface Logger {\n error(message: string, err?: any): void\n warn(message: string, err?: any): void\n}\n\n/**\n * Logger that logs to console.out\n */\nexport const consoleLogger: Logger = {\n error(message, error) {\n // eslint-disable-next-line no-console\n console.error('ERROR: ' + message, error ? error : '')\n },\n warn(message, error) {\n // eslint-disable-next-line no-console\n console.warn('WARN: ' + message, error ? error : '')\n },\n}\nlet provider: Logger = consoleLogger\n\nexport const Log: Logger = {\n error(message, error) {\n provider.error(message, error)\n },\n warn(message, error) {\n provider.warn(message, error)\n },\n}\n\n/**\n * Sets custom logger.\n * @param logger - logger to use\n * @returns previous logger\n */\nexport function setLogger(logger: Logger): Logger {\n const previous = provider\n provider = logger\n return previous\n}\n","/** Property that offers a function that returns flux-sanitized value of an object. */\nexport const FLUX_VALUE = Symbol('FLUX_VALUE')\n\n/**\n * A flux parameter can print its (sanitized) flux value.\n */\nexport interface FluxParameterLike {\n [FLUX_VALUE](): string\n}\n\n/**\n * Represents a parameterized query.\n */\nexport interface ParameterizedQuery {\n /**\n * Returns flux query with sanitized parameters.\n */\n toString(): string\n}\n\nclass FluxParameter implements FluxParameterLike, ParameterizedQuery {\n constructor(private fluxValue: string) {}\n toString(): string {\n return this.fluxValue\n }\n [FLUX_VALUE](): string {\n return this.fluxValue\n }\n}\n\n/**\n * Checks if the supplied object is FluxParameterLike\n * @param value - any value\n * @returns true if it is\n */\nfunction isFluxParameterLike(value: any): boolean {\n return typeof value === 'object' && typeof value[FLUX_VALUE] === 'function'\n}\n\n/**\n * Escapes content of the supplied string so it can be wrapped into double qoutes\n * to become a [flux string literal](https://docs.influxdata.com/flux/latest/spec/lexical-elements/#string-literals).\n * @param value - string value\n * @returns sanitized string\n */\nfunction sanitizeString(value: any): string {\n if (value === null || value === undefined) return ''\n value = value.toString()\n let retVal: any = undefined\n let i = 0\n function prepareRetVal(): void {\n if (retVal === undefined) {\n retVal = value.substring(0, i)\n }\n }\n for (; i < value.length; i++) {\n const c = value.charAt(i)\n switch (c) {\n case '\\r':\n prepareRetVal()\n retVal += '\\\\r'\n break\n case '\\n':\n prepareRetVal()\n retVal += '\\\\n'\n break\n case '\\t':\n prepareRetVal()\n retVal += '\\\\t'\n break\n case '\"':\n case '\\\\':\n prepareRetVal()\n retVal = retVal + '\\\\' + c\n break\n case '$':\n // escape ${\n if (i + 1 < value.length && value.charAt(i + 1) === '{') {\n prepareRetVal()\n i++\n retVal += '\\\\${'\n break\n }\n // append $\n if (retVal != undefined) {\n retVal += c\n }\n break\n default:\n if (retVal != undefined) {\n retVal += c\n }\n }\n }\n if (retVal !== undefined) {\n return retVal\n }\n return value\n}\n\n/**\n * Creates a flux string literal.\n */\nexport function fluxString(value: any): FluxParameterLike {\n return new FluxParameter(`\"${sanitizeString(value)}\"`)\n}\n\n/**\n * Sanitizes float value to avoid injections.\n * @param value - InfluxDB float literal\n * @returns sanitized float value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeFloat(value: any): string {\n const val = Number(value)\n if (!isFinite(val)) {\n if (typeof value === 'number') {\n return `float(v: \"${val}\")`\n }\n throw new Error(`not a flux float: ${value}`)\n }\n // try to return a flux float literal if possible\n // https://docs.influxdata.com/flux/latest/data-types/basic/float/#float-syntax\n const strVal = val.toString()\n let hasDot = false\n for (const c of strVal) {\n if ((c >= '0' && c <= '9') || c == '-') continue\n if (c === '.') {\n hasDot = true\n continue\n }\n return `float(v: \"${strVal}\")`\n }\n return hasDot ? strVal : strVal + '.0'\n}\n/**\n * Creates a flux float literal.\n */\nexport function fluxFloat(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeFloat(value))\n}\n\n/**\n * Sanitizes integer value to avoid injections.\n * @param value - InfluxDB integer literal\n * @returns sanitized integer value\n * @throws Error if the the value cannot be sanitized\n */\nexport function sanitizeInteger(value: any): string {\n // https://docs.influxdata.com/flux/latest/data-types/basic/int/\n // Min value: -9223372036854775808\n // Max value: 9223372036854775807\n // \"9223372036854775807\".length === 19\n const strVal = String(value)\n const negative = strVal.startsWith('-')\n const val = negative ? strVal.substring(1) : strVal\n if (val.length === 0 || val.length > 19) {\n throw new Error(`not a flux integer: ${strVal}`)\n }\n for (const c of val) {\n if (c < '0' || c > '9') throw new Error(`not a flux integer: ${strVal}`)\n }\n if (val.length === 19) {\n if (negative && val > '9223372036854775808') {\n throw new Error(`flux integer out of bounds: ${strVal}`)\n }\n if (!negative && val > '9223372036854775807') {\n throw new Error(`flux integer out of bounds: ${strVal}`)\n }\n }\n return strVal\n}\n\n/**\n * Creates a flux integer literal.\n */\nexport function fluxInteger(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeInteger(value))\n}\n\nfunction sanitizeDateTime(value: any): string {\n return `time(v: \"${sanitizeString(value)}\")`\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDateTime(value: any): FluxParameterLike {\n return new FluxParameter(sanitizeDateTime(value))\n}\n\n/**\n * Creates flux date-time literal.\n */\nexport function fluxDuration(value: any): FluxParameterLike {\n return new FluxParameter(`duration(v: \"${sanitizeString(value)}\")`)\n}\n\nfunction sanitizeRegExp(value: any): string {\n if (value instanceof RegExp) {\n return value.toString()\n }\n return new RegExp(value).toString()\n}\n\n/**\n * Creates flux regexp literal out of a regular expression. See\n * https://docs.influxdata.com/flux/latest/data-types/basic/regexp/#regular-expression-syntax\n * for details.\n */\nexport function fluxRegExp(value: any): FluxParameterLike {\n // let the server decide if a regexp can be parsed\n return new FluxParameter(sanitizeRegExp(value))\n}\n\n/**\n * Creates flux boolean literal.\n */\nexport function fluxBool(value: any): FluxParameterLike {\n if (value === 'true' || value === 'false') {\n return new FluxParameter(value)\n }\n return new FluxParameter((!!value).toString())\n}\n\n/**\n * Assumes that the supplied value is flux expression or literal that does not need sanitizing.\n *\n * @param value - any value\n * @returns the supplied value as-is\n */\nexport function fluxExpression(value: any): FluxParameterLike {\n return new FluxParameter(String(value))\n}\n\n/**\n * Escapes content of the supplied parameter so that it can be safely embedded into flux query.\n * @param value - parameter value\n * @returns sanitized flux value or an empty string if it cannot be converted\n */\nexport function toFluxValue(value: any): string {\n if (value === undefined) {\n return ''\n } else if (value === null) {\n return 'null'\n } else if (typeof value === 'boolean') {\n return value.toString()\n } else if (typeof value === 'string') {\n return `\"${sanitizeString(value)}\"`\n } else if (typeof value === 'number') {\n if (Number.isSafeInteger(value)) {\n return sanitizeInteger(value)\n }\n return sanitizeFloat(value)\n } else if (typeof value === 'object') {\n if (typeof value[FLUX_VALUE] === 'function') {\n return value[FLUX_VALUE]()\n } else if (value instanceof Date) {\n return value.toISOString()\n } else if (value instanceof RegExp) {\n return sanitizeRegExp(value)\n } else if (Array.isArray(value)) {\n return `[${value.map(toFluxValue).join(',')}]`\n }\n } else if (typeof value === 'bigint') {\n return `${value}.0`\n }\n // use toString value for unrecognized object, symbol\n return toFluxValue(value.toString())\n}\n\n/**\n * Flux is a tagged template that sanitizes supplied parameters\n * to avoid injection attacks in flux.\n */\nexport function flux(\n strings: TemplateStringsArray,\n ...values: any\n): ParameterizedQuery {\n if (strings.length == 1 && values.length === 0) {\n return fluxExpression(strings[0]) // the simplest case\n }\n const parts = new Array(strings.length + values.length)\n let partIndex = 0\n for (let i = 0; i < strings.length; i++) {\n const text = strings[i]\n parts[partIndex++] = text\n if (i < values.length) {\n const val = values[i]\n let sanitized: string\n if (\n text.endsWith('\"') &&\n i + 1 < strings.length &&\n strings[i + 1].startsWith('\"')\n ) {\n // parameter is wrapped into flux double quotes\n sanitized = sanitizeString(val)\n } else {\n sanitized = toFluxValue(val)\n if (sanitized === '') {\n // do not allow to insert empty strings, unless it is FluxParameterLike\n if (!isFluxParameterLike(val)) {\n throw new Error(\n `Unsupported parameter literal '${val}' at index: ${i}, type: ${typeof val}`\n )\n }\n }\n }\n parts[partIndex++] = sanitized\n } else if (i < strings.length - 1) {\n throw new Error('Too few parameters supplied!')\n }\n }\n // return flux expression so that flux can be embedded into another flux as-is\n return fluxExpression(parts.join(''))\n}\n","import {convertTimeToNanos} from './util/currentTime'\nimport {escape} from './util/escape'\n\n/**\n * Settings that control the way of how a {@link Point} is serialized\n * to a protocol line.\n */\nexport interface PointSettings {\n /** default tags to add to every point */\n defaultTags?: {[key: string]: string}\n /** convertTime serializes Point's timestamp to a line protocol value */\n convertTime?: (\n value: string | number | Date | undefined\n ) => string | undefined\n}\n\n/**\n * Point defines values of a single measurement.\n */\nexport class Point {\n private name: string\n private tags: {[key: string]: string} = {}\n /** escaped field values */\n public fields: {[key: string]: string} = {}\n private time: string | number | Date | undefined\n\n /**\n * Create a new Point with specified a measurement name.\n *\n * @param measurementName - the measurement name\n */\n constructor(measurementName?: string) {\n if (measurementName) this.name = measurementName\n }\n\n /**\n * Sets point's measurement.\n *\n * @param name - measurement name\n * @returns this\n */\n public measurement(name: string): Point {\n this.name = name\n return this\n }\n\n /**\n * Adds a tag. The caller has to ensure that both name and value are not empty\n * and do not end with backslash.\n *\n * @param name - tag name\n * @param value - tag value\n * @returns this\n */\n public tag(name: string, value: string): Point {\n this.tags[name] = value\n return this\n }\n\n /**\n * Adds a boolean field.\n *\n * @param field - field name\n * @param value - field value\n * @returns this\n */\n public booleanField(name: string, value: boolean | any): Point {\n this.fields[name] = value ? 'T' : 'F'\n return this\n }\n\n /**\n * Adds an integer field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN or out of int64 range value is supplied\n */\n public intField(name: string, value: number | any): Point {\n let val: number\n if (typeof value === 'number') {\n val = value\n } else {\n val = parseInt(String(value))\n }\n if (isNaN(val) || val <= -9223372036854776e3 || val >= 9223372036854776e3) {\n throw new Error(`invalid integer value for field '${name}': '${value}'!`)\n }\n this.fields[name] = `${Math.floor(val)}i`\n return this\n }\n\n /**\n * Adds an unsigned integer field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN out of range value is supplied\n */\n public uintField(name: string, value: number | any): Point {\n if (typeof value === 'number') {\n if (isNaN(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {\n throw new Error(`uint value for field '${name}' out of range: ${value}`)\n }\n this.fields[name] = `${Math.floor(value as number)}u`\n } else {\n const strVal = String(value)\n for (let i = 0; i < strVal.length; i++) {\n const code = strVal.charCodeAt(i)\n if (code < 48 || code > 57) {\n throw new Error(\n `uint value has an unsupported character at pos ${i}: ${value}`\n )\n }\n }\n if (\n strVal.length > 20 ||\n (strVal.length === 20 &&\n strVal.localeCompare('18446744073709551615') > 0)\n ) {\n throw new Error(\n `uint value for field '${name}' out of range: ${strVal}`\n )\n }\n this.fields[name] = `${strVal}u`\n }\n return this\n }\n\n /**\n * Adds a number field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n * @throws NaN/Infinity/-Infinity is supplied\n */\n public floatField(name: string, value: number | any): Point {\n let val: number\n if (typeof value === 'number') {\n val = value\n } else {\n val = parseFloat(value)\n }\n if (!isFinite(val)) {\n throw new Error(`invalid float value for field '${name}': ${value}`)\n }\n\n this.fields[name] = String(val)\n return this\n }\n\n /**\n * Adds a string field.\n *\n * @param name - field name\n * @param value - field value\n * @returns this\n */\n public stringField(name: string, value: string | any): Point {\n if (value !== null && value !== undefined) {\n if (typeof value !== 'string') value = String(value)\n this.fields[name] = escape.quoted(value)\n }\n return this\n }\n\n /**\n * Sets point timestamp. Timestamp can be specified as a Date (preferred), number, string\n * or an undefined value. An undefined value instructs to assign a local timestamp using\n * the client's clock. An empty string can be used to let the server assign\n * the timestamp. A number value represents time as a count of time units since epoch, the\n * exact time unit then depends on the {@link InfluxDB.getWriteApi | precision} of the API\n * that writes the point.\n *\n * Beware that the current time in nanoseconds can't precisely fit into a JS number,\n * which can hold at most 2^53 integer number. Nanosecond precision numbers are thus supplied as\n * a (base-10) string. An application can also use ES2020 BigInt to represent nanoseconds,\n * BigInt's `toString()` returns the required high-precision string.\n *\n * Note that InfluxDB requires the timestamp to fit into int64 data type.\n *\n * @param value - point time\n * @returns this\n */\n public timestamp(value: Date | number | string | undefined): Point {\n this.time = value\n return this\n }\n\n /**\n * Creates an InfluxDB protocol line out of this instance.\n * @param settings - settings control serialization of a point timestamp and can also add default tags,\n * nanosecond timestamp precision is used when no `settings` or no `settings.convertTime` is supplied.\n * @returns an InfluxDB protocol line out of this instance\n */\n public toLineProtocol(settings?: Partial): string | undefined {\n if (!this.name) return undefined\n let fieldsLine = ''\n Object.keys(this.fields)\n .sort()\n .forEach((x) => {\n if (x) {\n const val = this.fields[x]\n if (fieldsLine.length > 0) fieldsLine += ','\n fieldsLine += `${escape.tag(x)}=${val}`\n }\n })\n if (fieldsLine.length === 0) return undefined // no fields present\n let tagsLine = ''\n const tags =\n settings && settings.defaultTags\n ? {...settings.defaultTags, ...this.tags}\n : this.tags\n Object.keys(tags)\n .sort()\n .forEach((x) => {\n if (x) {\n const val = tags[x]\n if (val) {\n tagsLine += ','\n tagsLine += `${escape.tag(x)}=${escape.tag(val)}`\n }\n }\n })\n let time = this.time\n if (settings && settings.convertTime) {\n time = settings.convertTime(time)\n } else {\n time = convertTimeToNanos(time)\n }\n\n return `${escape.measurement(this.name)}${tagsLine} ${fieldsLine}${\n time !== undefined ? ' ' + time : ''\n }`\n }\n\n toString(): string {\n const line = this.toLineProtocol(undefined)\n return line ? line : `invalid point: ${JSON.stringify(this, undefined)}`\n }\n}\n","import {getRetryDelay, RetryDelayStrategy} from '../errors'\nimport {\n RetryDelayStrategyOptions,\n DEFAULT_RetryDelayStrategyOptions,\n} from '../options'\n\n/**\n * Applies a variant of exponential backoff with initial and max delay and a random\n * jitter delay. It also respects `retry delay` when specified together with an error.\n */\nexport class RetryStrategyImpl implements RetryDelayStrategy {\n options: RetryDelayStrategyOptions\n currentDelay: number | undefined\n\n constructor(options?: Partial) {\n this.options = {...DEFAULT_RetryDelayStrategyOptions, ...options}\n this.success()\n }\n\n nextDelay(error?: Error, failedAttempts?: number): number {\n const delay = getRetryDelay(error)\n if (delay && delay > 0) {\n return delay + Math.round(Math.random() * this.options.retryJitter)\n } else {\n if (failedAttempts && failedAttempts > 0) {\n // compute delay\n if (this.options.randomRetry) {\n // random delay between deterministic delays\n let delay = Math.max(this.options.minRetryDelay, 1)\n let nextDelay = delay * this.options.exponentialBase\n for (let i = 1; i < failedAttempts; i++) {\n delay = nextDelay\n nextDelay = nextDelay * this.options.exponentialBase\n if (nextDelay >= this.options.maxRetryDelay) {\n nextDelay = this.options.maxRetryDelay\n break\n }\n }\n return (\n delay +\n Math.round(\n Math.random() * (nextDelay - delay) +\n Math.random() * this.options.retryJitter\n )\n )\n }\n // deterministric delay otherwise\n let delay = Math.max(this.options.minRetryDelay, 1)\n for (let i = 1; i < failedAttempts; i++) {\n delay = delay * this.options.exponentialBase\n if (delay >= this.options.maxRetryDelay) {\n delay = this.options.maxRetryDelay\n break\n }\n }\n return delay + Math.round(Math.random() * this.options.retryJitter)\n } else if (this.currentDelay) {\n this.currentDelay = Math.min(\n Math.max(this.currentDelay * this.options.exponentialBase, 1) +\n Math.round(Math.random() * this.options.retryJitter),\n this.options.maxRetryDelay\n )\n } else {\n this.currentDelay =\n this.options.minRetryDelay +\n Math.round(Math.random() * this.options.retryJitter)\n }\n return this.currentDelay\n }\n }\n success(): void {\n this.currentDelay = undefined\n }\n}\n\n/**\n * Creates a new instance of retry strategy.\n * @param options - retry options\n * @returns retry strategy implementation\n */\nexport function createRetryDelayStrategy(\n options?: Partial\n): RetryDelayStrategy {\n return new RetryStrategyImpl(options)\n}\n","import {Log} from '../util/logger'\n\ninterface RetryItem {\n lines: string[]\n retryCount: number\n retryTime: number\n expires: number\n next?: RetryItem\n}\n\ntype FindShrinkCandidateResult = [found: RetryItem, parent?: RetryItem]\n\nfunction findShrinkCandidate(first: RetryItem): FindShrinkCandidateResult {\n let parent = undefined\n let found = first\n let currentParent = first\n while (currentParent.next) {\n if (currentParent.next.expires < found.expires) {\n parent = currentParent\n found = currentParent.next\n }\n currentParent = currentParent.next\n }\n return [found, parent]\n}\n\n/**\n * Retries lines up to a limit of max buffer size.\n */\nexport default class RetryBuffer {\n first?: RetryItem\n size = 0\n closed = false\n private _timeoutHandle: any = undefined\n\n constructor(\n private maxLines: number,\n private retryLines: (\n lines: string[],\n retryCountdown: number,\n started: number\n ) => Promise,\n private onShrink: (entry: {\n lines: string[]\n retryCount: number\n expires: number\n }) => void = () => undefined\n ) {}\n\n addLines(\n lines: string[],\n retryCount: number,\n delay: number,\n expires: number\n ): void {\n if (this.closed) return\n if (!lines.length) return\n let retryTime = Date.now() + delay\n if (expires < retryTime) {\n retryTime = expires\n }\n // ensure at most maxLines are in the Buffer\n if (this.first && this.size + lines.length > this.maxLines) {\n const origSize = this.size\n const newSize = origSize * 0.7 // reduce to 70 %\n do {\n // remove \"oldest\" item\n const [found, parent] = findShrinkCandidate(this.first)\n this.size -= found.lines.length\n if (parent) {\n parent.next = found.next\n } else {\n this.first = found.next\n if (this.first) {\n this.scheduleRetry(this.first.retryTime - Date.now())\n }\n }\n found.next = undefined\n this.onShrink(found)\n } while (this.first && this.size + lines.length > newSize)\n Log.error(\n `RetryBuffer: ${\n origSize - this.size\n } oldest lines removed to keep buffer size under the limit of ${\n this.maxLines\n } lines.`\n )\n }\n const toAdd: RetryItem = {\n lines,\n retryCount,\n retryTime,\n expires,\n }\n // insert sorted according to retryTime\n let current: RetryItem | undefined = this.first\n let parent = undefined\n for (;;) {\n if (!current || current.retryTime > retryTime) {\n toAdd.next = current\n if (parent) {\n parent.next = toAdd\n } else {\n this.first = toAdd\n this.scheduleRetry(retryTime - Date.now())\n }\n break\n }\n parent = current\n current = current.next\n }\n this.size += lines.length\n }\n\n removeLines(): RetryItem | undefined {\n if (this.first) {\n const toRetry = this.first\n this.first = this.first.next\n toRetry.next = undefined\n this.size -= toRetry.lines.length\n return toRetry\n }\n return undefined\n }\n\n scheduleRetry(delay: number): void {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle)\n }\n this._timeoutHandle = setTimeout(() => {\n const toRetry = this.removeLines()\n if (toRetry) {\n this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n .catch(() => {\n /* error is already logged, it must be caught */\n })\n .finally(() => {\n // schedule next retry execution\n if (this.first) {\n this.scheduleRetry(this.first.retryTime - Date.now())\n }\n })\n } else {\n this._timeoutHandle = undefined\n }\n }, Math.max(delay, 0))\n }\n\n async flush(): Promise {\n let toRetry\n while ((toRetry = this.removeLines())) {\n await this.retryLines(toRetry.lines, toRetry.retryCount, toRetry.expires)\n }\n }\n\n close(): number {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle)\n this._timeoutHandle = undefined\n }\n this.closed = true\n return this.size\n }\n}\n","/**\n * Utf8Length returns an expected length of a string when UTF-8 encoded.\n * @param s - input string\n * @returns expected count of bytes\n */\nexport default function utf8Length(s: string): number {\n let retVal = s.length\n // extends the size with code points (https://en.wikipedia.org/wiki/UTF-8#Encoding)\n for (let i = 0; i < s.length; i++) {\n const code = s.charCodeAt(i)\n /* istanbul ignore else - JS does not count with 4-bytes UNICODE characters at the moment */\n if (code < 0x80) {\n continue\n } else if (code >= 0x80 && code <= 0x7ff) {\n retVal++\n } else if (code >= 0x800 && code <= 0xffff) {\n if (code >= 0xd800 && code <= 0xdfff) {\n // node.js represents unicode characters above 0xffff by two UTF-16 surrogate halves\n // see https://en.wikipedia.org/wiki/UTF-8#Codepage_layout\n retVal++\n } else {\n retVal += 2\n }\n } else {\n // never happens in node.js 14, the situation can vary in the futures or in deno/browsers\n retVal += 3\n }\n }\n return retVal\n}\n","import WriteApi from '../WriteApi'\nimport {\n DEFAULT_WriteOptions,\n WriteOptions,\n WritePrecisionType,\n} from '../options'\nimport {Transport, SendOptions} from '../transport'\nimport {Headers} from '../results'\nimport {Log} from '../util/logger'\nimport {HttpError, RetryDelayStrategy} from '../errors'\nimport {Point} from '../Point'\nimport {currentTime, dateToProtocolTimestamp} from '../util/currentTime'\nimport {createRetryDelayStrategy} from './retryStrategy'\nimport RetryBuffer from './RetryBuffer'\nimport utf8Length from '../util/utf8Length'\n\nclass WriteBuffer {\n length = 0\n bytes = -1\n lines: string[]\n\n constructor(\n private maxChunkRecords: number,\n private maxBatchBytes: number,\n private flushFn: (lines: string[]) => Promise,\n private scheduleSend: () => void\n ) {\n this.lines = new Array(maxChunkRecords)\n }\n\n add(record: string): void {\n const size = utf8Length(record)\n if (this.length === 0) {\n this.scheduleSend()\n } else if (this.bytes + size + 1 >= this.maxBatchBytes) {\n // the new size already exceeds maxBatchBytes, send it\n this.flush().catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n })\n }\n this.lines[this.length] = record\n this.length++\n this.bytes += size + 1\n if (\n this.length >= this.maxChunkRecords ||\n this.bytes >= this.maxBatchBytes\n ) {\n this.flush().catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n })\n }\n }\n flush(): Promise {\n const lines = this.reset()\n if (lines.length > 0) {\n return this.flushFn(lines)\n } else {\n return Promise.resolve()\n }\n }\n reset(): string[] {\n const retVal = this.lines.slice(0, this.length)\n this.length = 0\n this.bytes = -1 // lines are joined with \\n\n return retVal\n }\n}\n\nexport default class WriteApiImpl implements WriteApi {\n public path: string\n\n private writeBuffer: WriteBuffer\n private closed = false\n private writeOptions: WriteOptions\n private sendOptions: SendOptions\n private _timeoutHandle: any = undefined\n private currentTime: () => string\n private dateToProtocolTimestamp: (d: Date) => string\n\n retryBuffer: RetryBuffer\n retryStrategy: RetryDelayStrategy\n\n constructor(\n private transport: Transport,\n org: string,\n bucket: string,\n precision: WritePrecisionType,\n writeOptions?: Partial\n ) {\n this.path = `/api/v2/write?org=${encodeURIComponent(\n org\n )}&bucket=${encodeURIComponent(bucket)}&precision=${precision}`\n if (writeOptions?.consistency) {\n this.path += `&consistency=${encodeURIComponent(\n writeOptions.consistency\n )}`\n }\n this.writeOptions = {\n ...DEFAULT_WriteOptions,\n ...writeOptions,\n }\n this.currentTime = currentTime[precision]\n this.dateToProtocolTimestamp = dateToProtocolTimestamp[precision]\n if (this.writeOptions.defaultTags) {\n this.useDefaultTags(this.writeOptions.defaultTags)\n }\n this.sendOptions = {\n method: 'POST',\n headers: {\n 'content-type': 'text/plain; charset=utf-8',\n ...writeOptions?.headers,\n },\n gzipThreshold: this.writeOptions.gzipThreshold,\n }\n\n const scheduleNextSend = (): void => {\n if (this.writeOptions.flushInterval > 0) {\n this._clearFlushTimeout()\n /* istanbul ignore else manually reviewed, hard to reproduce */\n if (!this.closed) {\n this._timeoutHandle = setTimeout(\n () =>\n this.sendBatch(\n this.writeBuffer.reset(),\n this.writeOptions.maxRetries\n ).catch((_e) => {\n // an error is logged in case of failure, avoid UnhandledPromiseRejectionWarning\n }),\n this.writeOptions.flushInterval\n )\n }\n }\n }\n // write buffer\n this.writeBuffer = new WriteBuffer(\n this.writeOptions.batchSize,\n this.writeOptions.maxBatchBytes,\n (lines) => {\n this._clearFlushTimeout()\n return this.sendBatch(lines, this.writeOptions.maxRetries)\n },\n scheduleNextSend\n )\n this.sendBatch = this.sendBatch.bind(this)\n // retry buffer\n this.retryStrategy = createRetryDelayStrategy(this.writeOptions)\n this.retryBuffer = new RetryBuffer(\n this.writeOptions.maxBufferLines,\n this.sendBatch,\n this.writeOptions.writeRetrySkipped\n )\n }\n\n sendBatch(\n lines: string[],\n retryAttempts: number,\n expires: number = Date.now() + this.writeOptions.maxRetryTime\n ): Promise {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self: WriteApiImpl = this\n const failedAttempts = self.writeOptions.maxRetries + 1 - retryAttempts\n if (!this.closed && lines.length > 0) {\n if (expires <= Date.now()) {\n const error = new Error('Max retry time exceeded.')\n const onRetry = self.writeOptions.writeFailed.call(\n self,\n error,\n lines,\n failedAttempts,\n expires\n )\n if (onRetry) {\n return onRetry\n }\n Log.error(\n `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n error\n )\n return Promise.reject(error)\n }\n return new Promise((resolve, reject) => {\n let responseStatusCode: number | undefined\n const callbacks = {\n responseStarted(_headers: Headers, statusCode?: number): void {\n responseStatusCode = statusCode\n },\n error(error: Error): void {\n // call the writeFailed listener and check if we can retry\n const onRetry = self.writeOptions.writeFailed.call(\n self,\n error,\n lines,\n failedAttempts,\n expires\n )\n if (onRetry) {\n onRetry.then(resolve, reject)\n return\n }\n // ignore informational message about the state of InfluxDB\n // enterprise cluster, if present\n if (\n error instanceof HttpError &&\n error.json &&\n typeof error.json.error === 'string' &&\n error.json.error.includes('hinted handoff queue not empty')\n ) {\n Log.warn('Write to InfluxDB returns: ' + error.json.error)\n responseStatusCode = 204\n callbacks.complete()\n return\n }\n // retry if possible\n if (\n !self.closed &&\n retryAttempts > 0 &&\n (!(error instanceof HttpError) ||\n (error as HttpError).statusCode >= 429)\n ) {\n Log.warn(\n `Write to InfluxDB failed (attempt: ${failedAttempts}).`,\n error\n )\n self.retryBuffer.addLines(\n lines,\n retryAttempts - 1,\n self.retryStrategy.nextDelay(error, failedAttempts),\n expires\n )\n reject(error)\n return\n }\n Log.error(`Write to InfluxDB failed.`, error)\n reject(error)\n },\n complete(): void {\n // older implementations of transport do not report status code\n if (responseStatusCode == 204 || responseStatusCode == undefined) {\n self.writeOptions.writeSuccess.call(self, lines)\n self.retryStrategy.success()\n resolve()\n } else {\n const message = `204 HTTP response status code expected, but ${responseStatusCode} returned`\n const error = new HttpError(\n responseStatusCode,\n message,\n undefined,\n '0'\n )\n error.message = message\n callbacks.error(error)\n }\n },\n }\n this.transport.send(\n this.path,\n lines.join('\\n'),\n this.sendOptions,\n callbacks\n )\n })\n } else {\n return Promise.resolve()\n }\n }\n\n private _clearFlushTimeout(): void {\n if (this._timeoutHandle !== undefined) {\n clearTimeout(this._timeoutHandle)\n this._timeoutHandle = undefined\n }\n }\n\n writeRecord(record: string): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n this.writeBuffer.add(record)\n }\n writeRecords(records: ArrayLike): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n for (let i = 0; i < records.length; i++) {\n this.writeBuffer.add(records[i])\n }\n }\n writePoint(point: Point): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n const line = point.toLineProtocol(this)\n if (line) this.writeBuffer.add(line)\n }\n writePoints(points: ArrayLike): void {\n if (this.closed) {\n throw new Error('writeApi: already closed!')\n }\n for (let i = 0; i < points.length; i++) {\n const line = points[i].toLineProtocol(this)\n if (line) this.writeBuffer.add(line)\n }\n }\n async flush(withRetryBuffer?: boolean): Promise {\n await this.writeBuffer.flush()\n if (withRetryBuffer) {\n return await this.retryBuffer.flush()\n }\n }\n close(): Promise {\n const retVal = this.writeBuffer.flush().finally(() => {\n const remaining = this.retryBuffer.close()\n if (remaining) {\n Log.error(\n `Retry buffer closed with ${remaining} items that were not written to InfluxDB!`,\n null\n )\n }\n this.closed = true\n })\n return retVal\n }\n dispose(): number {\n this._clearFlushTimeout()\n this.closed = true\n return this.retryBuffer.close() + this.writeBuffer.length\n }\n\n // PointSettings\n defaultTags: {[key: string]: string} | undefined\n useDefaultTags(tags: {[key: string]: string}): WriteApi {\n this.defaultTags = tags\n return this\n }\n convertTime(value: string | number | Date | undefined): string | undefined {\n if (value === undefined) {\n return this.currentTime()\n } else if (typeof value === 'string') {\n return value.length > 0 ? value : undefined\n } else if (value instanceof Date) {\n return this.dateToProtocolTimestamp(value)\n } else if (typeof value === 'number') {\n return String(Math.floor(value))\n } else {\n return String(value)\n }\n }\n}\n","import {CommunicationObserver, Headers} from '../results'\n\ntype CompleteObserver = Omit<\n Required>,\n 'useCancellable' | 'useResume'\n> &\n Pick, 'useResume' | 'useCancellable'>\n\nexport default function completeCommunicationObserver(\n callbacks: Partial> = {}\n): CompleteObserver {\n let state = 0\n const retVal: CompleteObserver = {\n next: (data: any): void | boolean => {\n if (\n state === 0 &&\n callbacks.next &&\n data !== null &&\n data !== undefined\n ) {\n return callbacks.next(data)\n }\n },\n error: (error: Error): void => {\n /* istanbul ignore else propagate error at most once */\n if (state === 0) {\n state = 1\n /* istanbul ignore else safety check */\n if (callbacks.error) callbacks.error(error)\n }\n },\n complete: (): void => {\n if (state === 0) {\n state = 2\n /* istanbul ignore else safety check */\n if (callbacks.complete) callbacks.complete()\n }\n },\n responseStarted: (headers: Headers, statusCode?: number): void => {\n if (callbacks.responseStarted)\n callbacks.responseStarted(headers, statusCode)\n },\n }\n if (callbacks.useCancellable) {\n retVal.useCancellable = callbacks.useCancellable.bind(callbacks)\n }\n if (callbacks.useResume) {\n retVal.useResume = callbacks.useResume.bind(callbacks)\n }\n return retVal\n}\n","import {Transport, SendOptions} from '../../transport'\nimport {ConnectionOptions} from '../../options'\nimport {AbortError, HttpError} from '../../errors'\nimport completeCommunicationObserver from '../completeCommunicationObserver'\nimport {Log} from '../../util/logger'\nimport {\n ChunkCombiner,\n CommunicationObserver,\n createTextDecoderCombiner,\n Headers,\n ResponseStartedFn,\n} from '../../results'\n\nfunction getResponseHeaders(response: Response): Headers {\n const headers: Headers = {}\n response.headers.forEach((value: string, key: string) => {\n const previous = headers[key]\n if (previous === undefined) {\n headers[key] = value\n } else if (Array.isArray(previous)) {\n previous.push(value)\n } else {\n headers[key] = [previous, value]\n }\n })\n return headers\n}\n\n/**\n * Transport layer that use browser fetch.\n */\nexport default class FetchTransport implements Transport {\n chunkCombiner: ChunkCombiner = createTextDecoderCombiner()\n private defaultHeaders: {[key: string]: string}\n private url: string\n constructor(private connectionOptions: ConnectionOptions) {\n this.defaultHeaders = {\n 'content-type': 'application/json; charset=utf-8',\n // 'User-Agent': `influxdb-client-js/${CLIENT_LIB_VERSION}`, // user-agent can hardly be customized https://github.com/influxdata/influxdb-client-js/issues/262\n ...connectionOptions.headers,\n }\n if (this.connectionOptions.token) {\n this.defaultHeaders['Authorization'] =\n 'Token ' + this.connectionOptions.token\n }\n this.url = String(this.connectionOptions.url)\n if (this.url.endsWith('/')) {\n this.url = this.url.substring(0, this.url.length - 1)\n }\n // https://github.com/influxdata/influxdb-client-js/issues/263\n // don't allow /api/v2 suffix to avoid future problems\n if (this.url.endsWith('/api/v2')) {\n this.url = this.url.substring(0, this.url.length - '/api/v2'.length)\n Log.warn(\n `Please remove '/api/v2' context path from InfluxDB base url, using ${this.url} !`\n )\n }\n }\n send(\n path: string,\n body: string,\n options: SendOptions,\n callbacks?: Partial> | undefined\n ): void {\n const observer = completeCommunicationObserver(callbacks)\n let cancelled = false\n let signal = (options as any).signal\n let pausePromise: Promise | undefined\n const resumeQuickly = () => {}\n let resume = resumeQuickly\n if (callbacks && callbacks.useCancellable) {\n const controller = new AbortController()\n if (!signal) {\n signal = controller.signal\n options = {...options, signal}\n }\n // resume data reading so that it can exit on abort signal\n signal.addEventListener('abort', () => {\n resume()\n })\n callbacks.useCancellable({\n cancel() {\n cancelled = true\n controller.abort()\n },\n isCancelled() {\n return cancelled || signal.aborted\n },\n })\n }\n this.fetch(path, body, options)\n .then(async (response) => {\n if (callbacks?.responseStarted) {\n observer.responseStarted(\n getResponseHeaders(response),\n response.status\n )\n }\n await this.throwOnErrorResponse(response)\n if (response.body) {\n const reader = response.body.getReader()\n let chunk: ReadableStreamReadResult\n do {\n if (pausePromise) {\n await pausePromise\n }\n if (cancelled) {\n break\n }\n chunk = await reader.read()\n if (observer.next(chunk.value) === false) {\n const useResume = observer.useResume\n if (!useResume) {\n const msg = 'Unable to pause, useResume is not configured!'\n await reader.cancel(msg)\n return Promise.reject(new Error(msg))\n }\n pausePromise = new Promise((resolve) => {\n resume = () => {\n resolve()\n pausePromise = undefined\n resume = resumeQuickly\n }\n useResume(resume)\n })\n }\n } while (!chunk.done)\n } else if (response.arrayBuffer) {\n const buffer = await response.arrayBuffer()\n observer.next(new Uint8Array(buffer))\n } else {\n const text = await response.text()\n observer.next(new TextEncoder().encode(text))\n }\n })\n .catch((e) => {\n if (!cancelled) {\n observer.error(e)\n }\n })\n .finally(() => observer.complete())\n }\n private async throwOnErrorResponse(response: Response): Promise {\n if (response.status >= 300) {\n let text = ''\n try {\n text = await response.text()\n if (!text) {\n const headerError = response.headers.get('x-influxdb-error')\n if (headerError) {\n text = headerError\n }\n }\n } catch (e) {\n Log.warn('Unable to receive error body', e)\n throw new HttpError(\n response.status,\n response.statusText,\n undefined,\n response.headers.get('retry-after'),\n response.headers.get('content-type')\n )\n }\n throw new HttpError(\n response.status,\n response.statusText,\n text,\n response.headers.get('retry-after'),\n response.headers.get('content-type')\n )\n }\n }\n\n async *iterate(\n path: string,\n body: string,\n options: SendOptions\n ): AsyncIterableIterator {\n const response = await this.fetch(path, body, options)\n await this.throwOnErrorResponse(response)\n if (response.body) {\n const reader = response.body.getReader()\n for (;;) {\n const {value, done} = await reader.read()\n if (done) {\n break\n }\n if (options.signal?.aborted) {\n await response.body.cancel()\n throw new AbortError()\n }\n yield value\n }\n } else if (response.arrayBuffer) {\n const buffer = await response.arrayBuffer()\n yield new Uint8Array(buffer)\n } else {\n const text = await response.text()\n yield new TextEncoder().encode(text)\n }\n }\n\n async request(\n path: string,\n body: any,\n options: SendOptions,\n responseStarted?: ResponseStartedFn\n ): Promise {\n const response = await this.fetch(path, body, options)\n const {headers} = response\n const responseContentType = headers.get('content-type') || ''\n if (responseStarted) {\n responseStarted(getResponseHeaders(response), response.status)\n }\n\n await this.throwOnErrorResponse(response)\n const responseType = options.headers?.accept ?? responseContentType\n if (responseType.includes('json')) {\n return await response.json()\n } else if (\n responseType.includes('text') ||\n responseType.startsWith('application/csv')\n ) {\n return await response.text()\n }\n }\n\n private fetch(\n path: string,\n body: any,\n options: SendOptions\n ): Promise {\n const {method, headers, ...other} = options\n const url = `${this.url}${path}`\n const request: RequestInit = {\n method: method,\n body:\n method === 'GET' || method === 'HEAD'\n ? undefined\n : typeof body === 'string'\n ? body\n : JSON.stringify(body),\n headers: {\n ...this.defaultHeaders,\n ...headers,\n },\n credentials: 'omit' as const,\n // override with custom transport options\n ...this.connectionOptions.transportOptions,\n // allow to specify custom options, such as signal, in SendOptions\n ...other,\n }\n this.requestDecorator(request, options, url)\n return fetch(url, request)\n }\n\n /**\n * RequestDecorator allows to modify requests before sending.\n *\n * The following example shows a function that adds gzip\n * compression of requests using pako.js.\n *\n * ```ts\n * const client = new InfluxDB({url: 'http://a'})\n * client.transport.requestDecorator = function(request, options) {\n * const body = request.body\n * if (\n * typeof body === 'string' &&\n * options.gzipThreshold !== undefined &&\n * body.length > options.gzipThreshold\n * ) {\n * request.headers['content-encoding'] = 'gzip'\n * request.body = pako.gzip(body)\n * }\n * }\n * ```\n */\n public requestDecorator: (\n request: RequestInit,\n options: SendOptions,\n url: string\n ) => void = function () {}\n}\n","import {Observable} from '../observable'\nimport QueryApi, {QueryOptions} from '../QueryApi'\nimport {Transport} from '../transport'\nimport {\n CommunicationObserver,\n FluxResultObserver,\n FluxTableMetaData,\n Row,\n AnnotatedCSVResponse,\n IterableResultExecutor,\n} from '../results'\nimport {ParameterizedQuery} from '../query/flux'\nimport {APIExecutor} from '../results/ObservableQuery'\n\nconst DEFAULT_dialect: any = {\n header: true,\n delimiter: ',',\n quoteChar: '\"',\n commentPrefix: '#',\n annotations: ['datatype', 'group', 'default'],\n}\n\nexport class QueryApiImpl implements QueryApi {\n private options: QueryOptions\n constructor(\n private transport: Transport,\n private createCSVResponse: (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ) => AnnotatedCSVResponse,\n org: string | QueryOptions\n ) {\n this.options = typeof org === 'string' ? {org} : org\n }\n\n with(options: Partial): QueryApi {\n return new QueryApiImpl(this.transport, this.createCSVResponse, {\n ...this.options,\n ...options,\n })\n }\n\n response(query: string | ParameterizedQuery): AnnotatedCSVResponse {\n const {org, type, gzip, headers} = this.options\n const path = `/api/v2/query?org=${encodeURIComponent(org)}`\n const body = JSON.stringify(\n this.decorateRequest({\n query: query.toString(),\n dialect: DEFAULT_dialect,\n type,\n })\n )\n const options = {\n method: 'POST',\n headers: {\n 'content-type': 'application/json; encoding=utf-8',\n 'accept-encoding': gzip ? 'gzip' : 'identity',\n ...headers,\n },\n }\n return this.createCSVResponse(\n (consumer) => this.transport.send(path, body, options, consumer),\n () => this.transport.iterate(path, body, options)\n )\n }\n\n iterateLines(query: string | ParameterizedQuery): AsyncIterable {\n return this.response(query).iterateLines()\n }\n iterateRows(query: string | ParameterizedQuery): AsyncIterable {\n return this.response(query).iterateRows()\n }\n lines(query: string | ParameterizedQuery): Observable {\n return this.response(query).lines()\n }\n\n rows(query: string | ParameterizedQuery): Observable {\n return this.response(query).rows()\n }\n\n queryLines(\n query: string | ParameterizedQuery,\n consumer: CommunicationObserver\n ): void {\n return this.response(query).consumeLines(consumer)\n }\n\n queryRows(\n query: string | ParameterizedQuery,\n consumer: FluxResultObserver\n ): void {\n return this.response(query).consumeRows(consumer)\n }\n\n collectRows(\n query: string | ParameterizedQuery,\n rowMapper?: (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined\n ): Promise> {\n return this.response(query).collectRows(rowMapper)\n }\n\n collectLines(query: string | ParameterizedQuery): Promise> {\n return this.response(query).collectLines()\n }\n\n queryRaw(query: string | ParameterizedQuery): Promise {\n const {org, type, gzip, headers} = this.options\n return this.transport.request(\n `/api/v2/query?org=${encodeURIComponent(org)}`,\n JSON.stringify(\n this.decorateRequest({\n query: query.toString(),\n dialect: DEFAULT_dialect,\n type,\n })\n ),\n {\n method: 'POST',\n headers: {\n accept: 'text/csv',\n 'accept-encoding': gzip ? 'gzip' : 'identity',\n 'content-type': 'application/json; encoding=utf-8',\n ...headers,\n },\n }\n )\n }\n\n private decorateRequest(request: any): any {\n if (typeof this.options.now === 'function') {\n request.now = this.options.now()\n }\n // https://docs.influxdata.com/influxdb/latest/api/#operation/PostQuery requires type\n request.type = this.options.type ?? 'flux'\n return request\n }\n}\n\nexport default QueryApiImpl\n","import {\n CommunicationObserver,\n FluxResultObserver,\n FluxTableMetaData,\n Row,\n linesToTables,\n ChunkCombiner,\n chunksToLines,\n chunksToLinesIterable,\n linesToRowsIterable,\n} from '../results'\nimport {Observable} from '../observable'\nimport {\n AnnotatedCSVResponse,\n IterableResultExecutor,\n} from './AnnotatedCSVResponse'\nimport ObservableQuery, {APIExecutor} from './ObservableQuery'\n\nexport function defaultRowMapping(\n values: string[],\n tableMeta: FluxTableMetaData\n): Record {\n return tableMeta.toObject(values)\n}\n\n/**\n * AnnotatedCsvResponseImpl is an implementation AnnotatedCsvResponse\n * that uses the supplied executor to supply a response data stream.\n */\nexport class AnnotatedCSVResponseImpl implements AnnotatedCSVResponse {\n constructor(\n private executor: APIExecutor,\n private iterableResultExecutor: IterableResultExecutor,\n private chunkCombiner: ChunkCombiner\n ) {}\n iterateLines(): AsyncIterable {\n return chunksToLinesIterable(this.iterableResultExecutor())\n }\n iterateRows(): AsyncIterable {\n return linesToRowsIterable(\n chunksToLinesIterable(this.iterableResultExecutor())\n )\n }\n lines(): Observable {\n return new ObservableQuery(this.executor, (observer) =>\n chunksToLines(observer, this.chunkCombiner)\n )\n }\n\n rows(): Observable {\n return new ObservableQuery(this.executor, (observer) => {\n return chunksToLines(\n linesToTables({\n next(values, tableMeta) {\n observer.next({values, tableMeta})\n },\n error(e) {\n observer.error(e)\n },\n complete() {\n observer.complete()\n },\n }),\n this.chunkCombiner\n )\n })\n }\n\n consumeLines(consumer: CommunicationObserver): void {\n this.executor(chunksToLines(consumer, this.chunkCombiner))\n }\n\n consumeRows(consumer: FluxResultObserver): void {\n this.executor(chunksToLines(linesToTables(consumer), this.chunkCombiner))\n }\n\n collectRows(\n rowMapper: (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined = defaultRowMapping as (\n values: string[],\n tableMeta: FluxTableMetaData\n ) => T | undefined\n ): Promise> {\n const retVal: Array = []\n return new Promise((resolve, reject) => {\n this.consumeRows({\n next(values: string[], tableMeta: FluxTableMetaData): void {\n const toAdd = rowMapper.call(this, values, tableMeta)\n if (toAdd !== undefined) {\n retVal.push(toAdd)\n }\n },\n error(error: Error): void {\n reject(error)\n },\n complete(): void {\n resolve(retVal)\n },\n })\n })\n }\n\n collectLines(): Promise> {\n const retVal: Array = []\n return new Promise((resolve, reject) => {\n this.consumeLines({\n next(line: string): void {\n retVal.push(line)\n },\n error(error: Error): void {\n reject(error)\n },\n complete(): void {\n resolve(retVal)\n },\n })\n })\n }\n}\n","import WriteApi from './WriteApi'\nimport {ClientOptions, WriteOptions, WritePrecisionType} from './options'\nimport WriteApiImpl from './impl/WriteApiImpl'\nimport {IllegalArgumentError} from './errors'\nimport {Transport} from './transport'\n// replaced by ./impl/browser/FetchTransport in browser builds\nimport TransportImpl from './impl/browser/FetchTransport'\nimport QueryApi, {QueryOptions} from './QueryApi'\nimport QueryApiImpl from './impl/QueryApiImpl'\nimport {\n AnnotatedCSVResponse,\n APIExecutor,\n IterableResultExecutor,\n} from './results'\nimport {AnnotatedCSVResponseImpl} from './results/AnnotatedCSVResponseImpl'\n\n/**\n * InfluxDB entry point that configures communication with InfluxDB server\n * and provide APIs to write and query data.\n */\nexport default class InfluxDB {\n private _options: ClientOptions\n readonly transport: Transport\n readonly processCSVResponse: (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ) => AnnotatedCSVResponse\n\n /**\n * Creates influxdb client options from an options object or url.\n * @param options - client options\n */\n constructor(options: ClientOptions | string) {\n if (typeof options === 'string') {\n this._options = {url: options}\n } else if (options !== null && typeof options === 'object') {\n this._options = options\n } else {\n throw new IllegalArgumentError('No url or configuration specified!')\n }\n const url = this._options.url\n if (typeof url !== 'string')\n throw new IllegalArgumentError('No url specified!')\n if (url.endsWith('/')) this._options.url = url.substring(0, url.length - 1)\n this.transport = this._options.transport ?? new TransportImpl(this._options)\n this.processCSVResponse = (\n executor: APIExecutor,\n iterableResultExecutor: IterableResultExecutor\n ): AnnotatedCSVResponse =>\n new AnnotatedCSVResponseImpl(\n executor,\n iterableResultExecutor,\n this.transport.chunkCombiner\n )\n }\n\n /**\n * Creates WriteApi for the supplied organization and bucket. BEWARE that returned instances must be closed\n * in order to flush the remaining data and close already scheduled retry executions.\n *\n * @remarks\n * Use {@link WriteOptions} to customize retry strategy options, data chunking\n * and flushing options. See {@link DEFAULT_WriteOptions} to see the defaults.\n *\n * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/write.mjs | write example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/writeAdvanced.mjs | writeAdvanced example},\n * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example}.\n *\n * @param org - Specifies the destination organization for writes. Takes either the ID or Name interchangeably.\n * @param bucket - The destination bucket for writes.\n * @param precision - Timestamp precision for line items.\n * @param writeOptions - Custom write options.\n * @returns WriteApi instance\n */\n getWriteApi(\n org: string,\n bucket: string,\n precision: WritePrecisionType = 'ns',\n writeOptions?: Partial\n ): WriteApi {\n return new WriteApiImpl(\n this.transport,\n org,\n bucket,\n precision,\n writeOptions ?? this._options.writeOptions\n )\n }\n\n /**\n * Creates QueryApi for the supplied organization .\n *\n * @remarks\n * See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/query.ts | query.ts example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/queryWithParams.mjs | queryWithParams.mjs example},\n * {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/rxjs-query.ts | rxjs-query.ts example},\n * and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example},\n *\n * @param org - organization or query options\n * @returns QueryApi instance\n */\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,KAAK,SAAS,YAChC,CACF,CAcA,YAAYH,EAAsC,CAChD,OAAO,IAAIK,GAAa,KAAK,UAAW,KAAK,mBAAoBL,CAAG,CACtE,CACF","names":["src_exports","__export","AbortError","DEFAULT_ConnectionOptions","DEFAULT_RetryDelayStrategyOptions","DEFAULT_WriteOptions","FLUX_VALUE","HttpError","IllegalArgumentError","InfluxDB","LineSplitter","Log","Point","RequestTimedOutError","UNKNOWN_COLUMN","canRetryHttpCall","chunksToLines","chunksToLinesIterable","consoleLogger","convertTimeToNanos","createFluxTableColumn","createFluxTableMetaData","createTextDecoderCombiner","currentTime","dateToProtocolTimestamp","escape","flux","fluxBool","fluxDateTime","fluxDuration","fluxExpression","fluxFloat","fluxInteger","fluxRegExp","fluxString","getRetryDelay","isStatusCodeRetriable","linesToRowsIterable","linesToTables","newFluxTableColumn","sanitizeFloat","sanitizeInteger","serializeDateTimeAsDate","serializeDateTimeAsNumber","serializeDateTimeAsString","setLogger","stringToLines","symbolObservable","toFluxValue","typeSerializers","useProcessHrtime","createTextDecoderCombiner","decoder","first","second","retVal","chunk","start","end","chunksToLines","target","chunkCombiner","chunks","createTextDecoderCombiner","previous","finished","quoted","paused","resumeChunks","bufferReceived","chunk","index","start","c","end","retVal","e","error","cancellable","x","chunksToLinesIterable","source","chunkCombiner","chunks","createTextDecoderCombiner","previous","quoted","chunk","index","start","c","end","LineSplitter","val","line","quoteCount","startIndex","values","count","i","c","start","end","identity","x","typeSerializers","FluxTableColumnImpl","row","_a","val","UNKNOWN_COLUMN","newFluxTableColumn","createFluxTableColumn","object","_b","retVal","retriableStatusCodes","isStatusCodeRetriable","statusCode","IllegalArgumentError","message","HttpError","statusMessage","body","retryAfter","contentType","e","RETRY_CODES","canRetryHttpCall","error","getRetryDelay","retryJitter","retVal","RequestTimedOutError","AbortError","serializeDateTimeAsDate","typeSerializers","x","serializeDateTimeAsNumber","serializeDateTimeAsString","FluxTableMetaDataImpl","columns","col","i","label","errorOnMissingColumn","IllegalArgumentError","UNKNOWN_COLUMN","row","acc","column","createFluxTableMetaData","linesToTables","consumer","splitter","LineSplitter","columns","expectMeta","firstColumnIndex","lastMeta","retVal","error","line","values","size","i","newFluxTableColumn","createFluxTableMetaData","linesToRowsIterable","source","splitter","LineSplitter","columns","expectMeta","firstColumnIndex","lastMeta","line","values","size","i","newFluxTableColumn","createFluxTableMetaData","stringToLines","source","target","quoted","start","index","c","end","symbolObservable","QuerySubscription","observer","executor","value","e","c","_a","noop","completeObserver","next","error","complete","ObservableQuery","decorator","observerOrNext","symbolObservable","DEFAULT_ConnectionOptions","DEFAULT_RetryDelayStrategyOptions","DEFAULT_WriteOptions","createEscaper","characters","replacements","value","retVal","from","i","found","createQuotedEscaper","escaper","escape","zeroPadding","useProcessHrtime","use","lastMillis","stepsInMillis","nanos","millis","zeroPadding","micros","seconds","currentTime","dateToProtocolTimestamp","d","convertTimeToNanos","value","consoleLogger","message","error","provider","Log","setLogger","logger","previous","FLUX_VALUE","FluxParameter","fluxValue","isFluxParameterLike","value","sanitizeString","retVal","i","prepareRetVal","c","fluxString","sanitizeFloat","val","strVal","hasDot","fluxFloat","sanitizeInteger","negative","fluxInteger","sanitizeDateTime","fluxDateTime","fluxDuration","sanitizeRegExp","fluxRegExp","fluxBool","fluxExpression","toFluxValue","flux","strings","values","parts","partIndex","text","sanitized","Point","measurementName","name","value","val","strVal","code","escape","settings","fieldsLine","x","tagsLine","tags","time","convertTimeToNanos","line","RetryStrategyImpl","options","DEFAULT_RetryDelayStrategyOptions","error","failedAttempts","delay","getRetryDelay","nextDelay","i","createRetryDelayStrategy","findShrinkCandidate","first","parent","found","currentParent","RetryBuffer","maxLines","retryLines","onShrink","lines","retryCount","delay","expires","retryTime","origSize","newSize","Log","toAdd","current","toRetry","utf8Length","s","retVal","i","code","WriteBuffer","maxChunkRecords","maxBatchBytes","flushFn","scheduleSend","record","size","utf8Length","_e","lines","retVal","WriteApiImpl","transport","org","bucket","precision","writeOptions","DEFAULT_WriteOptions","currentTime","dateToProtocolTimestamp","scheduleNextSend","createRetryDelayStrategy","RetryBuffer","retryAttempts","expires","self","failedAttempts","error","onRetry","Log","resolve","reject","responseStatusCode","callbacks","_headers","statusCode","HttpError","message","records","i","point","line","points","withRetryBuffer","remaining","tags","value","completeCommunicationObserver","callbacks","state","retVal","data","error","headers","statusCode","getResponseHeaders","response","headers","value","key","previous","FetchTransport","connectionOptions","createTextDecoderCombiner","Log","path","body","options","callbacks","observer","completeCommunicationObserver","cancelled","signal","pausePromise","resumeQuickly","resume","controller","reader","chunk","useResume","msg","resolve","buffer","text","e","headerError","HttpError","_a","done","AbortError","responseStarted","_b","responseContentType","responseType","method","other","url","request","DEFAULT_dialect","QueryApiImpl","transport","createCSVResponse","org","options","query","type","gzip","headers","path","body","consumer","rowMapper","request","_a","QueryApiImpl_default","defaultRowMapping","values","tableMeta","AnnotatedCSVResponseImpl","executor","iterableResultExecutor","chunkCombiner","chunksToLinesIterable","linesToRowsIterable","ObservableQuery","observer","chunksToLines","linesToTables","e","consumer","rowMapper","retVal","resolve","reject","toAdd","error","line","InfluxDB","options","_a","IllegalArgumentError","url","FetchTransport","executor","iterableResultExecutor","AnnotatedCSVResponseImpl","org","bucket","precision","writeOptions","WriteApiImpl","QueryApiImpl_default"]} \ No newline at end of file diff --git a/software/flow/node_modules/gridstack/dist/gridstack-extra.css b/software/flow/node_modules/gridstack/dist/gridstack-extra.css new file mode 100644 index 0000000..46fb987 --- /dev/null +++ b/software/flow/node_modules/gridstack/dist/gridstack-extra.css @@ -0,0 +1,555 @@ +/*! + * gridstack 0.6.4 extra CSS for [2-11] columns (non default) + * https://gridstackjs.com/ + * (c) 2014-2020 Alain Dumesny, Dylan Weiss, Pavel Reznikov + * gridstack.js may be freely distributed under the MIT license. +*/ +.grid-stack.grid-stack-2 > .grid-stack-item { + min-width: 50%; } + .grid-stack.grid-stack-2 > .grid-stack-item[data-gs-width='1'] { + width: 50%; } + .grid-stack.grid-stack-2 > .grid-stack-item[data-gs-x='1'] { + left: 50%; } + .grid-stack.grid-stack-2 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 50%; } + .grid-stack.grid-stack-2 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 50%; } + .grid-stack.grid-stack-2 > .grid-stack-item[data-gs-width='2'] { + width: 100%; } + .grid-stack.grid-stack-2 > .grid-stack-item[data-gs-x='2'] { + left: 100%; } + .grid-stack.grid-stack-2 > .grid-stack-item[data-gs-min-width='2'] { + min-width: 100%; } + .grid-stack.grid-stack-2 > .grid-stack-item[data-gs-max-width='2'] { + max-width: 100%; } + +.grid-stack.grid-stack-3 > .grid-stack-item { + min-width: 33.3333333333%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-width='1'] { + width: 33.3333333333%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-x='1'] { + left: 33.3333333333%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 33.3333333333%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 33.3333333333%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-width='2'] { + width: 66.6666666667%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-x='2'] { + left: 66.6666666667%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-min-width='2'] { + min-width: 66.6666666667%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-max-width='2'] { + max-width: 66.6666666667%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-width='3'] { + width: 100%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-x='3'] { + left: 100%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-min-width='3'] { + min-width: 100%; } + .grid-stack.grid-stack-3 > .grid-stack-item[data-gs-max-width='3'] { + max-width: 100%; } + +.grid-stack.grid-stack-4 > .grid-stack-item { + min-width: 25%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-width='1'] { + width: 25%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-x='1'] { + left: 25%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 25%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 25%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-width='2'] { + width: 50%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-x='2'] { + left: 50%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-min-width='2'] { + min-width: 50%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-max-width='2'] { + max-width: 50%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-width='3'] { + width: 75%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-x='3'] { + left: 75%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-min-width='3'] { + min-width: 75%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-max-width='3'] { + max-width: 75%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-width='4'] { + width: 100%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-x='4'] { + left: 100%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-min-width='4'] { + min-width: 100%; } + .grid-stack.grid-stack-4 > .grid-stack-item[data-gs-max-width='4'] { + max-width: 100%; } + +.grid-stack.grid-stack-5 > .grid-stack-item { + min-width: 20%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-width='1'] { + width: 20%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-x='1'] { + left: 20%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 20%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 20%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-width='2'] { + width: 40%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-x='2'] { + left: 40%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-min-width='2'] { + min-width: 40%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-max-width='2'] { + max-width: 40%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-width='3'] { + width: 60%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-x='3'] { + left: 60%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-min-width='3'] { + min-width: 60%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-max-width='3'] { + max-width: 60%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-width='4'] { + width: 80%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-x='4'] { + left: 80%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-min-width='4'] { + min-width: 80%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-max-width='4'] { + max-width: 80%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-width='5'] { + width: 100%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-x='5'] { + left: 100%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-min-width='5'] { + min-width: 100%; } + .grid-stack.grid-stack-5 > .grid-stack-item[data-gs-max-width='5'] { + max-width: 100%; } + +.grid-stack.grid-stack-6 > .grid-stack-item { + min-width: 16.6666666667%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='1'] { + width: 16.6666666667%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='1'] { + left: 16.6666666667%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 16.6666666667%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 16.6666666667%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='2'] { + width: 33.3333333333%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='2'] { + left: 33.3333333333%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='2'] { + min-width: 33.3333333333%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='2'] { + max-width: 33.3333333333%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='3'] { + width: 50%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='3'] { + left: 50%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='3'] { + min-width: 50%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='3'] { + max-width: 50%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='4'] { + width: 66.6666666667%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='4'] { + left: 66.6666666667%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='4'] { + min-width: 66.6666666667%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='4'] { + max-width: 66.6666666667%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='5'] { + width: 83.3333333333%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='5'] { + left: 83.3333333333%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='5'] { + min-width: 83.3333333333%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='5'] { + max-width: 83.3333333333%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-width='6'] { + width: 100%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-x='6'] { + left: 100%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-min-width='6'] { + min-width: 100%; } + .grid-stack.grid-stack-6 > .grid-stack-item[data-gs-max-width='6'] { + max-width: 100%; } + +.grid-stack.grid-stack-7 > .grid-stack-item { + min-width: 14.2857142857%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='1'] { + width: 14.2857142857%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='1'] { + left: 14.2857142857%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 14.2857142857%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 14.2857142857%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='2'] { + width: 28.5714285714%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='2'] { + left: 28.5714285714%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='2'] { + min-width: 28.5714285714%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='2'] { + max-width: 28.5714285714%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='3'] { + width: 42.8571428571%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='3'] { + left: 42.8571428571%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='3'] { + min-width: 42.8571428571%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='3'] { + max-width: 42.8571428571%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='4'] { + width: 57.1428571429%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='4'] { + left: 57.1428571429%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='4'] { + min-width: 57.1428571429%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='4'] { + max-width: 57.1428571429%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='5'] { + width: 71.4285714286%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='5'] { + left: 71.4285714286%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='5'] { + min-width: 71.4285714286%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='5'] { + max-width: 71.4285714286%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='6'] { + width: 85.7142857143%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='6'] { + left: 85.7142857143%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='6'] { + min-width: 85.7142857143%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='6'] { + max-width: 85.7142857143%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-width='7'] { + width: 100%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-x='7'] { + left: 100%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-min-width='7'] { + min-width: 100%; } + .grid-stack.grid-stack-7 > .grid-stack-item[data-gs-max-width='7'] { + max-width: 100%; } + +.grid-stack.grid-stack-8 > .grid-stack-item { + min-width: 12.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='1'] { + width: 12.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='1'] { + left: 12.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 12.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 12.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='2'] { + width: 25%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='2'] { + left: 25%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='2'] { + min-width: 25%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='2'] { + max-width: 25%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='3'] { + width: 37.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='3'] { + left: 37.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='3'] { + min-width: 37.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='3'] { + max-width: 37.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='4'] { + width: 50%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='4'] { + left: 50%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='4'] { + min-width: 50%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='4'] { + max-width: 50%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='5'] { + width: 62.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='5'] { + left: 62.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='5'] { + min-width: 62.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='5'] { + max-width: 62.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='6'] { + width: 75%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='6'] { + left: 75%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='6'] { + min-width: 75%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='6'] { + max-width: 75%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='7'] { + width: 87.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='7'] { + left: 87.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='7'] { + min-width: 87.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='7'] { + max-width: 87.5%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-width='8'] { + width: 100%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-x='8'] { + left: 100%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-min-width='8'] { + min-width: 100%; } + .grid-stack.grid-stack-8 > .grid-stack-item[data-gs-max-width='8'] { + max-width: 100%; } + +.grid-stack.grid-stack-9 > .grid-stack-item { + min-width: 11.1111111111%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='1'] { + width: 11.1111111111%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='1'] { + left: 11.1111111111%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 11.1111111111%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 11.1111111111%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='2'] { + width: 22.2222222222%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='2'] { + left: 22.2222222222%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='2'] { + min-width: 22.2222222222%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='2'] { + max-width: 22.2222222222%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='3'] { + width: 33.3333333333%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='3'] { + left: 33.3333333333%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='3'] { + min-width: 33.3333333333%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='3'] { + max-width: 33.3333333333%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='4'] { + width: 44.4444444444%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='4'] { + left: 44.4444444444%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='4'] { + min-width: 44.4444444444%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='4'] { + max-width: 44.4444444444%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='5'] { + width: 55.5555555556%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='5'] { + left: 55.5555555556%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='5'] { + min-width: 55.5555555556%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='5'] { + max-width: 55.5555555556%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='6'] { + width: 66.6666666667%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='6'] { + left: 66.6666666667%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='6'] { + min-width: 66.6666666667%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='6'] { + max-width: 66.6666666667%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='7'] { + width: 77.7777777778%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='7'] { + left: 77.7777777778%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='7'] { + min-width: 77.7777777778%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='7'] { + max-width: 77.7777777778%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='8'] { + width: 88.8888888889%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='8'] { + left: 88.8888888889%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='8'] { + min-width: 88.8888888889%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='8'] { + max-width: 88.8888888889%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-width='9'] { + width: 100%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-x='9'] { + left: 100%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-min-width='9'] { + min-width: 100%; } + .grid-stack.grid-stack-9 > .grid-stack-item[data-gs-max-width='9'] { + max-width: 100%; } + +.grid-stack.grid-stack-10 > .grid-stack-item { + min-width: 10%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='1'] { + width: 10%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='1'] { + left: 10%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 10%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 10%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='2'] { + width: 20%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='2'] { + left: 20%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='2'] { + min-width: 20%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='2'] { + max-width: 20%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='3'] { + width: 30%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='3'] { + left: 30%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='3'] { + min-width: 30%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='3'] { + max-width: 30%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='4'] { + width: 40%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='4'] { + left: 40%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='4'] { + min-width: 40%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='4'] { + max-width: 40%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='5'] { + width: 50%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='5'] { + left: 50%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='5'] { + min-width: 50%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='5'] { + max-width: 50%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='6'] { + width: 60%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='6'] { + left: 60%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='6'] { + min-width: 60%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='6'] { + max-width: 60%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='7'] { + width: 70%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='7'] { + left: 70%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='7'] { + min-width: 70%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='7'] { + max-width: 70%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='8'] { + width: 80%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='8'] { + left: 80%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='8'] { + min-width: 80%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='8'] { + max-width: 80%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='9'] { + width: 90%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='9'] { + left: 90%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='9'] { + min-width: 90%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='9'] { + max-width: 90%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-width='10'] { + width: 100%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-x='10'] { + left: 100%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-min-width='10'] { + min-width: 100%; } + .grid-stack.grid-stack-10 > .grid-stack-item[data-gs-max-width='10'] { + max-width: 100%; } + +.grid-stack.grid-stack-11 > .grid-stack-item { + min-width: 9.0909090909%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='1'] { + width: 9.0909090909%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='1'] { + left: 9.0909090909%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 9.0909090909%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 9.0909090909%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='2'] { + width: 18.1818181818%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='2'] { + left: 18.1818181818%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='2'] { + min-width: 18.1818181818%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='2'] { + max-width: 18.1818181818%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='3'] { + width: 27.2727272727%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='3'] { + left: 27.2727272727%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='3'] { + min-width: 27.2727272727%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='3'] { + max-width: 27.2727272727%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='4'] { + width: 36.3636363636%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='4'] { + left: 36.3636363636%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='4'] { + min-width: 36.3636363636%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='4'] { + max-width: 36.3636363636%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='5'] { + width: 45.4545454545%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='5'] { + left: 45.4545454545%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='5'] { + min-width: 45.4545454545%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='5'] { + max-width: 45.4545454545%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='6'] { + width: 54.5454545455%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='6'] { + left: 54.5454545455%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='6'] { + min-width: 54.5454545455%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='6'] { + max-width: 54.5454545455%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='7'] { + width: 63.6363636364%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='7'] { + left: 63.6363636364%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='7'] { + min-width: 63.6363636364%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='7'] { + max-width: 63.6363636364%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='8'] { + width: 72.7272727273%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='8'] { + left: 72.7272727273%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='8'] { + min-width: 72.7272727273%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='8'] { + max-width: 72.7272727273%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='9'] { + width: 81.8181818182%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='9'] { + left: 81.8181818182%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='9'] { + min-width: 81.8181818182%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='9'] { + max-width: 81.8181818182%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='10'] { + width: 90.9090909091%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='10'] { + left: 90.9090909091%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='10'] { + min-width: 90.9090909091%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='10'] { + max-width: 90.9090909091%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-width='11'] { + width: 100%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-x='11'] { + left: 100%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-min-width='11'] { + min-width: 100%; } + .grid-stack.grid-stack-11 > .grid-stack-item[data-gs-max-width='11'] { + max-width: 100%; } diff --git a/software/flow/node_modules/gridstack/dist/gridstack-extra.min.css b/software/flow/node_modules/gridstack/dist/gridstack-extra.min.css new file mode 100644 index 0000000..b72b0a2 --- /dev/null +++ b/software/flow/node_modules/gridstack/dist/gridstack-extra.min.css @@ -0,0 +1,6 @@ +/*! + * gridstack 0.6.4 extra CSS for [2-11] columns (non default) + * https://gridstackjs.com/ + * (c) 2014-2020 Alain Dumesny, Dylan Weiss, Pavel Reznikov + * gridstack.js may be freely distributed under the MIT license. +*/.grid-stack.grid-stack-2>.grid-stack-item{min-width:50%}.grid-stack.grid-stack-2>.grid-stack-item[data-gs-width='1']{width:50%}.grid-stack.grid-stack-2>.grid-stack-item[data-gs-x='1']{left:50%}.grid-stack.grid-stack-2>.grid-stack-item[data-gs-min-width='1']{min-width:50%}.grid-stack.grid-stack-2>.grid-stack-item[data-gs-max-width='1']{max-width:50%}.grid-stack.grid-stack-2>.grid-stack-item[data-gs-width='2']{width:100%}.grid-stack.grid-stack-2>.grid-stack-item[data-gs-x='2']{left:100%}.grid-stack.grid-stack-2>.grid-stack-item[data-gs-min-width='2']{min-width:100%}.grid-stack.grid-stack-2>.grid-stack-item[data-gs-max-width='2']{max-width:100%}.grid-stack.grid-stack-3>.grid-stack-item{min-width:33.3333333333%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-width='1']{width:33.3333333333%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-x='1']{left:33.3333333333%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-min-width='1']{min-width:33.3333333333%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-max-width='1']{max-width:33.3333333333%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-width='2']{width:66.6666666667%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-x='2']{left:66.6666666667%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-min-width='2']{min-width:66.6666666667%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-max-width='2']{max-width:66.6666666667%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-width='3']{width:100%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-x='3']{left:100%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-min-width='3']{min-width:100%}.grid-stack.grid-stack-3>.grid-stack-item[data-gs-max-width='3']{max-width:100%}.grid-stack.grid-stack-4>.grid-stack-item{min-width:25%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-width='1']{width:25%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-x='1']{left:25%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-min-width='1']{min-width:25%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-max-width='1']{max-width:25%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-width='2']{width:50%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-x='2']{left:50%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-min-width='2']{min-width:50%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-max-width='2']{max-width:50%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-width='3']{width:75%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-x='3']{left:75%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-min-width='3']{min-width:75%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-max-width='3']{max-width:75%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-width='4']{width:100%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-x='4']{left:100%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-min-width='4']{min-width:100%}.grid-stack.grid-stack-4>.grid-stack-item[data-gs-max-width='4']{max-width:100%}.grid-stack.grid-stack-5>.grid-stack-item{min-width:20%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-width='1']{width:20%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-x='1']{left:20%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-min-width='1']{min-width:20%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-max-width='1']{max-width:20%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-width='2']{width:40%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-x='2']{left:40%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-min-width='2']{min-width:40%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-max-width='2']{max-width:40%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-width='3']{width:60%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-x='3']{left:60%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-min-width='3']{min-width:60%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-max-width='3']{max-width:60%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-width='4']{width:80%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-x='4']{left:80%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-min-width='4']{min-width:80%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-max-width='4']{max-width:80%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-width='5']{width:100%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-x='5']{left:100%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-min-width='5']{min-width:100%}.grid-stack.grid-stack-5>.grid-stack-item[data-gs-max-width='5']{max-width:100%}.grid-stack.grid-stack-6>.grid-stack-item{min-width:16.6666666667%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-width='1']{width:16.6666666667%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-x='1']{left:16.6666666667%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-min-width='1']{min-width:16.6666666667%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-max-width='1']{max-width:16.6666666667%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-width='2']{width:33.3333333333%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-x='2']{left:33.3333333333%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-min-width='2']{min-width:33.3333333333%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-max-width='2']{max-width:33.3333333333%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-width='3']{width:50%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-x='3']{left:50%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-min-width='3']{min-width:50%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-max-width='3']{max-width:50%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-width='4']{width:66.6666666667%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-x='4']{left:66.6666666667%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-min-width='4']{min-width:66.6666666667%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-max-width='4']{max-width:66.6666666667%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-width='5']{width:83.3333333333%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-x='5']{left:83.3333333333%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-min-width='5']{min-width:83.3333333333%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-max-width='5']{max-width:83.3333333333%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-width='6']{width:100%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-x='6']{left:100%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-min-width='6']{min-width:100%}.grid-stack.grid-stack-6>.grid-stack-item[data-gs-max-width='6']{max-width:100%}.grid-stack.grid-stack-7>.grid-stack-item{min-width:14.2857142857%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-width='1']{width:14.2857142857%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-x='1']{left:14.2857142857%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-min-width='1']{min-width:14.2857142857%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-max-width='1']{max-width:14.2857142857%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-width='2']{width:28.5714285714%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-x='2']{left:28.5714285714%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-min-width='2']{min-width:28.5714285714%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-max-width='2']{max-width:28.5714285714%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-width='3']{width:42.8571428571%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-x='3']{left:42.8571428571%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-min-width='3']{min-width:42.8571428571%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-max-width='3']{max-width:42.8571428571%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-width='4']{width:57.1428571429%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-x='4']{left:57.1428571429%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-min-width='4']{min-width:57.1428571429%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-max-width='4']{max-width:57.1428571429%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-width='5']{width:71.4285714286%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-x='5']{left:71.4285714286%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-min-width='5']{min-width:71.4285714286%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-max-width='5']{max-width:71.4285714286%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-width='6']{width:85.7142857143%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-x='6']{left:85.7142857143%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-min-width='6']{min-width:85.7142857143%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-max-width='6']{max-width:85.7142857143%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-width='7']{width:100%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-x='7']{left:100%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-min-width='7']{min-width:100%}.grid-stack.grid-stack-7>.grid-stack-item[data-gs-max-width='7']{max-width:100%}.grid-stack.grid-stack-8>.grid-stack-item{min-width:12.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-width='1']{width:12.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-x='1']{left:12.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-min-width='1']{min-width:12.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-max-width='1']{max-width:12.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-width='2']{width:25%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-x='2']{left:25%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-min-width='2']{min-width:25%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-max-width='2']{max-width:25%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-width='3']{width:37.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-x='3']{left:37.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-min-width='3']{min-width:37.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-max-width='3']{max-width:37.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-width='4']{width:50%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-x='4']{left:50%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-min-width='4']{min-width:50%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-max-width='4']{max-width:50%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-width='5']{width:62.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-x='5']{left:62.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-min-width='5']{min-width:62.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-max-width='5']{max-width:62.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-width='6']{width:75%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-x='6']{left:75%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-min-width='6']{min-width:75%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-max-width='6']{max-width:75%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-width='7']{width:87.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-x='7']{left:87.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-min-width='7']{min-width:87.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-max-width='7']{max-width:87.5%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-width='8']{width:100%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-x='8']{left:100%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-min-width='8']{min-width:100%}.grid-stack.grid-stack-8>.grid-stack-item[data-gs-max-width='8']{max-width:100%}.grid-stack.grid-stack-9>.grid-stack-item{min-width:11.1111111111%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-width='1']{width:11.1111111111%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-x='1']{left:11.1111111111%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-min-width='1']{min-width:11.1111111111%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-max-width='1']{max-width:11.1111111111%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-width='2']{width:22.2222222222%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-x='2']{left:22.2222222222%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-min-width='2']{min-width:22.2222222222%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-max-width='2']{max-width:22.2222222222%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-width='3']{width:33.3333333333%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-x='3']{left:33.3333333333%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-min-width='3']{min-width:33.3333333333%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-max-width='3']{max-width:33.3333333333%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-width='4']{width:44.4444444444%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-x='4']{left:44.4444444444%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-min-width='4']{min-width:44.4444444444%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-max-width='4']{max-width:44.4444444444%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-width='5']{width:55.5555555556%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-x='5']{left:55.5555555556%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-min-width='5']{min-width:55.5555555556%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-max-width='5']{max-width:55.5555555556%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-width='6']{width:66.6666666667%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-x='6']{left:66.6666666667%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-min-width='6']{min-width:66.6666666667%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-max-width='6']{max-width:66.6666666667%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-width='7']{width:77.7777777778%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-x='7']{left:77.7777777778%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-min-width='7']{min-width:77.7777777778%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-max-width='7']{max-width:77.7777777778%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-width='8']{width:88.8888888889%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-x='8']{left:88.8888888889%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-min-width='8']{min-width:88.8888888889%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-max-width='8']{max-width:88.8888888889%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-width='9']{width:100%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-x='9']{left:100%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-min-width='9']{min-width:100%}.grid-stack.grid-stack-9>.grid-stack-item[data-gs-max-width='9']{max-width:100%}.grid-stack.grid-stack-10>.grid-stack-item{min-width:10%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-width='1']{width:10%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-x='1']{left:10%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-min-width='1']{min-width:10%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-max-width='1']{max-width:10%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-width='2']{width:20%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-x='2']{left:20%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-min-width='2']{min-width:20%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-max-width='2']{max-width:20%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-width='3']{width:30%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-x='3']{left:30%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-min-width='3']{min-width:30%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-max-width='3']{max-width:30%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-width='4']{width:40%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-x='4']{left:40%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-min-width='4']{min-width:40%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-max-width='4']{max-width:40%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-width='5']{width:50%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-x='5']{left:50%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-min-width='5']{min-width:50%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-max-width='5']{max-width:50%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-width='6']{width:60%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-x='6']{left:60%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-min-width='6']{min-width:60%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-max-width='6']{max-width:60%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-width='7']{width:70%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-x='7']{left:70%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-min-width='7']{min-width:70%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-max-width='7']{max-width:70%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-width='8']{width:80%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-x='8']{left:80%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-min-width='8']{min-width:80%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-max-width='8']{max-width:80%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-width='9']{width:90%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-x='9']{left:90%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-min-width='9']{min-width:90%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-max-width='9']{max-width:90%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-width='10']{width:100%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-x='10']{left:100%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-min-width='10']{min-width:100%}.grid-stack.grid-stack-10>.grid-stack-item[data-gs-max-width='10']{max-width:100%}.grid-stack.grid-stack-11>.grid-stack-item{min-width:9.0909090909%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='1']{width:9.0909090909%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='1']{left:9.0909090909%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='1']{min-width:9.0909090909%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='1']{max-width:9.0909090909%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='2']{width:18.1818181818%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='2']{left:18.1818181818%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='2']{min-width:18.1818181818%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='2']{max-width:18.1818181818%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='3']{width:27.2727272727%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='3']{left:27.2727272727%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='3']{min-width:27.2727272727%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='3']{max-width:27.2727272727%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='4']{width:36.3636363636%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='4']{left:36.3636363636%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='4']{min-width:36.3636363636%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='4']{max-width:36.3636363636%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='5']{width:45.4545454545%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='5']{left:45.4545454545%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='5']{min-width:45.4545454545%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='5']{max-width:45.4545454545%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='6']{width:54.5454545455%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='6']{left:54.5454545455%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='6']{min-width:54.5454545455%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='6']{max-width:54.5454545455%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='7']{width:63.6363636364%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='7']{left:63.6363636364%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='7']{min-width:63.6363636364%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='7']{max-width:63.6363636364%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='8']{width:72.7272727273%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='8']{left:72.7272727273%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='8']{min-width:72.7272727273%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='8']{max-width:72.7272727273%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='9']{width:81.8181818182%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='9']{left:81.8181818182%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='9']{min-width:81.8181818182%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='9']{max-width:81.8181818182%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='10']{width:90.9090909091%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='10']{left:90.9090909091%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='10']{min-width:90.9090909091%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='10']{max-width:90.9090909091%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-width='11']{width:100%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-x='11']{left:100%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-min-width='11']{min-width:100%}.grid-stack.grid-stack-11>.grid-stack-item[data-gs-max-width='11']{max-width:100%} \ No newline at end of file diff --git a/software/flow/node_modules/gridstack/dist/gridstack-poly.js b/software/flow/node_modules/gridstack/dist/gridstack-poly.js new file mode 100644 index 0000000..4888fe8 --- /dev/null +++ b/software/flow/node_modules/gridstack/dist/gridstack-poly.js @@ -0,0 +1,105 @@ +/** gridstack.js 0.6.4 - IE and older browsers Polyfills for this library @preserve*/ +/** + * https://gridstackjs.com/ + * (c) 2019-2020 Alain Dumesny + * gridstack.js may be freely distributed under the MIT license. +*/ + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN +Number.isNaN = Number.isNaN || function isNaN(input) { + return typeof input === 'number' && input !== input; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find +if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + value: function (predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If IsCallable(predicate) is false, throw a TypeError exception. + if (typeof predicate !== 'function') { + throw TypeError('predicate must be a function'); + } + + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + var thisArg = arguments[1]; + + // 5. Let k be 0. + var k = 0; + + // 6. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return kValue. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return kValue; + } + // e. Increase k by 1. + k++; + } + + // 7. Return undefined. + return undefined; + }, + configurable: true, + writable: true + }); +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex +if (!Array.prototype.findIndex) { + Object.defineProperty(Array.prototype, 'findIndex', { + value: function(predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If IsCallable(predicate) is false, throw a TypeError exception. + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + var thisArg = arguments[1]; + + // 5. Let k be 0. + var k = 0; + + // 6. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return k. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return k; + } + // e. Increase k by 1. + k++; + } + + // 7. Return -1. + return -1; + }, + configurable: true, + writable: true + }); +} \ No newline at end of file diff --git a/software/flow/node_modules/gridstack/dist/gridstack-poly.min.js b/software/flow/node_modules/gridstack/dist/gridstack-poly.min.js new file mode 100644 index 0000000..f09db1f --- /dev/null +++ b/software/flow/node_modules/gridstack/dist/gridstack-poly.min.js @@ -0,0 +1,3 @@ +/** gridstack.js 0.6.4 - IE and older browsers Polyfills for this library @preserve*/ +Number.isNaN=Number.isNaN||function(r){return"number"==typeof r&&r!=r},Array.prototype.find||Object.defineProperty(Array.prototype,"find",{value:function(r){if(null==this)throw TypeError('"this" is null or not defined');var e=Object(this),t=e.length>>>0;if("function"!=typeof r)throw TypeError("predicate must be a function");for(var n=arguments[1],i=0;i>>0;if("function"!=typeof r)throw new TypeError("predicate must be a function");for(var n=arguments[1],i=0;i>>0;if("function"!=typeof t)throw TypeError("predicate must be a function");for(var s=arguments[1],o=0;o>>0;if("function"!=typeof t)throw new TypeError("predicate must be a function");for(var s=arguments[1],o=0;ot.clientHeight?t:m.getScrollParent(t.parentNode)},updateScrollPosition:function(t,e,i){var s=t.getBoundingClientRect(),o=window.innerHeight||document.documentElement.clientHeight;if(s.top<0||s.bottom>o){var n=s.bottom-o,r=s.top,a=m.getScrollParent(t);if(null!==a){var h=a.scrollTop;s.top<0&&i<0?t.offsetHeight>o?a.scrollTop+=i:a.scrollTop+=Math.abs(r)>Math.abs(i)?i:r:0o?a.scrollTop+=i:a.scrollTop+=i=t._packY;){this.nodes.slice(0,e).find(m._didCollide,{n:t,newY:i})||(t._dirty=!0,t.y=i),--i}},this):this.nodes.forEach(function(t,e){if(!t.locked)for(;0this.column?t.width=this.column:t.width<1&&(t.width=1),t.height<1&&(t.height=1),t.x<0&&(t.x=0),t.x+t.width>this.column&&(e?t.width=this.column-t.x:t.x=this.column-t.width),t.y<0&&(t.y=0),t},d.prototype._notify=function(){if(!this._batchMode){var t=Array.prototype.slice.call(arguments,0);t[0]=void 0===t[0]?[]:Array.isArray(t[0])?t[0]:[t[0]],t[1]=void 0===t[1]||t[1];var e=t[0].concat(this.getDirtyNodes());this.onchange(e,t[1])}},d.prototype.cleanNodes=function(){this._batchMode||this.nodes.forEach(function(t){delete t._dirty})},d.prototype.getDirtyNodes=function(t){if(t){var e=[];return this.nodes.forEach(function(t){t._dirty&&(t.y===t._origY&&t.x===t._origX&&t.width===t._origW&&t.height===t._origH?delete t._dirty:e.push(t))}),e}return this.nodes.filter(function(t){return t._dirty})},d.prototype.addNode=function(t,e){if(void 0!==(t=this._prepareNode(t)).maxWidth&&(t.width=Math.min(t.width,t.maxWidth)),void 0!==t.maxHeight&&(t.height=Math.min(t.height,t.maxHeight)),void 0!==t.minWidth&&(t.width=Math.max(t.width,t.minWidth)),void 0!==t.minHeight&&(t.height=Math.max(t.height,t.minHeight)),t._id=t._id||++n,t.autoPosition){this._sortNodes();for(var i=0;;++i){var s=i%this.column,o=Math.floor(i/this.column);if(!(s+t.width>this.column)&&!this.nodes.find(m._isAddNodeIntercepted,{x:s,y:o,node:t})){t.x=s,t.y=o,delete t.autoPosition;break}}}return this.nodes.push(t),e&&this._addedNodes.push(t),this._fixCollisions(t),this._packNodes(),this._notify(),t},d.prototype.removeNode=function(t,e){e=void 0===e||e,this._removedNodes.push(t),t._id=null,this.nodes=m.without(this.nodes,t),this._packNodes(),this._notify(t,e)},d.prototype.removeAll=function(t){delete this._layouts,0!==this.nodes.length&&(t=void 0===t||t,this.nodes.forEach(function(t){t._id=null}),this._removedNodes=this.nodes,this.nodes=[],this._notify(this._removedNodes,t))},d.prototype.canMoveNode=function(e,t,i,s,o){if(!this.isNodeChangedPosition(e,t,i,s,o))return!1;var n,r=Boolean(this.nodes.find(function(t){return t.locked}));if(!this.maxRow&&!r)return!0;var a=new d(this.column,null,this.float,0,this.nodes.map(function(t){return t===e?n=f.extend({},t):f.extend({},t)}));if(!n)return!0;a.moveNode(n,t,i,s,o);var h=!0;return r&&(h&=!Boolean(a.nodes.find(function(t){return t!==n&&Boolean(t.locked)&&Boolean(t._dirty)}))),this.maxRow&&(h&=a.getGridHeight()<=this.maxRow),h},d.prototype.canBePlacedWithRespectToHeight=function(t){if(!this.maxRow)return!0;var e=new d(this.column,null,this.float,0,this.nodes.map(function(t){return f.extend({},t)}));return e.addNode(t),e.getGridHeight()<=this.maxRow},d.prototype.isNodeChangedPosition=function(t,e,i,s,o){return"number"!=typeof e&&(e=t.x),"number"!=typeof i&&(i=t.y),"number"!=typeof s&&(s=t.width),"number"!=typeof o&&(o=t.height),void 0!==t.maxWidth&&(s=Math.min(s,t.maxWidth)),void 0!==t.maxHeight&&(o=Math.min(o,t.maxHeight)),void 0!==t.minWidth&&(s=Math.max(s,t.minWidth)),void 0!==t.minHeight&&(o=Math.max(o,t.minHeight)),t.x!==e||t.y!==i||t.width!==s||t.height!==o},d.prototype.moveNode=function(t,e,i,s,o,n){if("number"!=typeof e&&(e=t.x),"number"!=typeof i&&(i=t.y),"number"!=typeof s&&(s=t.width),"number"!=typeof o&&(o=t.height),void 0!==t.maxWidth&&(s=Math.min(s,t.maxWidth)),void 0!==t.maxHeight&&(o=Math.min(o,t.maxHeight)),void 0!==t.minWidth&&(s=Math.max(s,t.minWidth)),void 0!==t.minHeight&&(o=Math.max(o,t.minHeight)),t.x===e&&t.y===i&&t.width===s&&t.height===o)return t;var r=t.width!==s;return t._dirty=!0,t.x=e,t.y=i,t.width=s,t.height=o,t.lastTriedX=e,t.lastTriedY=i,t.lastTriedWidth=s,t.lastTriedHeight=o,t=this._prepareNode(t,r),this._fixCollisions(t),n||(this._packNodes(),this._notify()),t},d.prototype.getGridHeight=function(){return this.nodes.reduce(function(t,e){return Math.max(t,e.y+e.height)},0)},d.prototype.beginUpdate=function(t){t._updating||(t._updating=!0,this.nodes.forEach(function(t){t._packY=t.y}))},d.prototype.endUpdate=function(){var t=this.nodes.find(function(t){return t._updating});t&&(t._updating=!1,this.nodes.forEach(function(t){delete t._packY}))};function i(t,e){var i,c=this;e=e||{},this.container=f(t),a(e,"width","column","v0.5.3"),a(e,"height","maxRow","v0.5.3"),function(t,e,i,s){void 0!==t[e]&&console.warn("gridstack.js: Option `"+e+"` is deprecated in "+i+s)}(e,"oneColumnModeClass","v0.6.3",". Use class `.grid-stack-1` instead"),h(this.container,"data-gs-width","data-gs-column","v0.5.3"),h(this.container,"data-gs-height","data-gs-max-row","v0.5.3"),e.itemClass=e.itemClass||"grid-stack-item";var s=0
'+this.opts.placeholderText+"
").hide(),this._updateContainerHeight(),this._updateHeightsOnResize=m.throttle(function(){c.cellHeight(c.cellWidth(),!1)},100),this.onResizeHandler=function(){if(i&&c._updateHeightsOnResize(),!c.opts.staticGrid)if(!c.opts.disableOneColumnMode&&(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)<=c.opts.minWidth){if(c.oneColumnMode)return;c.oneColumnMode=!0,c.setColumn(1)}else{if(!c.oneColumnMode)return;c.oneColumnMode=!1,c.setColumn(c._prevColumn)}},f(window).resize(this.onResizeHandler),this.onResizeHandler(),!c.opts.staticGrid&&"string"==typeof c.opts.removable){var r=f(c.opts.removable);this.dd.isDroppable(r)||this.dd.droppable(r,c.opts.removableOptions),this.dd.on(r,"dropover",function(t,e){var i=f(e.draggable),s=i.data("_gridstack_node");s&&s._grid===c&&(i.data("inTrashZone",!0),c._setupRemovingTimeout(i))}).on(r,"dropout",function(t,e){var i=f(e.draggable),s=i.data("_gridstack_node");s&&s._grid===c&&(i.data("inTrashZone",!1),c._clearRemovingTimeout(i))})}if(!c.opts.staticGrid&&c.opts.acceptWidgets){function u(t,e){var i=g,s=i.data("_gridstack_node"),o=c.getCellFromPixel({left:t.pageX,top:t.pageY},!0),n=Math.max(0,o.x),r=Math.max(0,o.y);s._added||(s._added=!0,s.el=i,s.autoPosition=!0,s.x=n,s.y=r,c.grid.cleanNodes(),c.grid.beginUpdate(s),c.grid.addNode(s),c.container.append(c.placeholder),c.placeholder.attr("data-gs-x",s.x).attr("data-gs-y",s.y).attr("data-gs-width",s.width).attr("data-gs-height",s.height).show(),s.el=c.placeholder,s._beforeDragX=s.x,s._beforeDragY=s.y,c._updateContainerHeight()),c.grid.canMoveNode(s,n,r)&&(c.grid.moveNode(s,n,r),c._updateContainerHeight())}var g=null;this.dd.droppable(c.container,{accept:function(t){var e=(t=f(t)).data("_gridstack_node");return(!e||e._grid!==c)&&t.is(!0===c.opts.acceptWidgets?".grid-stack-item":c.opts.acceptWidgets)}}).on(c.container,"dropover",function(t,e){var i,s,o=f(e.draggable),n=o.data("_gridstack_node");if(!n||!n.width||!n.height){var r=parseInt(o.attr("data-gs-width"));0this._styles._max)){for(var o=this._styles._max;o=u.grid.column||n<0||!u.grid.float&&n>u.grid.getGridHeight()){if(d._temporaryRemoved)return;!0===u.opts.removable&&u._setupRemovingTimeout(l),o=d._beforeDragX,n=d._beforeDragY,u.placeholder.detach(),u.placeholder.hide(),u.grid.removeNode(d),u._updateContainerHeight(),d._temporaryRemoved=!0}else u._clearRemovingTimeout(l),d._temporaryRemoved&&(u.grid.addNode(d),u.placeholder.attr("data-gs-x",o).attr("data-gs-y",n).attr("data-gs-width",i).attr("data-gs-height",s).show(),u.container.append(u.placeholder),d.el=u.placeholder,d._temporaryRemoved=!1)}else if("resize"===t.type&&o<0)return;var a=void 0!==i?i:d.lastTriedWidth,h=void 0!==s?s:d.lastTriedHeight;!u.grid.canMoveNode(d,o,n,i,s)||d.lastTriedX===o&&d.lastTriedY===n&&d.lastTriedWidth===a&&d.lastTriedHeight===h||(d.lastTriedX=o,d.lastTriedY=n,d.lastTriedWidth=i,d.lastTriedHeight=s,u.grid.moveNode(d,o,n,i,s),u._updateContainerHeight(),"resize"===t.type&&f(t.target).trigger("gsresize",d))}function e(t,e){u.container.append(u.placeholder);var i=f(this);u.grid.cleanNodes(),u.grid.beginUpdate(d),p=u.cellWidth();var s=u.cellHeight();c=u.container.height()/parseInt(u.container.attr("data-gs-current-height")),u.placeholder.attr("data-gs-x",i.attr("data-gs-x")).attr("data-gs-y",i.attr("data-gs-y")).attr("data-gs-width",i.attr("data-gs-width")).attr("data-gs-height",i.attr("data-gs-height")).show(),d.el=u.placeholder,d._beforeDragX=d.x,d._beforeDragY=d.y,d._prevYPix=e.position.top;var o=d.minHeight||1,n=u.opts.verticalMargin;u.dd.resizable(l,"option","minWidth",p*(d.minWidth||1)),u.dd.resizable(l,"option","minHeight",s*o+(o-1)*n),"resizestart"===t.type&&i.find(".grid-stack-item").trigger("resizestart")}function i(t,e){var i=f(this);if(i.data("_gridstack_node")){if(u.placeholder.detach(),d.el=i,u.placeholder.hide(),d._isAboutToRemove)l.data("_gridstack_node")._grid._triggerRemoveEvent(),l.removeData("_gridstack_node"),l.remove();else u._clearRemovingTimeout(l),d._temporaryRemoved?(m.removePositioningStyles(i),i.attr("data-gs-x",d._beforeDragX).attr("data-gs-y",d._beforeDragY).attr("data-gs-width",d.width).attr("data-gs-height",d.height),d.x=d._beforeDragX,d.y=d._beforeDragY,d._temporaryRemoved=!1,u.grid.addNode(d)):(m.removePositioningStyles(i),i.attr("data-gs-x",d.x).attr("data-gs-y",d.y).attr("data-gs-width",d.width).attr("data-gs-height",d.height));u._updateContainerHeight(),u._triggerChangeEvent(),u.grid.endUpdate();var s=i.find(".grid-stack");s.length&&"resizestop"===t.type&&(s.each(function(t,e){f(e).data("gridstack").onResizeHandler()}),i.find(".grid-stack-item").trigger("resizestop"),i.find(".grid-stack-item").trigger("gsresizestop")),"resizestop"===t.type&&u.container.trigger("gsresizestop",i)}}var p,c,u=this;this.dd.draggable(l,{start:e,stop:i,drag:t}).resizable(l,{start:e,stop:i,resize:t}),(d.noMove||this.opts.disableDrag||this.opts.staticGrid)&&this.dd.draggable(l,"disable"),(d.noResize||this.opts.disableResize||this.opts.staticGrid)&&this.dd.resizable(l,"disable"),this._writeAttr(l,d)},i.prototype._prepareElement=function(t,e){e=void 0!==e&&e;(t=f(t)).addClass(this.opts.itemClass);var i=this._readAttr(t,{el:t,_grid:this});i=this.grid.addNode(i,e),t.data("_gridstack_node",i),this._prepareElementsByNode(t,i)},i.prototype._writeAttr=function(t,e){t=f(t),void 0!==(e=e||{}).x&&t.attr("data-gs-x",e.x),void 0!==e.y&&t.attr("data-gs-y",e.y),void 0!==e.width&&t.attr("data-gs-width",e.width),void 0!==e.height&&t.attr("data-gs-height",e.height),void 0!==e.autoPosition&&t.attr("data-gs-auto-position",!!e.autoPosition||null),void 0!==e.minWidth&&t.attr("data-gs-min-width",e.minWidth),void 0!==e.maxWidth&&t.attr("data-gs-max-width",e.maxWidth),void 0!==e.minHeight&&t.attr("data-gs-min-height",e.minHeight),void 0!==e.maxHeight&&t.attr("data-gs-max-height",e.maxHeight),void 0!==e.noResize&&t.attr("data-gs-no-resize",!!e.noResize||null),void 0!==e.noMove&&t.attr("data-gs-no-move",!!e.noMove||null),void 0!==e.locked&&t.attr("data-gs-locked",!!e.locked||null),void 0!==e.resizeHandles&&t.attr("data-gs-resize-handles",e.resizeHandles),void 0!==e.id&&t.attr("data-gs-id",e.id)},i.prototype._readAttr=function(t,e){return t=f(t),(e=e||{}).x=t.attr("data-gs-x"),e.y=t.attr("data-gs-y"),e.width=t.attr("data-gs-width"),e.height=t.attr("data-gs-height"),e.autoPosition=m.toBool(t.attr("data-gs-auto-position")),e.maxWidth=t.attr("data-gs-max-width"),e.minWidth=t.attr("data-gs-min-width"),e.maxHeight=t.attr("data-gs-max-height"),e.minHeight=t.attr("data-gs-min-height"),e.noResize=m.toBool(t.attr("data-gs-no-resize")),e.noMove=m.toBool(t.attr("data-gs-no-move")),e.locked=m.toBool(t.attr("data-gs-locked")),e.resizeHandles=t.attr("data-gs-resize-handles"),e.id=t.attr("data-gs-id"),e},i.prototype.setAnimation=function(t){t?this.container.addClass("grid-stack-animate"):this.container.removeClass("grid-stack-animate")},i.prototype.addWidget=function(t,e,i,s,o,n,r,a,h,l,d){return void 0!==e&&"object"!=typeof e?this.addWidget(t,{x:e,y:i,width:s,height:o,autoPosition:n,minWidth:r,maxWidth:a,minHeight:h,maxHeight:l,id:d}):(e=e||{},t=f(t),this._writeAttr(t,e),this.container.append(t),this.makeWidget(t))},i.prototype.makeWidget=function(t){return t=f(t),this._prepareElement(t,!0),this._updateContainerHeight(),this._triggerAddEvent(),this._triggerChangeEvent(!0),t},i.prototype.willItFit=function(t,e,i,s,o){var n={x:t,y:e,width:i,height:s,autoPosition:o};return this.grid.canBePlacedWithRespectToHeight(n)},i.prototype.removeWidget=function(t,e){e=void 0===e||e;var i=(t=f(t)).data("_gridstack_node");i=i||this.grid.getNodeDataByDOMEl(t),t.removeData("_gridstack_node"),this.grid.removeNode(i,e),this._triggerRemoveEvent(),this._triggerChangeEvent(!0)},i.prototype.removeAll=function(t){!1!==t&&this.grid.nodes.forEach(function(t){t.el.removeData("_gridstack_node")}),this.grid.removeAll(t),this._triggerRemoveEvent()},i.prototype.destroy=function(t){f(window).off("resize",this.onResizeHandler),this.disable(),void 0===t||t?this.container.remove():(this.removeAll(!1),this.container.removeData("gridstack")),m.removeStylesheet(this._stylesId),this.grid&&(this.grid=null)},i.prototype.resizable=function(t,s){var o=this;return(t=f(t)).each(function(t,e){var i=(e=f(e)).data("_gridstack_node");i&&(i.noResize=!s,i.noResize?o.dd.resizable(e,"disable"):o.dd.resizable(e,"enable"))}),this},i.prototype.movable=function(t,s){var o=this;return(t=f(t)).each(function(t,e){var i=(e=f(e)).data("_gridstack_node");i&&(i.noMove=!s,i.noMove?(o.dd.draggable(e,"disable"),e.removeClass("ui-draggable-handle")):(o.dd.draggable(e,"enable"),e.addClass("ui-draggable-handle")))}),this},i.prototype.enableMove=function(t,e){this.movable(this.container.children("."+this.opts.itemClass),t),e&&(this.opts.disableDrag=!t)},i.prototype.enableResize=function(t,e){this.resizable(this.container.children("."+this.opts.itemClass),t),e&&(this.opts.disableResize=!t)},i.prototype.disable=function(){this.movable(this.container.children("."+this.opts.itemClass),!1),this.resizable(this.container.children("."+this.opts.itemClass),!1),this.container.trigger("disable")},i.prototype.enable=function(){this.movable(this.container.children("."+this.opts.itemClass),!0),this.resizable(this.container.children("."+this.opts.itemClass),!0),this.container.trigger("enable")},i.prototype.locked=function(t,s){return(t=f(t)).each(function(t,e){var i=(e=f(e)).data("_gridstack_node");i&&(i.locked=s||!1,e.attr("data-gs-locked",i.locked?"yes":null))}),this},i.prototype.maxHeight=function(t,s){return(t=f(t)).each(function(t,e){var i=(e=f(e)).data("_gridstack_node");i&&(isNaN(s)||(i.maxHeight=s||!1,e.attr("data-gs-max-height",s)))}),this},i.prototype.minHeight=function(t,s){return(t=f(t)).each(function(t,e){var i=(e=f(e)).data("_gridstack_node");i&&(isNaN(s)||(i.minHeight=s||!1,e.attr("data-gs-min-height",s)))}),this},i.prototype.maxWidth=function(t,s){return(t=f(t)).each(function(t,e){var i=(e=f(e)).data("_gridstack_node");i&&(isNaN(s)||(i.maxWidth=s||!1,e.attr("data-gs-max-width",s)))}),this},i.prototype.minWidth=function(t,s){return(t=f(t)).each(function(t,e){var i=(e=f(e)).data("_gridstack_node");i&&(isNaN(s)||(i.minWidth=s||!1,e.attr("data-gs-min-width",s)))}),this},i.prototype._updateElement=function(t,e){var i=(t=f(t).first()).data("_gridstack_node");if(i){var s=this;s.grid.cleanNodes(),s.grid.beginUpdate(i),e.call(this,t,i),s._updateContainerHeight(),s._triggerChangeEvent(),s.grid.endUpdate()}},i.prototype.resize=function(t,i,s){this._updateElement(t,function(t,e){i=null!=i?i:e.width,s=null!=s?s:e.height,this.grid.moveNode(e,e.x,e.y,i,s)})},i.prototype.move=function(t,i,s){this._updateElement(t,function(t,e){i=null!=i?i:e.x,s=null!=s?s:e.y,this.grid.moveNode(e,i,s,e.width,e.height)})},i.prototype.update=function(t,i,s,o,n){this._updateElement(t,function(t,e){i=null!=i?i:e.x,s=null!=s?s:e.y,o=null!=o?o:e.width,n=null!=n?n:e.height,this.grid.moveNode(e,i,s,o,n)})},i.prototype.compact=function(){if(0!==this.grid.nodes.length){this.batchUpdate(),this.grid._sortNodes();var t=this.grid.nodes;this.grid.nodes=[],t.forEach(function(t){t.noMove||t.locked||(t.autoPosition=!0),this.grid.addNode(t,!1),t._dirty=!0},this),this.commit()}},i.prototype.verticalMargin=function(t,e){if(void 0===t)return this.opts.verticalMargin;var i=m.parseHeight(t);this.opts.verticalMarginUnit===i.unit&&this.opts.maxRow===i.height||(this.opts.verticalMarginUnit=i.unit,this.opts.verticalMargin=i.height,e||this._updateStyles())},i.prototype.cellHeight=function(t,e){if(void 0===t){if(this.opts.cellHeight&&"auto"!==this.opts.cellHeight)return this.opts.cellHeight;var i=this.container.children("."+this.opts.itemClass).first(),s=i.attr("data-gs-height"),o=this.opts.verticalMargin;return Math.round((i.outerHeight()-(s-1)*o)/s)}var n=m.parseHeight(t);this.opts.cellHeightUnit===n.unit&&this.opts.cellHeight===n.height||(this.opts.cellHeightUnit=n.unit,this.opts.cellHeight=n.height,e||this._updateStyles())},i.prototype.cellWidth=function(){return Math.round(this.container.outerWidth()/this.opts.column)},i.prototype.getCellFromPixel=function(t,e){var i=void 0!==e&&e?this.container.offset():this.container.position(),s=t.left-i.left,o=t.top-i.top,n=Math.floor(this.container.width()/this.opts.column),r=Math.floor(this.container.height()/parseInt(this.container.attr("data-gs-current-height")));return{x:Math.floor(s/n),y:Math.floor(o/r)}},i.prototype.batchUpdate=function(){this.grid.batchUpdate()},i.prototype.commit=function(){this.grid.commit(),this._triggerRemoveEvent(),this._triggerAddEvent(),this._triggerChangeEvent()},i.prototype.isAreaEmpty=function(t,e,i,s){return this.grid.isAreaEmpty(t,e,i,s)},i.prototype.setStatic=function(t){this.opts.staticGrid=!0===t,this.enableMove(!t),this.enableResize(!t),this._setStaticClass()},i.prototype._setStaticClass=function(){var t="grid-stack-static";!0===this.opts.staticGrid?this.container.addClass(t):this.container.removeClass(t)},d.prototype._layoutsNodesChange=function(t){this._layouts&&!this._ignoreLayoutsNodeChange&&this._layouts.forEach(function(s,o){s&&o!==this.column&&(o",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=y(e||this.defaultElement||this)[0],this.element=y(e),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=y(),this.hoverable=y(),this.focusable=y(),this.classesElementLookup={},e!==this&&(y.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=y(e.style?e.ownerDocument:e.document||e),this.window=y(this.document[0].defaultView||this.document[0].parentWindow)),this.options=y.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:y.noop,_create:y.noop,_init:y.noop,destroy:function(){var i=this;this._destroy(),y.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:y.noop,widget:function(){return this.element},option:function(t,e){var i,s,o,n=t;if(0===arguments.length)return y.widget.extend({},this.options);if("string"==typeof t)if(n={},t=(i=t.split(".")).shift(),i.length){for(s=n[t]=y.widget.extend({},this.options[t]),o=0;o=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),y.ui.plugin={add:function(t,e,i){var s,o=y.ui[t].prototype;for(s in i)o.plugins[s]=o.plugins[s]||[],o.plugins[s].push([e,i[s]])},call:function(t,e,i,s){var o,n=t.plugins[e];if(n&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(o=0;o").css("position","absolute").appendTo(t.parent()).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(t){var e=y.ui.safeActiveElement(this.document[0]);y(t.target).closest(e).length||y.ui.safeBlur(e)},_mouseStart:function(t){var e=this.options;return this.helper=this._createHelper(t),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),y.ui.ddmanager&&(y.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=0i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),r.grid&&(o=r.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/r.grid[1])*r.grid[1]:this.originalPageY,l=i?o-this.offset.click.top>=i[1]||o-this.offset.click.top>i[3]?o:o-this.offset.click.top>=i[1]?o-r.grid[1]:o+r.grid[1]:o,n=r.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/r.grid[0])*r.grid[0]:this.originalPageX,h=i?n-this.offset.click.left>=i[0]||n-this.offset.click.left>i[2]?n:n-this.offset.click.left>=i[0]?n-r.grid[0]:n+r.grid[0]:n),"y"===r.axis&&(h=this.originalPageX),"x"===r.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:a?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:a?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(t,e,i){return i=i||this._uiHash(),y.ui.plugin.call(this,t,[e,i,this],!0),/^(drag|start|stop)/.test(t)&&(this.positionAbs=this._convertPositionTo("absolute"),i.offset=this.positionAbs),y.Widget.prototype._trigger.call(this,t,e,i)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),y.ui.plugin.add("draggable","connectToSortable",{start:function(e,t,i){var s=y.extend({},t,{item:i.element});i.sortables=[],y(i.options.connectToSortable).each(function(){var t=y(this).sortable("instance");t&&!t.options.disabled&&(i.sortables.push(t),t.refreshPositions(),t._trigger("activate",e,s))})},stop:function(e,t,i){var s=y.extend({},t,{item:i.element});i.cancelHelperRemoval=!1,y.each(i.sortables,function(){var t=this;t.isOver?(t.isOver=0,i.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,s))})},drag:function(i,s,o){y.each(o.sortables,function(){var t=!1,e=this;e.positionAbs=o.positionAbs,e.helperProportions=o.helperProportions,e.offset.click=o.offset.click,e._intersectsWith(e.containerCache)&&(t=!0,y.each(o.sortables,function(){return this.positionAbs=o.positionAbs,this.helperProportions=o.helperProportions,this.offset.click=o.offset.click,this!==e&&this._intersectsWith(this.containerCache)&&y.contains(e.element[0],this.element[0])&&(t=!1),t})),t?(e.isOver||(e.isOver=1,o._parent=s.helper.parent(),e.currentItem=s.helper.appendTo(e.element).data("ui-sortable-item",!0),e.options._helper=e.options.helper,e.options.helper=function(){return s.helper[0]},i.target=e.currentItem[0],e._mouseCapture(i,!0),e._mouseStart(i,!0,!0),e.offset.click.top=o.offset.click.top,e.offset.click.left=o.offset.click.left,e.offset.parent.left-=o.offset.parent.left-e.offset.parent.left,e.offset.parent.top-=o.offset.parent.top-e.offset.parent.top,o._trigger("toSortable",i),o.dropped=e.element,y.each(o.sortables,function(){this.refreshPositions()}),o.currentItem=o.element,e.fromOutside=o),e.currentItem&&(e._mouseDrag(i),s.position=e.position)):e.isOver&&(e.isOver=0,e.cancelHelperRemoval=!0,e.options._revert=e.options.revert,e.options.revert=!1,e._trigger("out",i,e._uiHash(e)),e._mouseStop(i,!0),e.options.revert=e.options._revert,e.options.helper=e.options._helper,e.placeholder&&e.placeholder.remove(),s.helper.appendTo(o._parent),o._refreshOffsets(i),s.position=o._generatePosition(i,!0),o._trigger("fromSortable",i),o.dropped=!1,y.each(o.sortables,function(){this.refreshPositions()}))})}}),y.ui.plugin.add("draggable","cursor",{start:function(t,e,i){var s=y("body"),o=i.options;s.css("cursor")&&(o._cursor=s.css("cursor")),s.css("cursor",o.cursor)},stop:function(t,e,i){var s=i.options;s._cursor&&y("body").css("cursor",s._cursor)}}),y.ui.plugin.add("draggable","opacity",{start:function(t,e,i){var s=y(e.helper),o=i.options;s.css("opacity")&&(o._opacity=s.css("opacity")),s.css("opacity",o.opacity)},stop:function(t,e,i){var s=i.options;s._opacity&&y(e.helper).css("opacity",s._opacity)}}),y.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(t,e,i){var s=i.options,o=!1,n=i.scrollParentNotHidden[0],r=i.document[0];n!==r&&"HTML"!==n.tagName?(s.axis&&"x"===s.axis||(i.overflowOffset.top+n.offsetHeight-t.pageY").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,t={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(t),this.originalElement.css("margin",0),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css(t),this._proportionallyResize()),this._setupHandles(),e.autoHide&&y(this.element).on("mouseenter",function(){e.disabled||(i._removeClass("ui-resizable-autohide"),i._handles.show())}).on("mouseleave",function(){e.disabled||i.resizing||(i._addClass("ui-resizable-autohide"),i._handles.hide())}),this._mouseInit()},_destroy:function(){this._mouseDestroy();function t(t){y(t).removeData("resizable").removeData("ui-resizable").off(".resizable").find(".ui-resizable-handle").remove()}var e;return this.elementIsWrapper&&(t(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),t(this.originalElement),this},_setOption:function(t,e){switch(this._super(t,e),t){case"handles":this._removeHandles(),this._setupHandles()}},_setupHandles:function(){var t,e,i,s,o,n=this.options,r=this;if(this.handles=n.handles||(y(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=y(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),i=this.handles.split(","),this.handles={},e=0;e"),this._addClass(o,"ui-resizable-handle "+s),o.css({zIndex:n.zIndex}),this.handles[t]=".ui-resizable-"+t,this.element.append(o);this._renderAxis=function(t){var e,i,s,o;for(e in t=t||this.element,this.handles)this.handles[e].constructor===String?this.handles[e]=this.element.children(this.handles[e]).first().show():(this.handles[e].jquery||this.handles[e].nodeType)&&(this.handles[e]=y(this.handles[e]),this._on(this.handles[e],{mousedown:r._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(i=y(this.handles[e],this.element),o=/sw|ne|nw|se|n|s/.test(e)?i.outerHeight():i.outerWidth(),s=["padding",/ne|nw|n/.test(e)?"Top":/se|sw|s/.test(e)?"Bottom":/^e$/.test(e)?"Right":"Left"].join(""),t.css(s,o),this._proportionallyResize()),this._handles=this._handles.add(this.handles[e])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){r.resizing||(this.className&&(o=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),r.axis=o&&o[1]?o[1]:"se")}),n.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._handles.remove()},_mouseCapture:function(t){var e,i,s=!1;for(e in this.handles)(i=y(this.handles[e])[0])!==t.target&&!y.contains(i,t.target)||(s=!0);return!this.options.disabled&&s},_mouseStart:function(t){var e,i,s,o=this.options,n=this.element;return this.resizing=!0,this._renderProxy(),e=this._num(this.helper.css("left")),i=this._num(this.helper.css("top")),o.containment&&(e+=y(o.containment).scrollLeft()||0,i+=y(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:e,top:i},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:n.width(),height:n.height()},this.originalSize=this._helper?{width:n.outerWidth(),height:n.outerHeight()}:{width:n.width(),height:n.height()},this.sizeDiff={width:n.outerWidth()-n.width(),height:n.outerHeight()-n.height()},this.originalPosition={left:e,top:i},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio="number"==typeof o.aspectRatio?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,s=y(".ui-resizable-"+this.axis).css("cursor"),y("body").css("cursor","auto"===s?this.axis+"-resize":s),this._addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var e,i,s=this.originalMousePosition,o=this.axis,n=t.pageX-s.left||0,r=t.pageY-s.top||0,a=this._change[o];return this._updatePrevProperties(),a&&(e=a.apply(this,[t,n,r]),this._updateVirtualBoundaries(t.shiftKey),(this._aspectRatio||t.shiftKey)&&(e=this._updateRatio(e,t)),e=this._respectSize(e,t),this._updateCache(e),this._propagate("resize",t),i=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),y.isEmptyObject(i)||(this._updatePrevProperties(),this._trigger("resize",t,this.ui()),this._applyChanges())),!1},_mouseStop:function(t){this.resizing=!1;var e,i,s,o,n,r,a,h=this.options,l=this;return this._helper&&(s=(i=(e=this._proportionallyResizeElements).length&&/textarea/i.test(e[0].nodeName))&&this._hasScroll(e[0],"left")?0:l.sizeDiff.height,o=i?0:l.sizeDiff.width,n={width:l.helper.width()-o,height:l.helper.height()-s},r=parseFloat(l.element.css("left"))+(l.position.left-l.originalPosition.left)||null,a=parseFloat(l.element.css("top"))+(l.position.top-l.originalPosition.top)||null,h.animate||this.element.css(y.extend(n,{top:a,left:r})),l.helper.height(l.size.height),l.helper.width(l.size.width),this._helper&&!h.animate&&this._proportionallyResize()),y("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px"),this.helper.css(t),t},_updateVirtualBoundaries:function(t){var e,i,s,o,n,r=this.options;n={minWidth:this._isNumber(r.minWidth)?r.minWidth:0,maxWidth:this._isNumber(r.maxWidth)?r.maxWidth:1/0,minHeight:this._isNumber(r.minHeight)?r.minHeight:0,maxHeight:this._isNumber(r.maxHeight)?r.maxHeight:1/0},(this._aspectRatio||t)&&(e=n.minHeight*this.aspectRatio,s=n.minWidth/this.aspectRatio,i=n.maxHeight*this.aspectRatio,o=n.maxWidth/this.aspectRatio,e>n.minWidth&&(n.minWidth=e),s>n.minHeight&&(n.minHeight=s),it.width,r=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,a=this.originalPosition.left+this.originalSize.width,h=this.originalPosition.top+this.originalSize.height,l=/sw|nw|w/.test(i),d=/nw|ne|n/.test(i);return n&&(t.width=e.minWidth),r&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),o&&(t.height=e.maxHeight),n&&l&&(t.left=a-e.minWidth),s&&l&&(t.left=a-e.maxWidth),r&&d&&(t.top=h-e.minHeight),o&&d&&(t.top=h-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],o=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];e<4;e++)i[e]=parseFloat(s[e])||0,i[e]+=parseFloat(o[e])||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;e"),this._addClass(this.helper,this._helper),this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++e.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize;return{left:this.originalPosition.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize;return{top:this.originalPosition.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(t,e,i){return y.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,e,i]))},sw:function(t,e,i){return y.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,e,i]))},ne:function(t,e,i){return y.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,e,i]))},nw:function(t,e,i){return y.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,e,i]))}},_propagate:function(t,e){y.ui.plugin.call(this,t,[e,this.ui()]),"resize"!==t&&this._trigger(t,e,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),y.ui.plugin.add("resizable","animate",{stop:function(e){var i=y(this).resizable("instance"),t=i.options,s=i._proportionallyResizeElements,o=s.length&&/textarea/i.test(s[0].nodeName),n=o&&i._hasScroll(s[0],"left")?0:i.sizeDiff.height,r=o?0:i.sizeDiff.width,a={width:i.size.width-r,height:i.size.height-n},h=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,l=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(y.extend(a,l&&h?{top:l,left:h}:{}),{duration:t.animateDuration,easing:t.animateEasing,step:function(){var t={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};s&&s.length&&y(s[0]).css({width:t.width,height:t.height}),i._updateCache(t),i._propagate("resize",e)}})}}),y.ui.plugin.add("resizable","containment",{start:function(){var i,s,t,e,o,n,r,a=y(this).resizable("instance"),h=a.options,l=a.element,d=h.containment,p=d instanceof y?d.get(0):/parent/.test(d)?l.parent().get(0):d;p&&(a.containerElement=y(p),/document/.test(d)||d===document?(a.containerOffset={left:0,top:0},a.containerPosition={left:0,top:0},a.parentData={element:y(document),left:0,top:0,width:y(document).width(),height:y(document).height()||document.body.parentNode.scrollHeight}):(i=y(p),s=[],y(["Top","Right","Left","Bottom"]).each(function(t,e){s[t]=a._num(i.css("padding"+e))}),a.containerOffset=i.offset(),a.containerPosition=i.position(),a.containerSize={height:i.innerHeight()-s[3],width:i.innerWidth()-s[1]},t=a.containerOffset,e=a.containerSize.height,o=a.containerSize.width,n=a._hasScroll(p,"left")?p.scrollWidth:o,r=a._hasScroll(p)?p.scrollHeight:e,a.parentData={element:p,left:t.left,top:t.top,width:n,height:r}))},resize:function(t){var e,i,s,o,n=y(this).resizable("instance"),r=n.options,a=n.containerOffset,h=n.position,l=n._aspectRatio||t.shiftKey,d={top:0,left:0},p=n.containerElement,c=!0;p[0]!==document&&/static/.test(p.css("position"))&&(d=a),h.left<(n._helper?a.left:0)&&(n.size.width=n.size.width+(n._helper?n.position.left-a.left:n.position.left-d.left),l&&(n.size.height=n.size.width/n.aspectRatio,c=!1),n.position.left=r.helper?a.left:0),h.top<(n._helper?a.top:0)&&(n.size.height=n.size.height+(n._helper?n.position.top-a.top:n.position.top),l&&(n.size.width=n.size.height*n.aspectRatio,c=!1),n.position.top=n._helper?a.top:0),s=n.containerElement.get(0)===n.element.parent().get(0),o=/relative|absolute/.test(n.containerElement.css("position")),s&&o?(n.offset.left=n.parentData.left+n.position.left,n.offset.top=n.parentData.top+n.position.top):(n.offset.left=n.element.offset().left,n.offset.top=n.element.offset().top),e=Math.abs(n.sizeDiff.width+(n._helper?n.offset.left-d.left:n.offset.left-a.left)),i=Math.abs(n.sizeDiff.height+(n._helper?n.offset.top-d.top:n.offset.top-a.top)),e+n.size.width>=n.parentData.width&&(n.size.width=n.parentData.width-e,l&&(n.size.height=n.size.width/n.aspectRatio,c=!1)),i+n.size.height>=n.parentData.height&&(n.size.height=n.parentData.height-i,l&&(n.size.width=n.size.height*n.aspectRatio,c=!1)),c||(n.position.left=n.prevPosition.left,n.position.top=n.prevPosition.top,n.size.width=n.prevSize.width,n.size.height=n.prevSize.height)},stop:function(){var t=y(this).resizable("instance"),e=t.options,i=t.containerOffset,s=t.containerPosition,o=t.containerElement,n=y(t.helper),r=n.offset(),a=n.outerWidth()-t.sizeDiff.width,h=n.outerHeight()-t.sizeDiff.height;t._helper&&!e.animate&&/relative/.test(o.css("position"))&&y(this).css({left:r.left-s.left-i.left,width:a,height:h}),t._helper&&!e.animate&&/static/.test(o.css("position"))&&y(this).css({left:r.left-s.left-i.left,width:a,height:h})}}),y.ui.plugin.add("resizable","alsoResize",{start:function(){var t=y(this).resizable("instance").options;y(t.alsoResize).each(function(){var t=y(this);t.data("ui-resizable-alsoresize",{width:parseFloat(t.width()),height:parseFloat(t.height()),left:parseFloat(t.css("left")),top:parseFloat(t.css("top"))})})},resize:function(t,i){var e=y(this).resizable("instance"),s=e.options,o=e.originalSize,n=e.originalPosition,r={height:e.size.height-o.height||0,width:e.size.width-o.width||0,top:e.position.top-n.top||0,left:e.position.left-n.left||0};y(s.alsoResize).each(function(){var t=y(this),s=y(this).data("ui-resizable-alsoresize"),o={},e=t.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];y.each(e,function(t,e){var i=(s[e]||0)+(r[e]||0);i&&0<=i&&(o[e]=i||null)}),t.css(o)})},stop:function(){y(this).removeData("ui-resizable-alsoresize")}}),y.ui.plugin.add("resizable","ghost",{start:function(){var t=y(this).resizable("instance"),e=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:e.height,width:e.width,margin:0,left:0,top:0}),t._addClass(t.ghost,"ui-resizable-ghost"),!1!==y.uiBackCompat&&"string"==typeof t.options.ghost&&t.ghost.addClass(this.options.ghost),t.ghost.appendTo(t.helper)},resize:function(){var t=y(this).resizable("instance");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=y(this).resizable("instance");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),y.ui.plugin.add("resizable","grid",{resize:function(){var t,e=y(this).resizable("instance"),i=e.options,s=e.size,o=e.originalSize,n=e.originalPosition,r=e.axis,a="number"==typeof i.grid?[i.grid,i.grid]:i.grid,h=a[0]||1,l=a[1]||1,d=Math.round((s.width-o.width)/h)*h,p=Math.round((s.height-o.height)/l)*l,c=o.width+d,u=o.height+p,g=i.maxWidth&&i.maxWidthc,v=i.minHeight&&i.minHeight>u;i.grid=a,m&&(c+=h),v&&(u+=l),g&&(c-=h),f&&(u-=l),/^(se|s|e)$/.test(r)?(e.size.width=c,e.size.height=u):/^(ne)$/.test(r)?(e.size.width=c,e.size.height=u,e.position.top=n.top-p):/^(sw)$/.test(r)?(e.size.width=c,e.size.height=u,e.position.left=n.left-d):((u-l<=0||c-h<=0)&&(t=e._getPaddingPlusBorderDimensions(this)),0 .ui-resizable-handle { + filter: none; } + +.grid-stack { + position: relative; } + .grid-stack.grid-stack-rtl { + direction: ltr; } + .grid-stack.grid-stack-rtl > .grid-stack-item { + direction: rtl; } + .grid-stack .grid-stack-placeholder > .placeholder-content { + border: 1px dashed lightgray; + margin: 0; + position: absolute; + top: 0; + left: 10px; + right: 10px; + bottom: 0; + width: auto; + z-index: 0 !important; + text-align: center; } + .grid-stack > .grid-stack-item { + min-width: 8.3333333333%; + position: absolute; + padding: 0; } + .grid-stack > .grid-stack-item > .grid-stack-item-content { + margin: 0; + position: absolute; + top: 0; + left: 10px; + right: 10px; + bottom: 0; + width: auto; + overflow-x: hidden; + overflow-y: auto; } + .grid-stack > .grid-stack-item > .ui-resizable-handle { + position: absolute; + font-size: 0.1px; + display: block; + -ms-touch-action: none; + touch-action: none; } + .grid-stack > .grid-stack-item.ui-resizable-disabled > .ui-resizable-handle, + .grid-stack > .grid-stack-item.ui-resizable-autohide > .ui-resizable-handle { + display: none; } + .grid-stack > .grid-stack-item.ui-draggable-dragging, .grid-stack > .grid-stack-item.ui-resizable-resizing { + z-index: 100; } + .grid-stack > .grid-stack-item.ui-draggable-dragging > .grid-stack-item-content, + .grid-stack > .grid-stack-item.ui-draggable-dragging > .grid-stack-item-content, .grid-stack > .grid-stack-item.ui-resizable-resizing > .grid-stack-item-content, + .grid-stack > .grid-stack-item.ui-resizable-resizing > .grid-stack-item-content { + box-shadow: 1px 4px 6px rgba(0, 0, 0, 0.2); + opacity: 0.8; } + .grid-stack > .grid-stack-item > .ui-resizable-se, + .grid-stack > .grid-stack-item > .ui-resizable-sw { + background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTYuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV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NDIxLTEyLjg1NCAgIEMzMzguMTQyLDQwMy44MDIsMzMzLjg1Nyw0MDEuOTk0LDMyOC45MDYsNDAxLjk5NHoiIGZpbGw9IiM2NjY2NjYiLz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8L3N2Zz4K); + background-repeat: no-repeat; + background-position: center; + -webkit-transform: rotate(45deg); + -moz-transform: rotate(45deg); + -ms-transform: rotate(45deg); + -o-transform: rotate(45deg); + transform: rotate(45deg); } + .grid-stack > .grid-stack-item > .ui-resizable-se { + -webkit-transform: rotate(-45deg); + -moz-transform: rotate(-45deg); + -ms-transform: rotate(-45deg); + -o-transform: rotate(-45deg); + transform: rotate(-45deg); } + .grid-stack > .grid-stack-item > .ui-resizable-nw { + cursor: nw-resize; + width: 20px; + height: 20px; + left: 10px; + top: 0; } + .grid-stack > .grid-stack-item > .ui-resizable-n { + cursor: n-resize; + height: 10px; + top: 0; + left: 25px; + right: 25px; } + .grid-stack > .grid-stack-item > .ui-resizable-ne { + cursor: ne-resize; + width: 20px; + height: 20px; + right: 10px; + top: 0; } + .grid-stack > .grid-stack-item > .ui-resizable-e { + cursor: e-resize; + width: 10px; + right: 10px; + top: 15px; + bottom: 15px; } + .grid-stack > .grid-stack-item > .ui-resizable-se { + cursor: se-resize; + width: 20px; + height: 20px; + right: 10px; + bottom: 0; } + .grid-stack > .grid-stack-item > .ui-resizable-s { + cursor: s-resize; + height: 10px; + left: 25px; + bottom: 0; + right: 25px; } + .grid-stack > .grid-stack-item > .ui-resizable-sw { + cursor: sw-resize; + width: 20px; + height: 20px; + left: 10px; + bottom: 0; } + .grid-stack > .grid-stack-item > .ui-resizable-w { + cursor: w-resize; + width: 10px; + left: 10px; + top: 15px; + bottom: 15px; } + .grid-stack > .grid-stack-item.ui-draggable-dragging > .ui-resizable-handle { + display: none !important; } + .grid-stack > .grid-stack-item[data-gs-width='1'] { + width: 8.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-x='1'] { + left: 8.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-min-width='1'] { + min-width: 8.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-max-width='1'] { + max-width: 8.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-width='2'] { + width: 16.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-x='2'] { + left: 16.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-min-width='2'] { + min-width: 16.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-max-width='2'] { + max-width: 16.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-width='3'] { + width: 25%; } + .grid-stack > .grid-stack-item[data-gs-x='3'] { + left: 25%; } + .grid-stack > .grid-stack-item[data-gs-min-width='3'] { + min-width: 25%; } + .grid-stack > .grid-stack-item[data-gs-max-width='3'] { + max-width: 25%; } + .grid-stack > .grid-stack-item[data-gs-width='4'] { + width: 33.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-x='4'] { + left: 33.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-min-width='4'] { + min-width: 33.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-max-width='4'] { + max-width: 33.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-width='5'] { + width: 41.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-x='5'] { + left: 41.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-min-width='5'] { + min-width: 41.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-max-width='5'] { + max-width: 41.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-width='6'] { + width: 50%; } + .grid-stack > .grid-stack-item[data-gs-x='6'] { + left: 50%; } + .grid-stack > .grid-stack-item[data-gs-min-width='6'] { + min-width: 50%; } + .grid-stack > .grid-stack-item[data-gs-max-width='6'] { + max-width: 50%; } + .grid-stack > .grid-stack-item[data-gs-width='7'] { + width: 58.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-x='7'] { + left: 58.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-min-width='7'] { + min-width: 58.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-max-width='7'] { + max-width: 58.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-width='8'] { + width: 66.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-x='8'] { + left: 66.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-min-width='8'] { + min-width: 66.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-max-width='8'] { + max-width: 66.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-width='9'] { + width: 75%; } + .grid-stack > .grid-stack-item[data-gs-x='9'] { + left: 75%; } + .grid-stack > .grid-stack-item[data-gs-min-width='9'] { + min-width: 75%; } + .grid-stack > .grid-stack-item[data-gs-max-width='9'] { + max-width: 75%; } + .grid-stack > .grid-stack-item[data-gs-width='10'] { + width: 83.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-x='10'] { + left: 83.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-min-width='10'] { + min-width: 83.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-max-width='10'] { + max-width: 83.3333333333%; } + .grid-stack > .grid-stack-item[data-gs-width='11'] { + width: 91.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-x='11'] { + left: 91.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-min-width='11'] { + min-width: 91.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-max-width='11'] { + max-width: 91.6666666667%; } + .grid-stack > .grid-stack-item[data-gs-width='12'] { + width: 100%; } + .grid-stack > .grid-stack-item[data-gs-x='12'] { + left: 100%; } + .grid-stack > .grid-stack-item[data-gs-min-width='12'] { + min-width: 100%; } + .grid-stack > .grid-stack-item[data-gs-max-width='12'] { + max-width: 100%; } + .grid-stack.grid-stack-1 > .grid-stack-item { + min-width: 100%; } + .grid-stack.grid-stack-1 > .grid-stack-item[data-gs-width='1'] { + width: 100%; } + .grid-stack.grid-stack-1 > .grid-stack-item[data-gs-x='1'] { + left: 100%; } + .grid-stack.grid-stack-1 > .grid-stack-item[data-gs-min-width='1'] { + min-width: 100%; } + .grid-stack.grid-stack-1 > .grid-stack-item[data-gs-max-width='1'] { + max-width: 100%; } + .grid-stack.grid-stack-animate, + .grid-stack.grid-stack-animate .grid-stack-item { + -webkit-transition: left 0.3s, top 0.3s, height 0.3s, width 0.3s; + -moz-transition: left 0.3s, top 0.3s, height 0.3s, width 0.3s; + -ms-transition: left 0.3s, top 0.3s, height 0.3s, width 0.3s; + -o-transition: left 0.3s, top 0.3s, height 0.3s, width 0.3s; + transition: left 0.3s, top 0.3s, height 0.3s, width 0.3s; } + .grid-stack.grid-stack-animate .grid-stack-item.ui-draggable-dragging, + .grid-stack.grid-stack-animate .grid-stack-item.ui-resizable-resizing, + .grid-stack.grid-stack-animate .grid-stack-item.grid-stack-placeholder { + -webkit-transition: left 0s, top 0s, height 0s, width 0s; + -moz-transition: left 0s, top 0s, height 0s, width 0s; + -ms-transition: left 0s, top 0s, height 0s, width 0s; + -o-transition: left 0s, top 0s, height 0s, width 0s; + transition: left 0s, top 0s, height 0s, width 0s; } diff --git a/software/flow/node_modules/gridstack/dist/gridstack.d.ts b/software/flow/node_modules/gridstack/dist/gridstack.d.ts new file mode 100644 index 0000000..827180e --- /dev/null +++ b/software/flow/node_modules/gridstack/dist/gridstack.d.ts @@ -0,0 +1,549 @@ +// Type definitions for Gridstack 0.6.4 +// Project: https://gridstackjs.com/ +// Definitions by: Pascal Senn +// Ricky Blankenaufulland +// Sl1MBoy +// John Archer +// Alain Dumesny +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped initially, but now part of gridstack.js +// TypeScript Version: 2.8 + +interface JQuery { + gridstack(options: GridstackOptions): JQuery; + data(key: 'gridstack'): GridStack; +} + +/* Other items in https://github.com/gridstack/gridstack.js/blob/develop/doc/README.md + * Grid attributes + * Item attributes + * Events + */ + +type GridStackElement = string | HTMLElement | JQuery; + +interface GridStack { + /** + * Creates new widget and returns it. + * + * Widget will be always placed even if result height is more than actual grid height. + * You need to use willItFit method before calling addWidget for additional check. + * See also `makeWidget()`. + * + * @example + * $('.grid-stack').gridstack(); + * var grid = $('.grid-stack').data('gridstack'); + * grid.addWidget(el, {width: 3, autoPosition: true}); + * + * @param el widget to add + * @param options widget position/size options (optional) + */ + addWidget(el: GridStackElement, options ? : GridstackWidget): JQuery; + + /** + * Creates new widget and returns it. + * Legacy: Spelled out version of the widgets options, recommend use new version instead. + * + * @example + * $('.grid-stack').gridstack(); + * var grid = $('.grid-stack').data('gridstack'); + * grid.addWidget(el, 0, 0, 3, 2, true); + * + * @param el widget to add + * @param x widget position x (optional) + * @param y widget position y (optional) + * @param width widget dimension width (optional) + * @param height widget dimension height (optional) + * @param autoPosition if true then x, y parameters will be ignored and widget will be places on the first available position (optional) + * @param minWidth minimum width allowed during resize/creation (optional) + * @param maxWidth maximum width allowed during resize/creation (optional) + * @param minHeight minimum height allowed during resize/creation (optional) + * @param maxHeight maximum height allowed during resize/creation (optional) + * @param id value for `data-gs-id` (optional) + */ + addWidget(el: GridStackElement, x ? : number, y ? : number, width ? : number, height ? : number, autoPosition ? : boolean, + minWidth ? : number, maxWidth ? : number, minHeight ? : number, maxHeight ? : number, id ? : number | string): JQuery; + + /** + * Initializes batch updates. You will see no changes until commit method is called. + */ + batchUpdate(): void; + + /** + * Gets current cell height. + */ + cellHeight(): number; + + /** + * Update current cell height - see `GridstackOptions.cellHeight` for format. + * This method rebuilds an internal CSS style sheet. + * Note: You can expect performance issues if call this method too often. + * + * @param val the cell height + * @param noUpdate (Optional) if true, styles will not be updated + * + * @example + * grid.cellHeight(grid.cellWidth() * 1.2); + */ + cellHeight(val: number | string, noUpdate ? : boolean): void; + + /** + * Gets current cell width. + */ + cellWidth(): number; + + /** + * Finishes batch updates. Updates DOM nodes. You must call it after batchUpdate. + */ + commit(): void; + + /** + * relayout grid items to reclaim any empty space + */ + compact(): void; + + /** + * Destroys a grid instance. + * @param detachGrid if false nodes and grid will not be removed from the DOM (Optional. Default true). + */ + destroy(detachGrid ? : boolean): void; + + /** + * Disables widgets moving/resizing. This is a shortcut for: + * @example + * grid.movable('.grid-stack-item', false); + * grid.resizable('.grid-stack-item', false); + */ + disable(): void; + + /** + * Enables widgets moving/resizing. This is a shortcut for: + * @example + * grid.movable('.grid-stack-item', true); + * grid.resizable('.grid-stack-item', true); + */ + enable(): void; + + /** + * Enables/disables widget moving. + * This is a shortcut for: + * @example + * grid.movable(this.container.children('.' + this.opts.itemClass), doEnable); + * + * @param doEnable + * @param includeNewWidgets will force new widgets to be draggable as per + * doEnable`s value by changing the disableDrag grid option. + */ + enableMove(doEnable: boolean, includeNewWidgets: boolean): void; + + /** + * Enables/disables widget resizing + * @param doEnable + * @param includeNewWidgets will force new widgets to be draggable as per + * doEnable`s value by changing the disableResize grid option. + * + * This is a shortcut for: + * @example + * grid.resizable(this.container.children('.' + this.opts.itemClass), doEnable); + */ + enableResize(doEnable: boolean, includeNewWidgets: boolean): void; + + /** + * enable/disable floating widgets (default: `false`) See [example](http://gridstackjs.com/demo/float.html) + * @param mode + */ + float(mode: boolean): void; + + /** + * get the current float mode + */ + float(): boolean; + + + + /** + * Get the position of the cell under a pixel on screen. + * @param position the position of the pixel to resolve in + * absolute coordinates, as an object with top and left properties + * @param useOffset if true, value will be based on offset vs position (Optional. Default false). + * Useful when grid is within `position: relative` element + * + * Returns an object with properties `x` and `y` i.e. the column and row in the grid. + */ + getCellFromPixel(position: MousePosition, useOffset ? : boolean): CellPosition; + + /** + * Checks if specified area is empty. + * @param x the position x. + * @param y the position y. + * @param width the width of to check + * @param height the height of to check + */ + isAreaEmpty(x: number, y: number, width: number, height: number): void; + + /** + * Locks/unlocks widget. + * @param el widget to modify. + * @param val if true widget will be locked. + */ + locked(el: GridStackElement, val: boolean): void; + + /** + * If you add elements to your gridstack container by hand, you have to tell gridstack afterwards to make them widgets. + * If you want gridstack to add the elements for you, use addWidget instead. + * Makes the given element a widget and returns it. + * @param el widget to convert. + * + * @example + * $('.grid-stack').gridstack(); + * $('.grid-stack').append('
') + * var grid = $('.grid-stack').data('gridstack'); + * grid.makeWidget('gsi-1'); + */ + makeWidget(el: GridStackElement): JQuery; + + /** + * Set the maxWidth for a widget. + * @param el widget to modify. + * @param val A numeric value of the number of columns + */ + maxWidth(el: GridStackElement, val: number): void; + + /** + * Set the minWidth for a widget. + * @param el widget to modify. + * @param val A numeric value of the number of columns + */ + minWidth(el: GridStackElement, val: number): void; + + /** + * Set the maxHeight for a widget. + * @param el widget to modify. + * @param val A numeric value of the number of rows + */ + maxHeight(el: GridStackElement, val: number): void; + + /** + * Set the minHeight for a widget. + * @param el widget to modify. + * @param val A numeric value of the number of rows + */ + minHeight(el: GridStackElement, val: number): void; + + /** + * Enables/Disables moving. + * @param el widget to modify. + * @param val if true widget will be draggable. + */ + movable(el: GridStackElement, val: boolean): void; + + /** + * Changes widget position + * @param el widget to modify + * @param x new position x. If value is null or undefined it will be ignored. + * @param y new position y. If value is null or undefined it will be ignored. + */ + move(el: GridStackElement, x: number, y: number): void; + + /** + * Removes widget from the grid. + * @param el widget to modify + * @param detachNode if false DOM node won't be removed from the tree (Default? true). + */ + removeWidget(el: GridStackElement, detachNode ? : boolean): void; + + /** + * Removes all widgets from the grid. + * @param detachNode if false DOM nodes won't be removed from the tree (Default? true). + */ + removeAll(detachNode ? : boolean): void; + + /** + * Changes widget size + * @param el widget to modify + * @param width new dimensions width. If value is null or undefined it will be ignored. + * @param height new dimensions height. If value is null or undefined it will be ignored. + */ + resize(el: GridStackElement, width: number, height: number): void; + + /** + * Enables/Disables resizing. + * @param el widget to modify + * @param val if true widget will be resizable. + */ + resizable(el: GridStackElement, val: boolean): void; + + /** + * Toggle the grid animation state. Toggles the `grid-stack-animate` class. + * @param doAnimate if true the grid will animate. + */ + setAnimation(doAnimate: boolean): void; + + /** + * Modify number of columns in the grid. Will update existing widgets to conform to new number of columns, + * as well as cache the original layout so you can revert back to previous positions without loss. + * Requires `gridstack-extra.css` or `gridstack-extra.min.css` for [1-11], + * else you will need to generate correct CSS (see https://github.com/gridstack/gridstack.js#change-grid-columns) + * @param column - Integer > 0 (default 12). + * @param doNotPropagate if true existing widgets will not be updated (optional) + */ + setColumn(column: number, doNotPropagate ? : boolean): void; + + /** + * Toggle the grid static state. Also toggle the grid-stack-static class. + * @param staticValue if true the grid become static. + */ + setStatic(staticValue: boolean): void; + + /** + * Updates widget position/size. + * @param el widget to modify + * @param x new position x. If value is null or undefined it will be ignored. + * @param y new position y. If value is null or undefined it will be ignored. + * @param width new dimensions width. If value is null or undefined it will be ignored. + * @param height new dimensions height. If value is null or undefined it will be ignored. + */ + update(el: GridStackElement, x: number, y: number, width: number, height: number): void; + + /** + * returns current vertical margin value + */ + verticalMargin(): number; + + /** + * Updates the vertical margin - see `GridstackOptions.verticalMargin` for format options. + * + * @param value new vertical margin value + * @param noUpdate (optional) if true, styles will not be updated + */ + verticalMargin(value: number | string, noUpdate ? : boolean): void; + + /** + * Returns true if the height of the grid will be less the vertical + * constraint. Always returns true if grid doesn't have height constraint. + * @param x new position x. If value is null or undefined it will be ignored. + * @param y new position y. If value is null or undefined it will be ignored. + * @param width new dimensions width. If value is null or undefined it will be ignored. + * @param height new dimensions height. If value is null or undefined it will be ignored. + * @param autoPosition if true then x, y parameters will be ignored and widget + * will be places on the first available position + * + * @example + * if (grid.willItFit(newNode.x, newNode.y, newNode.width, newNode.height, true)) { + * grid.addWidget(newNode.el, newNode.x, newNode.y, newNode.width, newNode.height, true); + * } else { + * alert('Not enough free space to place the widget'); + * } + */ + willItFit(x: number, y: number, width: number, height: number, autoPosition: boolean): boolean; +} + +/** + * Defines the coordinates of an object + */ +interface MousePosition { + top: number; + left: number; +} + +/** + * Defines the position of a cell inside the grid + */ +interface CellPosition { + x: number; + y: number; +} + +/** + * Gridstack Widget creation options + * @param x widget position x (default?: 0) + * @param y widget position y (default?: 0) + * @param width widget dimension width (default?: 1) + * @param height widget dimension height (default?: 1) + * @param autoPosition if true then x, y parameters will be ignored and widget will be places on the first available position (default?: false) + * @param minWidth minimum width allowed during resize/creation (default?: undefined = un-constrained) + * @param maxWidth maximum width allowed during resize/creation (default?: undefined = un-constrained) + * @param minHeight minimum height allowed during resize/creation (default?: undefined = un-constrained) + * @param maxHeight maximum height allowed during resize/creation (default?: undefined = un-constrained) + * @param id value for `data-gs-id` stored on the widget (default?: undefined) + */ +interface GridstackWidget { + x ? : number; + y ? : number; + width ? : number; + height ? : number; + autoPosition ? : boolean; + minWidth ? : number; + maxWidth ? : number; + minHeight ? : number; + maxHeight ? : number; + id ? : number | string; +} + +declare namespace GridStackUI { + interface Utils { + /** + * Sorts array of nodes + * @param nodes array to sort + * @param dir 1 for asc, -1 for desc (optional) + * @param width width of the grid. If undefined the width will be calculated automatically (optional). + **/ + sort(nodes: HTMLElement[], dir ? : number, width ? : number): void; + } +} + +/** + * Gridstack Options + * Defines the options for a Gridstack + */ +interface GridstackOptions { + /** + * accept widgets dragged from other grids or from outside (default: `false`). Can be: + * `true` (uses `'.grid-stack-item'` class filter) or `false`, + * string for explicit class name, + * function returning a boolean. See [example](http://gridstack.github.io/gridstack.js/demo/two.html) + */ + acceptWidgets ? : boolean | string | ((i: number, element: Element) => boolean); + + /** + * if true the resizing handles are shown even if the user is not hovering over the widget (default?: false) + */ + alwaysShowResizeHandle ? : boolean; + + /** + * turns animation on (default?: true) + */ + animate ? : boolean; + + /** + * if false gridstack will not initialize existing items (default?: true) + */ + auto ? : boolean; + + /** + * one cell height (default?: 60). Can be: + * an integer (px) + * a string (ex: '100px', '10em', '10rem', '10%') + * 0 or null, in which case the library will not generate styles for rows. Everything must be defined in CSS files. + * 'auto' - height will be calculated to match cell width (initial square grid). + */ + cellHeight ? : number | string; + + /** + * (internal?) unit for cellHeight (default? 'px') + */ + cellHeightUnit ? : string; + + /** class that implement drag'n'drop functionality for gridstack. If false grid will be static. + * (default?: null - first available plugin will be used) + */ + ddPlugin ? : boolean | null | any; + + /** disallows dragging of widgets (default?: false) */ + disableDrag ? : boolean; + + /** disallows resizing of widgets (default?: false). */ + disableResize ? : boolean; + + /** + * allows to override jQuery UI draggable options. (default?: { handle?: '.grid-stack-item-content', scroll?: true, appendTo?: 'body', containment: null }) + */ + draggable ? : {}; + + /** + * let user drag nested grid items out of a parent or not (default false) + */ + dragOut ? : boolean; + + /** + * draggable handle selector (default?: '.grid-stack-item-content') + */ + handle ? : string; + + /** draggable handle class (e.g. 'grid-stack-item-content'). If set 'handle' is ignored (default?: null) */ + handleClass ? : string; + + /** + * number of columns (default?: 12). Note: IF you change this, CSS also have to change. See https://github.com/gridstack/gridstack.js#change-grid-columns + */ + column ? : number; + + /** + * maximum rows amount. Default? is 0 which means no maximum rows + */ + maxRow ? : number; + + /** + * enable floating widgets (default?: false) See example (http://gridstack.github.io/gridstack.js/demo/float.html) + */ + float ? : boolean; + + /** + * widget class (default?: 'grid-stack-item') + */ + itemClass ? : string; + + /** + * minimal width. If window width is less, grid will be shown in one column mode (default?: 768) + */ + minWidth ? : number; + + /** disables the onColumnMode when the window width is less than minWidth (default?: false) */ + disableOneColumnMode ? : boolean; + + /** + * set to true if you want oneColumnMode to use the DOM order and ignore x,y from normal multi column + * layouts during sorting. This enables you to have custom 1 column layout that differ from the rest. (default?: false) + */ + oneColumnModeDomSort?: boolean; + + /** + * class for placeholder (default?: 'grid-stack-placeholder') + */ + placeholderClass ? : string; + + /** placeholder default content (default?: '') */ + placeholderText ? : string; + + /** + * allows to override jQuery UI resizable options. (default?: { autoHide?: true, handles?: 'se' }) + */ + resizable ? : {}; + + /** + * if true widgets could be removed by dragging outside of the grid. It could also be a jQuery selector string, + * in this case widgets will be removed by dropping them there (default?: false) + * See example (http://gridstack.github.io/gridstack.js/demo/two.html) + */ + removable ? : boolean | string; + + /** + * time in milliseconds before widget is being removed while dragging outside of the grid. (default?: 2000) + */ + removeTimeout ? : number; + + /** + * if true turns grid to RTL. Possible values are true, false, 'auto' (default?: 'auto') + * See [example](http://gridstack.github.io/gridstack.js/demo/rtl.html) + */ + rtl ? : boolean | 'auto'; + + /** + * makes grid static (default?: false).If true widgets are not movable/resizable. + * You don't even need jQueryUI draggable/resizable. A CSS class + * 'grid-stack-static' is also added to the container. + */ + staticGrid ? : boolean; + + /** + * vertical gap size (default?: 20). Can be: + * an integer (px) + * a string (ex: '2em', '20px', '2rem') + */ + verticalMargin ? : number | string; + + /** + * (internal?) unit for verticalMargin (default? 'px') + */ + verticalMarginUnit ? : string; +} \ No newline at end of file diff --git a/software/flow/node_modules/gridstack/dist/gridstack.jQueryUI.js b/software/flow/node_modules/gridstack/dist/gridstack.jQueryUI.js new file mode 100644 index 0000000..ac3b007 --- /dev/null +++ b/software/flow/node_modules/gridstack/dist/gridstack.jQueryUI.js @@ -0,0 +1,89 @@ +/** gridstack.js 0.6.4 - JQuery UI Drag&Drop plugin @preserve */ +/** + * https://gridstackjs.com/ + * (c) 2014-2020 Alain Dumesny, Dylan Weiss, Pavel Reznikov + * gridstack.js may be freely distributed under the MIT license. +*/ +(function(factory) { + if (typeof define === 'function' && define.amd) { + define(['jquery', 'gridstack', 'exports'], factory); + } else if (typeof exports !== 'undefined') { + try { jQuery = require('jquery'); } catch (e) {} + try { gridstack = require('gridstack'); } catch (e) {} + factory(jQuery, gridstack.GridStackUI, exports); + } else { + factory(jQuery, GridStackUI, window); + } +})(function($, GridStackUI, scope) { + /** + * @class JQueryUIGridStackDragDropPlugin + * jQuery UI implementation of drag'n'drop gridstack plugin. + */ + function JQueryUIGridStackDragDropPlugin(grid) { + GridStackUI.GridStackDragDropPlugin.call(this, grid); + } + + GridStackUI.GridStackDragDropPlugin.registerPlugin(JQueryUIGridStackDragDropPlugin); + + JQueryUIGridStackDragDropPlugin.prototype = Object.create(GridStackUI.GridStackDragDropPlugin.prototype); + JQueryUIGridStackDragDropPlugin.prototype.constructor = JQueryUIGridStackDragDropPlugin; + + JQueryUIGridStackDragDropPlugin.prototype.resizable = function(el, opts) { + el = $(el); + if (opts === 'disable' || opts === 'enable') { + el.resizable(opts); + } else if (opts === 'option') { + var key = arguments[2]; + var value = arguments[3]; + el.resizable(opts, key, value); + } else { + var handles = el.data('gs-resize-handles') ? el.data('gs-resize-handles') : + this.grid.opts.resizable.handles; + el.resizable($.extend({}, this.grid.opts.resizable, { + handles: handles + }, { + start: opts.start || function() {}, + stop: opts.stop || function() {}, + resize: opts.resize || function() {} + })); + } + return this; + }; + + JQueryUIGridStackDragDropPlugin.prototype.draggable = function(el, opts) { + el = $(el); + if (opts === 'disable' || opts === 'enable') { + el.draggable(opts); + } else { + el.draggable($.extend({}, this.grid.opts.draggable, { + containment: (this.grid.opts.isNested && !this.grid.opts.dragOut) ? + this.grid.container.parent() : + (this.grid.opts.draggable.containment || null), + start: opts.start || function() {}, + stop: opts.stop || function() {}, + drag: opts.drag || function() {} + })); + } + return this; + }; + + JQueryUIGridStackDragDropPlugin.prototype.droppable = function(el, opts) { + el = $(el); + el.droppable(opts); + return this; + }; + + JQueryUIGridStackDragDropPlugin.prototype.isDroppable = function(el, opts) { + el = $(el); + return Boolean(el.data('droppable')); + }; + + JQueryUIGridStackDragDropPlugin.prototype.on = function(el, eventName, callback) { + $(el).on(eventName, callback); + return this; + }; + + scope.JQueryUIGridStackDragDropPlugin = JQueryUIGridStackDragDropPlugin; + + return JQueryUIGridStackDragDropPlugin; +}); diff --git a/software/flow/node_modules/gridstack/dist/gridstack.jQueryUI.min.js b/software/flow/node_modules/gridstack/dist/gridstack.jQueryUI.min.js new file mode 100644 index 0000000..6ab22f2 --- /dev/null +++ b/software/flow/node_modules/gridstack/dist/gridstack.jQueryUI.min.js @@ -0,0 +1,3 @@ +/** gridstack.js 0.6.4 - JQuery UI Drag&Drop plugin @preserve */ +!function(t){if("function"==typeof define&&define.amd)define(["jquery","gridstack","exports"],t);else if("undefined"!=typeof exports){try{jQuery=require("jquery")}catch(t){}try{gridstack=require("gridstack")}catch(t){}t(jQuery,gridstack.GridStackUI,exports)}else t(jQuery,GridStackUI,window)}(function(a,e,t){function r(t){e.GridStackDragDropPlugin.call(this,t)}return e.GridStackDragDropPlugin.registerPlugin(r),((r.prototype=Object.create(e.GridStackDragDropPlugin.prototype)).constructor=r).prototype.resizable=function(t,e){if(t=a(t),"disable"===e||"enable"===e)t.resizable(e);else if("option"===e){var r=arguments[2],i=arguments[3];t.resizable(e,r,i)}else{var n=t.data("gs-resize-handles")?t.data("gs-resize-handles"):this.grid.opts.resizable.handles;t.resizable(a.extend({},this.grid.opts.resizable,{handles:n},{start:e.start||function(){},stop:e.stop||function(){},resize:e.resize||function(){}}))}return this},r.prototype.draggable=function(t,e){return t=a(t),"disable"===e||"enable"===e?t.draggable(e):t.draggable(a.extend({},this.grid.opts.draggable,{containment:this.grid.opts.isNested&&!this.grid.opts.dragOut?this.grid.container.parent():this.grid.opts.draggable.containment||null,start:e.start||function(){},stop:e.stop||function(){},drag:e.drag||function(){}})),this},r.prototype.droppable=function(t,e){return(t=a(t)).droppable(e),this},r.prototype.isDroppable=function(t,e){return t=a(t),Boolean(t.data("droppable"))},r.prototype.on=function(t,e,r){return a(t).on(e,r),this},t.JQueryUIGridStackDragDropPlugin=r}); +//# sourceMappingURL=gridstack.min.map \ No newline at end of file diff --git a/software/flow/node_modules/gridstack/dist/gridstack.js b/software/flow/node_modules/gridstack/dist/gridstack.js new file mode 100644 index 0000000..956cd7a --- /dev/null +++ b/software/flow/node_modules/gridstack/dist/gridstack.js @@ -0,0 +1,2033 @@ +/** + * gridstack.js 0.6.4 + * https://gridstackjs.com/ + * (c) 2014-2020 Alain Dumesny, Dylan Weiss, Pavel Reznikov + * gridstack.js may be freely distributed under the MIT license. + * @preserve +*/ +(function(factory) { + if (typeof define === 'function' && define.amd) { + define(['jquery', 'exports'], factory); + } else if (typeof exports !== 'undefined') { + var jQueryModule; + + try { jQueryModule = require('jquery'); } catch (e) {} + + factory(jQueryModule || window.jQuery, exports); + } else { + factory(window.jQuery, window); + } +})(function($, scope) { + + // checks for obsolete method names + var obsolete = function(f, oldName, newName, rev) { + var wrapper = function() { + console.warn('gridstack.js: Function `' + oldName + '` is deprecated in ' + rev + ' and has been replaced ' + + 'with `' + newName + '`. It will be **completely** removed in v1.0'); + return f.apply(this, arguments); + }; + wrapper.prototype = f.prototype; + + return wrapper; + }; + + // checks for obsolete grid options (can be used for any fields, but msg is about options) + var obsoleteOpts = function(opts, oldName, newName, rev) { + if (opts[oldName] !== undefined) { + opts[newName] = opts[oldName]; + console.warn('gridstack.js: Option `' + oldName + '` is deprecated in ' + rev + ' and has been replaced with `' + + newName + '`. It will be **completely** removed in v1.0'); + } + }; + + // checks for obsolete grid options which are gone + var obsoleteOptsDel = function(opts, oldName, rev, info) { + if (opts[oldName] !== undefined) { + console.warn('gridstack.js: Option `' + oldName + '` is deprecated in ' + rev + info); + } + }; + + // checks for obsolete Jquery element attributes + var obsoleteAttr = function(el, oldName, newName, rev) { + var oldAttr = el.attr(oldName); + if (oldAttr !== undefined) { + el.attr(newName, oldAttr); + console.warn('gridstack.js: attribute `' + oldName + '`=' + oldAttr + ' is deprecated on this object in ' + rev + ' and has been replaced with `' + + newName + '`. It will be **completely** removed in v1.0'); + } + }; + + var Utils = { + + isIntercepted: function(a, b) { + return !(a.x + a.width <= b.x || b.x + b.width <= a.x || a.y + a.height <= b.y || b.y + b.height <= a.y); + }, + + sort: function(nodes, dir, column) { + if (!column) { + var widths = nodes.map(function(node) { return node.x + node.width; }); + column = Math.max.apply(Math, widths); + } + + if (dir === -1) + return Utils.sortBy(nodes, function(n) { return -(n.x + n.y * column); }); + else + return Utils.sortBy(nodes, function(n) { return (n.x + n.y * column); }); + }, + + createStylesheet: function(id, parent) { + var style = document.createElement('style'); + style.setAttribute('type', 'text/css'); + style.setAttribute('data-gs-style-id', id); + if (style.styleSheet) { + style.styleSheet.cssText = ''; + } else { + style.appendChild(document.createTextNode('')); + } + if (!parent) { parent = document.getElementsByTagName('head')[0]; } // default to head + parent.insertBefore(style, parent.firstChild); + return style.sheet; + }, + + removeStylesheet: function(id) { + $('STYLE[data-gs-style-id=' + id + ']').remove(); + }, + + insertCSSRule: function(sheet, selector, rules, index) { + if (typeof sheet.insertRule === 'function') { + sheet.insertRule(selector + '{' + rules + '}', index); + } else if (typeof sheet.addRule === 'function') { + sheet.addRule(selector, rules, index); + } + }, + + toBool: function(v) { + if (typeof v === 'boolean') { + return v; + } + if (typeof v === 'string') { + v = v.toLowerCase(); + return !(v === '' || v === 'no' || v === 'false' || v === '0'); + } + return Boolean(v); + }, + + _collisionNodeCheck: function(n) { + return n !== this.node && Utils.isIntercepted(n, this.nn); + }, + + _didCollide: function(bn) { + return Utils.isIntercepted({x: this.n.x, y: this.newY, width: this.n.width, height: this.n.height}, bn); + }, + + _isAddNodeIntercepted: function(n) { + return Utils.isIntercepted({x: this.x, y: this.y, width: this.node.width, height: this.node.height}, n); + }, + + parseHeight: function(val) { + var height = val; + var heightUnit = 'px'; + if (height && typeof height === 'string') { + var match = height.match(/^(-[0-9]+\.[0-9]+|[0-9]*\.[0-9]+|-[0-9]+|[0-9]+)(px|em|rem|vh|vw|%)?$/); + if (!match) { + throw new Error('Invalid height'); + } + heightUnit = match[2] || 'px'; + height = parseFloat(match[1]); + } + return {height: height, unit: heightUnit}; + }, + + without: function(array, item) { + var index = array.indexOf(item); + + if (index !== -1) { + array = array.slice(0); + array.splice(index, 1); + } + + return array; + }, + + sortBy: function(array, getter) { + return array.slice(0).sort(function(left, right) { + var valueLeft = getter(left); + var valueRight = getter(right); + + if (valueRight === valueLeft) { + return 0; + } + + return valueLeft > valueRight ? 1 : -1; + }); + }, + + defaults: function(target) { + var sources = Array.prototype.slice.call(arguments, 1); + + sources.forEach(function(source) { + for (var prop in source) { + if (source.hasOwnProperty(prop) && (!target.hasOwnProperty(prop) || target[prop] === undefined)) { + target[prop] = source[prop]; + } + } + }); + + return target; + }, + + clone: function(target) { + return $.extend({}, target); + }, + + throttle: function(callback, delay) { + var isWaiting = false; + + return function() { + if (!isWaiting) { + callback.apply(this, arguments); + isWaiting = true; + setTimeout(function() { isWaiting = false; }, delay); + } + }; + }, + + removePositioningStyles: function(el) { + var style = el[0].style; + if (style.position) { + style.removeProperty('position'); + } + if (style.left) { + style.removeProperty('left'); + } + if (style.top) { + style.removeProperty('top'); + } + if (style.width) { + style.removeProperty('width'); + } + if (style.height) { + style.removeProperty('height'); + } + }, + getScrollParent: function(el) { + var returnEl; + if (el === null) { + returnEl = null; + } else if (el.scrollHeight > el.clientHeight) { + returnEl = el; + } else { + returnEl = Utils.getScrollParent(el.parentNode); + } + return returnEl; + }, + updateScrollPosition: function(el, ui, distance) { + // is widget in view? + var rect = el.getBoundingClientRect(); + var innerHeightOrClientHeight = (window.innerHeight || document.documentElement.clientHeight); + if (rect.top < 0 || + rect.bottom > innerHeightOrClientHeight + ) { + // set scrollTop of first parent that scrolls + // if parent is larger than el, set as low as possible + // to get entire widget on screen + var offsetDiffDown = rect.bottom - innerHeightOrClientHeight; + var offsetDiffUp = rect.top; + var scrollEl = Utils.getScrollParent(el); + if (scrollEl !== null) { + var prevScroll = scrollEl.scrollTop; + if (rect.top < 0 && distance < 0) { + // moving up + if (el.offsetHeight > innerHeightOrClientHeight) { + scrollEl.scrollTop += distance; + } else { + scrollEl.scrollTop += Math.abs(offsetDiffUp) > Math.abs(distance) ? distance : offsetDiffUp; + } + } else if (distance > 0) { + // moving down + if (el.offsetHeight > innerHeightOrClientHeight) { + scrollEl.scrollTop += distance; + } else { + scrollEl.scrollTop += offsetDiffDown > distance ? distance : offsetDiffDown; + } + } + // move widget y by amount scrolled + ui.position.top += scrollEl.scrollTop - prevScroll; + } + } + } + }; + + /** + * @class GridStackDragDropPlugin + * Base class for drag'n'drop plugin. + */ + function GridStackDragDropPlugin(grid) { + this.grid = grid; + } + + GridStackDragDropPlugin.registeredPlugins = []; + + GridStackDragDropPlugin.registerPlugin = function(pluginClass) { + GridStackDragDropPlugin.registeredPlugins.push(pluginClass); + }; + + GridStackDragDropPlugin.prototype.resizable = function(el, opts) { + return this; + }; + + GridStackDragDropPlugin.prototype.draggable = function(el, opts) { + return this; + }; + + GridStackDragDropPlugin.prototype.droppable = function(el, opts) { + return this; + }; + + GridStackDragDropPlugin.prototype.isDroppable = function(el) { + return false; + }; + + GridStackDragDropPlugin.prototype.on = function(el, eventName, callback) { + return this; + }; + + + var idSeq = 0; + + var GridStackEngine = function(column, onchange, float, maxRow, items) { + this.column = column || 12; + this.float = float || false; + this.maxRow = maxRow || 0; + + this.nodes = items || []; + this.onchange = onchange || function() {}; + + this._addedNodes = []; + this._removedNodes = []; + this._batchMode = false; + }; + + GridStackEngine.prototype.batchUpdate = function() { + if (this._batchMode) return; + this._batchMode = true; + this._prevFloat = this.float; + this.float = true; // let things go anywhere for now... commit() will restore and possibly reposition + }; + + GridStackEngine.prototype.commit = function() { + if (!this._batchMode) return; + this._batchMode = false; + this.float = this._prevFloat; + delete this._prevFloat; + this._packNodes(); + this._notify(); + }; + + // For Meteor support: https://github.com/gridstack/gridstack.js/pull/272 + GridStackEngine.prototype.getNodeDataByDOMEl = function(el) { + return this.nodes.find(function(n) { return el.get(0) === n.el.get(0); }); + }; + + GridStackEngine.prototype._fixCollisions = function(node) { + var self = this; + this._sortNodes(-1); + + var nn = node; + var hasLocked = Boolean(this.nodes.find(function(n) { return n.locked; })); + if (!this.float && !hasLocked) { + nn = {x: 0, y: node.y, width: this.column, height: node.height}; + } + while (true) { + var collisionNode = this.nodes.find(Utils._collisionNodeCheck, {node: node, nn: nn}); + if (!collisionNode) { return; } + this.moveNode(collisionNode, collisionNode.x, node.y + node.height, + collisionNode.width, collisionNode.height, true); + } + }; + + GridStackEngine.prototype.isAreaEmpty = function(x, y, width, height) { + var nn = {x: x || 0, y: y || 0, width: width || 1, height: height || 1}; + var collisionNode = this.nodes.find(function(n) { + return Utils.isIntercepted(n, nn); + }); + return !collisionNode; + }; + + GridStackEngine.prototype._sortNodes = function(dir) { + this.nodes = Utils.sort(this.nodes, dir, this.column); + }; + + GridStackEngine.prototype._packNodes = function() { + this._sortNodes(); + + if (this.float) { + this.nodes.forEach(function(n, i) { + if (n._updating || n._packY === undefined || n.y === n._packY) { + return; + } + + var newY = n.y; + while (newY >= n._packY) { + var collisionNode = this.nodes + .slice(0, i) + .find(Utils._didCollide, {n: n, newY: newY}); + + if (!collisionNode) { + n._dirty = true; + n.y = newY; + } + --newY; + } + }, this); + } else { + this.nodes.forEach(function(n, i) { + if (n.locked) { return; } + while (n.y > 0) { + var newY = n.y - 1; + var canBeMoved = i === 0; + + if (i > 0) { + var collisionNode = this.nodes + .slice(0, i) + .find(Utils._didCollide, {n: n, newY: newY}); + canBeMoved = collisionNode === undefined; + } + + if (!canBeMoved) { break; } + // Note: must be dirty (from last position) for GridStack::OnChange CB to update positions + // and move items back. The user 'change' CB should detect changes from the original + // starting position instead. + n._dirty = (n.y !== newY); + n.y = newY; + } + }, this); + } + }; + + GridStackEngine.prototype._prepareNode = function(node, resizing) { + node = node || {}; + // if we're missing position, have the grid position us automatically (before we set them to 0,0) + if (node.x === undefined || node.y === undefined || node.x === null || node.y === null) { + node.autoPosition = true; + } + + // assign defaults for missing required fields + var defaults = {width: 1, height: 1, x: 0, y: 0}; + node = Utils.defaults(node, defaults); + + // convert any strings over + node.x = parseInt(node.x); + node.y = parseInt(node.y); + node.width = parseInt(node.width); + node.height = parseInt(node.height); + node.autoPosition = node.autoPosition || false; + node.noResize = node.noResize || false; + node.noMove = node.noMove || false; + + // check for NaN (in case messed up strings were passed. can't do parseInt() || defaults.x above as 0 is valid #) + if (Number.isNaN(node.x)) { node.x = defaults.x; node.autoPosition = true; } + if (Number.isNaN(node.y)) { node.y = defaults.y; node.autoPosition = true; } + if (Number.isNaN(node.width)) { node.width = defaults.width; } + if (Number.isNaN(node.height)) { node.height = defaults.height; } + + if (node.width > this.column) { + node.width = this.column; + } else if (node.width < 1) { + node.width = 1; + } + + if (node.height < 1) { + node.height = 1; + } + + if (node.x < 0) { + node.x = 0; + } + + if (node.x + node.width > this.column) { + if (resizing) { + node.width = this.column - node.x; + } else { + node.x = this.column - node.width; + } + } + + if (node.y < 0) { + node.y = 0; + } + + return node; + }; + + GridStackEngine.prototype._notify = function() { + if (this._batchMode) { return; } + var args = Array.prototype.slice.call(arguments, 0); + args[0] = (args[0] === undefined ? [] : (Array.isArray(args[0]) ? args[0] : [args[0]]) ); + args[1] = (args[1] === undefined ? true : args[1]); + var dirtyNodes = args[0].concat(this.getDirtyNodes()); + this.onchange(dirtyNodes, args[1]); + }; + + GridStackEngine.prototype.cleanNodes = function() { + if (this._batchMode) { return; } + this.nodes.forEach(function(n) { delete n._dirty; }); + }; + + GridStackEngine.prototype.getDirtyNodes = function(verify) { + // compare original X,Y,W,H (or entire node?) instead as _dirty can be a temporary state + if (verify) { + var dirtNodes = []; + this.nodes.forEach(function (n) { + if (n._dirty) { + if (n.y === n._origY && n.x === n._origX && n.width === n._origW && n.height === n._origH) { + delete n._dirty; + } else { + dirtNodes.push(n); + } + } + }); + return dirtNodes; + } + + return this.nodes.filter(function(n) { return n._dirty; }); + }; + + GridStackEngine.prototype.addNode = function(node, triggerAddEvent) { + node = this._prepareNode(node); + + if (node.maxWidth !== undefined) { node.width = Math.min(node.width, node.maxWidth); } + if (node.maxHeight !== undefined) { node.height = Math.min(node.height, node.maxHeight); } + if (node.minWidth !== undefined) { node.width = Math.max(node.width, node.minWidth); } + if (node.minHeight !== undefined) { node.height = Math.max(node.height, node.minHeight); } + + node._id = node._id || ++idSeq; + + if (node.autoPosition) { + this._sortNodes(); + + for (var i = 0;; ++i) { + var x = i % this.column; + var y = Math.floor(i / this.column); + if (x + node.width > this.column) { + continue; + } + if (!this.nodes.find(Utils._isAddNodeIntercepted, {x: x, y: y, node: node})) { + node.x = x; + node.y = y; + delete node.autoPosition; // found our slot + break; + } + } + } + + this.nodes.push(node); + if (triggerAddEvent) { + this._addedNodes.push(node); + } + + this._fixCollisions(node); + this._packNodes(); + this._notify(); + return node; + }; + + GridStackEngine.prototype.removeNode = function(node, detachNode) { + detachNode = (detachNode === undefined ? true : detachNode); + this._removedNodes.push(node); + node._id = null; // hint that node is being removed + this.nodes = Utils.without(this.nodes, node); + this._packNodes(); + this._notify(node, detachNode); + }; + + GridStackEngine.prototype.removeAll = function(detachNode) { + delete this._layouts; + if (this.nodes.length === 0) { return; } + detachNode = (detachNode === undefined ? true : detachNode); + this.nodes.forEach(function(n) { n._id = null; }); // hint that node is being removed + this._removedNodes = this.nodes; + this.nodes = []; + this._notify(this._removedNodes, detachNode); + }; + + GridStackEngine.prototype.canMoveNode = function(node, x, y, width, height) { + if (!this.isNodeChangedPosition(node, x, y, width, height)) { + return false; + } + var hasLocked = Boolean(this.nodes.find(function(n) { return n.locked; })); + + if (!this.maxRow && !hasLocked) { + return true; + } + + var clonedNode; + var clone = new GridStackEngine( + this.column, + null, + this.float, + 0, + this.nodes.map(function(n) { + if (n === node) { + clonedNode = $.extend({}, n); + return clonedNode; + } + return $.extend({}, n); + })); + + if (!clonedNode) { return true;} + + clone.moveNode(clonedNode, x, y, width, height); + + var res = true; + + if (hasLocked) { + res &= !Boolean(clone.nodes.find(function(n) { + return n !== clonedNode && Boolean(n.locked) && Boolean(n._dirty); + })); + } + if (this.maxRow) { + res &= clone.getGridHeight() <= this.maxRow; + } + + return res; + }; + + GridStackEngine.prototype.canBePlacedWithRespectToHeight = function(node) { + if (!this.maxRow) { + return true; + } + + var clone = new GridStackEngine( + this.column, + null, + this.float, + 0, + this.nodes.map(function(n) { return $.extend({}, n); })); + clone.addNode(node); + return clone.getGridHeight() <= this.maxRow; + }; + + GridStackEngine.prototype.isNodeChangedPosition = function(node, x, y, width, height) { + if (typeof x !== 'number') { x = node.x; } + if (typeof y !== 'number') { y = node.y; } + if (typeof width !== 'number') { width = node.width; } + if (typeof height !== 'number') { height = node.height; } + + if (node.maxWidth !== undefined) { width = Math.min(width, node.maxWidth); } + if (node.maxHeight !== undefined) { height = Math.min(height, node.maxHeight); } + if (node.minWidth !== undefined) { width = Math.max(width, node.minWidth); } + if (node.minHeight !== undefined) { height = Math.max(height, node.minHeight); } + + if (node.x === x && node.y === y && node.width === width && node.height === height) { + return false; + } + return true; + }; + + GridStackEngine.prototype.moveNode = function(node, x, y, width, height, noPack) { + if (typeof x !== 'number') { x = node.x; } + if (typeof y !== 'number') { y = node.y; } + if (typeof width !== 'number') { width = node.width; } + if (typeof height !== 'number') { height = node.height; } + + if (node.maxWidth !== undefined) { width = Math.min(width, node.maxWidth); } + if (node.maxHeight !== undefined) { height = Math.min(height, node.maxHeight); } + if (node.minWidth !== undefined) { width = Math.max(width, node.minWidth); } + if (node.minHeight !== undefined) { height = Math.max(height, node.minHeight); } + + if (node.x === x && node.y === y && node.width === width && node.height === height) { + return node; + } + + var resizing = node.width !== width; + node._dirty = true; + + node.x = x; + node.y = y; + node.width = width; + node.height = height; + + node.lastTriedX = x; + node.lastTriedY = y; + node.lastTriedWidth = width; + node.lastTriedHeight = height; + + node = this._prepareNode(node, resizing); + + this._fixCollisions(node); + if (!noPack) { + this._packNodes(); + this._notify(); + } + return node; + }; + + GridStackEngine.prototype.getGridHeight = function() { + return this.nodes.reduce(function(memo, n) { return Math.max(memo, n.y + n.height); }, 0); + }; + + GridStackEngine.prototype.beginUpdate = function(node) { + if (node._updating) return; + node._updating = true; + this.nodes.forEach(function(n) { n._packY = n.y; }); + }; + + GridStackEngine.prototype.endUpdate = function() { + var n = this.nodes.find(function(n) { return n._updating; }); + if (n) { + n._updating = false; + this.nodes.forEach(function(n) { delete n._packY; }); + } + }; + + /** + * Construct a grid from the given element and options + * @param {GridStackElement} el + * @param {GridstackOptions} opts + */ + var GridStack = function(el, opts) { + var self = this; + var oneColumnMode, _prevColumn, isAutoCellHeight; + + opts = opts || {}; + + this.container = $(el); + + obsoleteOpts(opts, 'width', 'column', 'v0.5.3'); + obsoleteOpts(opts, 'height', 'maxRow', 'v0.5.3'); + obsoleteOptsDel(opts, 'oneColumnModeClass', 'v0.6.3', '. Use class `.grid-stack-1` instead'); + + // container attributes + obsoleteAttr(this.container, 'data-gs-width', 'data-gs-column', 'v0.5.3'); + obsoleteAttr(this.container, 'data-gs-height', 'data-gs-max-row', 'v0.5.3'); + + opts.itemClass = opts.itemClass || 'grid-stack-item'; + var isNested = this.container.closest('.' + opts.itemClass).length > 0; + + this.opts = Utils.defaults(opts, { + column: parseInt(this.container.attr('data-gs-column')) || 12, + maxRow: parseInt(this.container.attr('data-gs-max-row')) || 0, + itemClass: 'grid-stack-item', + placeholderClass: 'grid-stack-placeholder', + placeholderText: '', + handle: '.grid-stack-item-content', + handleClass: null, + cellHeight: 60, + verticalMargin: 20, + auto: true, + minWidth: 768, + float: false, + staticGrid: false, + _class: 'grid-stack-instance-' + (Math.random() * 10000).toFixed(0), + animate: Boolean(this.container.attr('data-gs-animate')) || false, + alwaysShowResizeHandle: opts.alwaysShowResizeHandle || false, + resizable: Utils.defaults(opts.resizable || {}, { + autoHide: !(opts.alwaysShowResizeHandle || false), + handles: 'se' + }), + draggable: Utils.defaults(opts.draggable || {}, { + handle: (opts.handleClass ? '.' + opts.handleClass : (opts.handle ? opts.handle : '')) || + '.grid-stack-item-content', + scroll: false, + appendTo: 'body' + }), + disableDrag: opts.disableDrag || false, + disableResize: opts.disableResize || false, + rtl: 'auto', + removable: false, + removableOptions: Utils.defaults(opts.removableOptions || {}, { + accept: '.' + opts.itemClass + }), + removeTimeout: 2000, + verticalMarginUnit: 'px', + cellHeightUnit: 'px', + disableOneColumnMode: opts.disableOneColumnMode || false, + oneColumnModeDomSort: opts.oneColumnModeDomSort, + ddPlugin: null + }); + + if (this.opts.ddPlugin === false) { + this.opts.ddPlugin = GridStackDragDropPlugin; + } else if (this.opts.ddPlugin === null) { + this.opts.ddPlugin = GridStackDragDropPlugin.registeredPlugins[0] || GridStackDragDropPlugin; + } + + this.dd = new this.opts.ddPlugin(this); + + if (this.opts.rtl === 'auto') { + this.opts.rtl = this.container.css('direction') === 'rtl'; + } + + if (this.opts.rtl) { + this.container.addClass('grid-stack-rtl'); + } + + this.opts.isNested = isNested; + + isAutoCellHeight = (this.opts.cellHeight === 'auto'); + if (isAutoCellHeight) { + // make the cell square initially + self.cellHeight(self.cellWidth(), true); + } else { + this.cellHeight(this.opts.cellHeight, true); + } + this.verticalMargin(this.opts.verticalMargin, true); + + this.container.addClass(this.opts._class); + + this._setStaticClass(); + + if (isNested) { + this.container.addClass('grid-stack-nested'); + } + + this._initStyles(); + + this.grid = new GridStackEngine(this.opts.column, function(nodes, detachNode) { + detachNode = (detachNode === undefined ? true : detachNode); + var maxHeight = 0; + this.nodes.forEach(function(n) { + maxHeight = Math.max(maxHeight, n.y + n.height); + }); + nodes.forEach(function(n) { + if (detachNode && n._id === null) { + if (n.el) { + n.el.remove(); + } + } else { + n.el + .attr('data-gs-x', n.x) + .attr('data-gs-y', n.y) + .attr('data-gs-width', n.width) + .attr('data-gs-height', n.height); + } + }); + self._updateStyles(maxHeight + 10); + }, this.opts.float, this.opts.maxRow); + + if (this.opts.auto) { + var elements = []; + var _this = this; + this.container.children('.' + this.opts.itemClass + ':not(.' + this.opts.placeholderClass + ')') + .each(function(index, el) { + el = $(el); + var x = parseInt(el.attr('data-gs-x')); + var y = parseInt(el.attr('data-gs-y')); + elements.push({ + el: el, + // if x,y are missing (autoPosition) add them to end of list - but keep their respective DOM order + i: (Number.isNaN(x) ? 1000 : x) + (Number.isNaN(y) ? 1000 : y) * _this.opts.column + }); + }); + Utils.sortBy(elements, function(x) { return x.i; }).forEach(function(item) { + this._prepareElement(item.el); + }, this); + } + this.grid._saveInitial(); // initial start of items + + this.setAnimation(this.opts.animate); + + this.placeholder = $( + '
' + + '
' + this.opts.placeholderText + '
').hide(); + + this._updateContainerHeight(); + + this._updateHeightsOnResize = Utils.throttle(function() { + self.cellHeight(self.cellWidth(), false); + }, 100); + + /** + * called when we are being resized - check if the one Column Mode needs to be turned on/off + * and remember the prev columns we used. + */ + this.onResizeHandler = function() { + if (isAutoCellHeight) { + self._updateHeightsOnResize(); + } + + if (self.opts.staticGrid) { return; } + + if (!self.opts.disableOneColumnMode && (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) <= self.opts.minWidth) { + if (self.oneColumnMode) { return; } + self.oneColumnMode = true; + self.setColumn(1); + } else { + if (!self.oneColumnMode) { return; } + self.oneColumnMode = false; + self.setColumn(self._prevColumn); + } + }; + + $(window).resize(this.onResizeHandler); + this.onResizeHandler(); + + if (!self.opts.staticGrid && typeof self.opts.removable === 'string') { + var trashZone = $(self.opts.removable); + if (!this.dd.isDroppable(trashZone)) { + this.dd.droppable(trashZone, self.opts.removableOptions); + } + this.dd + .on(trashZone, 'dropover', function(event, ui) { + var el = $(ui.draggable); + var node = el.data('_gridstack_node'); + if (!node || node._grid !== self) { + return; + } + el.data('inTrashZone', true); + self._setupRemovingTimeout(el); + }) + .on(trashZone, 'dropout', function(event, ui) { + var el = $(ui.draggable); + var node = el.data('_gridstack_node'); + if (!node || node._grid !== self) { + return; + } + el.data('inTrashZone', false); + self._clearRemovingTimeout(el); + }); + } + + if (!self.opts.staticGrid && self.opts.acceptWidgets) { + var draggingElement = null; + + var onDrag = function(event, ui) { + var el = draggingElement; + var node = el.data('_gridstack_node'); + var pos = self.getCellFromPixel({left: event.pageX, top: event.pageY}, true); + var x = Math.max(0, pos.x); + var y = Math.max(0, pos.y); + if (!node._added) { + node._added = true; + + node.el = el; + node.autoPosition = true; + node.x = x; + node.y = y; + self.grid.cleanNodes(); + self.grid.beginUpdate(node); + self.grid.addNode(node); + + self.container.append(self.placeholder); + self.placeholder + .attr('data-gs-x', node.x) + .attr('data-gs-y', node.y) + .attr('data-gs-width', node.width) + .attr('data-gs-height', node.height) + .show(); + node.el = self.placeholder; + node._beforeDragX = node.x; + node._beforeDragY = node.y; + + self._updateContainerHeight(); + } + if (!self.grid.canMoveNode(node, x, y)) { + return; + } + self.grid.moveNode(node, x, y); + self._updateContainerHeight(); + }; + + this.dd + .droppable(self.container, { + accept: function(el) { + el = $(el); + var node = el.data('_gridstack_node'); + if (node && node._grid === self) { + return false; + } + return el.is(self.opts.acceptWidgets === true ? '.grid-stack-item' : self.opts.acceptWidgets); + } + }) + .on(self.container, 'dropover', function(event, ui) { + var el = $(ui.draggable); + var width, height; + + // see if we already have a node with widget/height and check for attributes + var origNode = el.data('_gridstack_node'); + if (!origNode || !origNode.width || !origNode.height) { + var w = parseInt(el.attr('data-gs-width')); + if (w > 0) { origNode = origNode || {}; origNode.width = w; } + var h = parseInt(el.attr('data-gs-height')); + if (h > 0) { origNode = origNode || {}; origNode.height = h; } + } + + // if not calculate the grid size based on element outer size + // height: Each row is cellHeight + verticalMargin, until last one which has no margin below + var cellWidth = self.cellWidth(); + var cellHeight = self.cellHeight(); + var verticalMargin = self.opts.verticalMargin; + width = origNode && origNode.width ? origNode.width : Math.ceil(el.outerWidth() / cellWidth); + height = origNode && origNode.height ? origNode.height : Math.round((el.outerHeight() + verticalMargin) / (cellHeight + verticalMargin)); + + draggingElement = el; + + var node = self.grid._prepareNode({width: width, height: height, _added: false, _temporary: true}); + node.isOutOfGrid = true; + el.data('_gridstack_node', node); + el.data('_gridstack_node_orig', origNode); + + el.on('drag', onDrag); + return false; // prevent parent from receiving msg (which may be grid as well) + }) + .on(self.container, 'dropout', function(event, ui) { + // jquery-ui bug. Must verify widget is being dropped out + // check node variable that gets set when widget is out of grid + var el = $(ui.draggable); + if (!el.data('_gridstack_node')) { + return; + } + var node = el.data('_gridstack_node'); + if (!node.isOutOfGrid) { + return; + } + el.unbind('drag', onDrag); + node.el = null; + self.grid.removeNode(node); + self.placeholder.detach(); + self._updateContainerHeight(); + el.data('_gridstack_node', el.data('_gridstack_node_orig')); + return false; // prevent parent from receiving msg (which may be grid as well) + }) + .on(self.container, 'drop', function(event, ui) { + self.placeholder.detach(); + + var node = $(ui.draggable).data('_gridstack_node'); + node.isOutOfGrid = false; + node._grid = self; + var el = $(ui.draggable).clone(false); + el.data('_gridstack_node', node); + var originalNode = $(ui.draggable).data('_gridstack_node_orig'); + if (originalNode !== undefined && originalNode._grid !== undefined) { + originalNode._grid._triggerRemoveEvent(); + } + $(ui.helper).remove(); + node.el = el; + self.placeholder.hide(); + Utils.removePositioningStyles(el); + el.find('div.ui-resizable-handle').remove(); + + el + .attr('data-gs-x', node.x) + .attr('data-gs-y', node.y) + .attr('data-gs-width', node.width) + .attr('data-gs-height', node.height) + .addClass(self.opts.itemClass) + .enableSelection() + .removeData('draggable') + .removeClass('ui-draggable ui-draggable-dragging ui-draggable-disabled') + .unbind('drag', onDrag); + self.container.append(el); + self._prepareElementsByNode(el, node); + self._updateContainerHeight(); + self.grid._addedNodes.push(node); + self._triggerAddEvent(); + self._triggerChangeEvent(); + + self.grid.endUpdate(); + $(ui.draggable).unbind('drag', onDrag); + $(ui.draggable).removeData('_gridstack_node'); + $(ui.draggable).removeData('_gridstack_node_orig'); + self.container.trigger('dropped', [originalNode, node]); + return false; // prevent parent from receiving msg (which may be grid as well) + }); + } + }; + + GridStack.prototype._triggerChangeEvent = function(/*forceTrigger*/) { + if (this.grid._batchMode) { return; } + var elements = this.grid.getDirtyNodes(true); // verify they really changed + if (elements && elements.length) { + this.grid._layoutsNodesChange(elements); + this.container.trigger('change', [elements]); + } + this.grid._saveInitial(); // we called, now reset initial values & dirty flags + }; + + GridStack.prototype._triggerAddEvent = function() { + if (this.grid._batchMode) { return; } + if (this.grid._addedNodes && this.grid._addedNodes.length > 0) { + this.grid._layoutsNodesChange(this.grid._addedNodes); + // prevent added nodes from also triggering 'change' event (which is called next) + this.grid._addedNodes.forEach(function (n) { delete n._dirty; }); + this.container.trigger('added', [this.grid._addedNodes]); + this.grid._addedNodes = []; + } + }; + + GridStack.prototype._triggerRemoveEvent = function() { + if (this.grid._batchMode) { return; } + if (this.grid._removedNodes && this.grid._removedNodes.length > 0) { + this.container.trigger('removed', [this.grid._removedNodes]); + this.grid._removedNodes = []; + } + }; + + GridStack.prototype._initStyles = function() { + if (this._stylesId) { + Utils.removeStylesheet(this._stylesId); + } + this._stylesId = 'gridstack-style-' + (Math.random() * 100000).toFixed(); + // insert style to parent (instead of 'head') to support WebComponent + this._styles = Utils.createStylesheet(this._stylesId, this.container.get(0).parentNode); + if (this._styles !== null) { + this._styles._max = 0; + } + }; + + GridStack.prototype._updateStyles = function(maxHeight) { + if (this._styles === null || this._styles === undefined) { + return; + } + + var prefix = '.' + this.opts._class + ' .' + this.opts.itemClass; + var self = this; + var getHeight; + + if (maxHeight === undefined) { + maxHeight = this._styles._max; + } + + this._initStyles(); + this._updateContainerHeight(); + if (!this.opts.cellHeight) { // The rest will be handled by CSS + return ; + } + if (this._styles._max !== 0 && maxHeight <= this._styles._max) { // Keep this._styles._max increasing + return ; + } + + if (!this.opts.verticalMargin || this.opts.cellHeightUnit === this.opts.verticalMarginUnit) { + getHeight = function(nbRows, nbMargins) { + return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) + + self.opts.cellHeightUnit; + }; + } else { + getHeight = function(nbRows, nbMargins) { + if (!nbRows || !nbMargins) { + return (self.opts.cellHeight * nbRows + self.opts.verticalMargin * nbMargins) + + self.opts.cellHeightUnit; + } + return 'calc(' + ((self.opts.cellHeight * nbRows) + self.opts.cellHeightUnit) + ' + ' + + ((self.opts.verticalMargin * nbMargins) + self.opts.verticalMarginUnit) + ')'; + }; + } + + if (this._styles._max === 0) { + Utils.insertCSSRule(this._styles, prefix, 'min-height: ' + getHeight(1, 0) + ';', 0); + } + + if (maxHeight > this._styles._max) { + for (var i = this._styles._max; i < maxHeight; ++i) { + Utils.insertCSSRule(this._styles, + prefix + '[data-gs-height="' + (i + 1) + '"]', + 'height: ' + getHeight(i + 1, i) + ';', + i + ); + Utils.insertCSSRule(this._styles, + prefix + '[data-gs-min-height="' + (i + 1) + '"]', + 'min-height: ' + getHeight(i + 1, i) + ';', + i + ); + Utils.insertCSSRule(this._styles, + prefix + '[data-gs-max-height="' + (i + 1) + '"]', + 'max-height: ' + getHeight(i + 1, i) + ';', + i + ); + Utils.insertCSSRule(this._styles, + prefix + '[data-gs-y="' + i + '"]', + 'top: ' + getHeight(i, i) + ';', + i + ); + } + this._styles._max = maxHeight; + } + }; + + GridStack.prototype._updateContainerHeight = function() { + if (this.grid._batchMode) { return; } + var height = this.grid.getGridHeight(); + // check for css min height. Each row is cellHeight + verticalMargin, until last one which has no margin below + var cssMinHeight = parseInt(this.container.css('min-height')); + if (cssMinHeight > 0) { + var verticalMargin = this.opts.verticalMargin; + var minHeight = Math.round((cssMinHeight + verticalMargin) / (this.cellHeight() + verticalMargin)); + if (height < minHeight) { + height = minHeight; + } + } + this.container.attr('data-gs-current-height', height); + if (!this.opts.cellHeight) { + return ; + } + if (!this.opts.verticalMargin) { + this.container.css('height', (height * (this.opts.cellHeight)) + this.opts.cellHeightUnit); + } else if (this.opts.cellHeightUnit === this.opts.verticalMarginUnit) { + this.container.css('height', (height * (this.opts.cellHeight + this.opts.verticalMargin) - + this.opts.verticalMargin) + this.opts.cellHeightUnit); + } else { + this.container.css('height', 'calc(' + ((height * (this.opts.cellHeight)) + this.opts.cellHeightUnit) + + ' + ' + ((height * (this.opts.verticalMargin - 1)) + this.opts.verticalMarginUnit) + ')'); + } + }; + + GridStack.prototype._setupRemovingTimeout = function(el) { + var self = this; + var node = $(el).data('_gridstack_node'); + + if (node._removeTimeout || !self.opts.removable) { + return; + } + node._removeTimeout = setTimeout(function() { + el.addClass('grid-stack-item-removing'); + node._isAboutToRemove = true; + }, self.opts.removeTimeout); + }; + + GridStack.prototype._clearRemovingTimeout = function(el) { + var node = $(el).data('_gridstack_node'); + + if (!node._removeTimeout) { + return; + } + clearTimeout(node._removeTimeout); + node._removeTimeout = null; + el.removeClass('grid-stack-item-removing'); + node._isAboutToRemove = false; + }; + + GridStack.prototype._prepareElementsByNode = function(el, node) { + var self = this; + + var cellWidth; + var cellHeight; + + var dragOrResize = function(event, ui) { + var x = Math.round(ui.position.left / cellWidth); + var y = Math.floor((ui.position.top + cellHeight / 2) / cellHeight); + var width; + var height; + + if (event.type !== 'drag') { + width = Math.round(ui.size.width / cellWidth); + height = Math.round(ui.size.height / cellHeight); + } + + if (event.type === 'drag') { + var distance = ui.position.top - node._prevYPix; + node._prevYPix = ui.position.top; + Utils.updateScrollPosition(el[0], ui, distance); + if (el.data('inTrashZone') || x < 0 || x >= self.grid.column || y < 0 || + (!self.grid.float && y > self.grid.getGridHeight())) { + if (!node._temporaryRemoved) { + if (self.opts.removable === true) { + self._setupRemovingTimeout(el); + } + + x = node._beforeDragX; + y = node._beforeDragY; + + self.placeholder.detach(); + self.placeholder.hide(); + self.grid.removeNode(node); + self._updateContainerHeight(); + + node._temporaryRemoved = true; + } else { + return; + } + } else { + self._clearRemovingTimeout(el); + + if (node._temporaryRemoved) { + self.grid.addNode(node); + self.placeholder + .attr('data-gs-x', x) + .attr('data-gs-y', y) + .attr('data-gs-width', width) + .attr('data-gs-height', height) + .show(); + self.container.append(self.placeholder); + node.el = self.placeholder; + node._temporaryRemoved = false; + } + } + } else if (event.type === 'resize') { + if (x < 0) { + return; + } + } + // width and height are undefined if not resizing + var lastTriedWidth = width !== undefined ? width : node.lastTriedWidth; + var lastTriedHeight = height !== undefined ? height : node.lastTriedHeight; + if (!self.grid.canMoveNode(node, x, y, width, height) || + (node.lastTriedX === x && node.lastTriedY === y && + node.lastTriedWidth === lastTriedWidth && node.lastTriedHeight === lastTriedHeight)) { + return; + } + node.lastTriedX = x; + node.lastTriedY = y; + node.lastTriedWidth = width; + node.lastTriedHeight = height; + self.grid.moveNode(node, x, y, width, height); + self._updateContainerHeight(); + + if (event.type === 'resize') { + $(event.target).trigger('gsresize', node); + } + }; + + var onStartMoving = function(event, ui) { + self.container.append(self.placeholder); + var o = $(this); + self.grid.cleanNodes(); + self.grid.beginUpdate(node); + cellWidth = self.cellWidth(); + var strictCellHeight = self.cellHeight(); + // TODO: cellHeight = cellHeight() causes issue (i.e. remove strictCellHeight above) otherwise + // when sizing up we jump almost right away to next size instead of half way there. Not sure + // why as we don't use ceil() in many places but round() instead. + cellHeight = self.container.height() / parseInt(self.container.attr('data-gs-current-height')); + self.placeholder + .attr('data-gs-x', o.attr('data-gs-x')) + .attr('data-gs-y', o.attr('data-gs-y')) + .attr('data-gs-width', o.attr('data-gs-width')) + .attr('data-gs-height', o.attr('data-gs-height')) + .show(); + node.el = self.placeholder; + node._beforeDragX = node.x; + node._beforeDragY = node.y; + node._prevYPix = ui.position.top; + var minHeight = (node.minHeight || 1); + var verticalMargin = self.opts.verticalMargin; + + // mineHeight - Each row is cellHeight + verticalMargin, until last one which has no margin below + self.dd.resizable(el, 'option', 'minWidth', cellWidth * (node.minWidth || 1)); + self.dd.resizable(el, 'option', 'minHeight', (strictCellHeight * minHeight) + (minHeight - 1) * verticalMargin); + + if (event.type === 'resizestart') { + o.find('.grid-stack-item').trigger('resizestart'); + } + }; + + var onEndMoving = function(event, ui) { + var o = $(this); + if (!o.data('_gridstack_node')) { + return; + } + + // var forceNotify = false; what is the point of calling 'change' event with no data, when the 'removed' event is already called ? + self.placeholder.detach(); + node.el = o; + self.placeholder.hide(); + + if (node._isAboutToRemove) { + // forceNotify = true; + var gridToNotify = el.data('_gridstack_node')._grid; + gridToNotify._triggerRemoveEvent(); + el.removeData('_gridstack_node'); + el.remove(); + } else { + self._clearRemovingTimeout(el); + if (!node._temporaryRemoved) { + Utils.removePositioningStyles(o); + o + .attr('data-gs-x', node.x) + .attr('data-gs-y', node.y) + .attr('data-gs-width', node.width) + .attr('data-gs-height', node.height); + } else { + Utils.removePositioningStyles(o); + o + .attr('data-gs-x', node._beforeDragX) + .attr('data-gs-y', node._beforeDragY) + .attr('data-gs-width', node.width) + .attr('data-gs-height', node.height); + node.x = node._beforeDragX; + node.y = node._beforeDragY; + node._temporaryRemoved = false; + self.grid.addNode(node); + } + } + self._updateContainerHeight(); + self._triggerChangeEvent(/*forceNotify*/); + + self.grid.endUpdate(); + + var nestedGrids = o.find('.grid-stack'); + if (nestedGrids.length && event.type === 'resizestop') { + nestedGrids.each(function(index, el) { + $(el).data('gridstack').onResizeHandler(); + }); + o.find('.grid-stack-item').trigger('resizestop'); + o.find('.grid-stack-item').trigger('gsresizestop'); + } + if (event.type === 'resizestop') { + self.container.trigger('gsresizestop', o); + } + }; + + this.dd + .draggable(el, { + start: onStartMoving, + stop: onEndMoving, + drag: dragOrResize + }) + .resizable(el, { + start: onStartMoving, + stop: onEndMoving, + resize: dragOrResize + }); + + if (node.noMove || this.opts.disableDrag || this.opts.staticGrid) { + this.dd.draggable(el, 'disable'); + } + + if (node.noResize || this.opts.disableResize || this.opts.staticGrid) { + this.dd.resizable(el, 'disable'); + } + + this._writeAttr(el, node); + }; + + GridStack.prototype._prepareElement = function(el, triggerAddEvent) { + triggerAddEvent = triggerAddEvent !== undefined ? triggerAddEvent : false; + var self = this; + el = $(el); + + el.addClass(this.opts.itemClass); + var node = this._readAttr(el, {el: el, _grid: self}); + node = self.grid.addNode(node, triggerAddEvent); + el.data('_gridstack_node', node); + + this._prepareElementsByNode(el, node); + }; + + /** call to write any default attributes back to element */ + GridStack.prototype._writeAttr = function(el, node) { + el = $(el); + node = node || {}; + // Note: passing null removes the attr in jquery + if (node.x !== undefined) { el.attr('data-gs-x', node.x); } + if (node.y !== undefined) { el.attr('data-gs-y', node.y); } + if (node.width !== undefined) { el.attr('data-gs-width', node.width); } + if (node.height !== undefined) { el.attr('data-gs-height', node.height); } + if (node.autoPosition !== undefined) { el.attr('data-gs-auto-position', node.autoPosition ? true : null); } + if (node.minWidth !== undefined) { el.attr('data-gs-min-width', node.minWidth); } + if (node.maxWidth !== undefined) { el.attr('data-gs-max-width', node.maxWidth); } + if (node.minHeight !== undefined) { el.attr('data-gs-min-height', node.minHeight); } + if (node.maxHeight !== undefined) { el.attr('data-gs-max-height', node.maxHeight); } + if (node.noResize !== undefined) { el.attr('data-gs-no-resize', node.noResize ? true : null); } + if (node.noMove !== undefined) { el.attr('data-gs-no-move', node.noMove ? true : null); } + if (node.locked !== undefined) { el.attr('data-gs-locked', node.locked ? true : null); } + if (node.resizeHandles !== undefined) { el.attr('data-gs-resize-handles', node.resizeHandles); } + if (node.id !== undefined) { el.attr('data-gs-id', node.id); } + }; + + /** call to write any default attributes back to element */ + GridStack.prototype._readAttr = function(el, node) { + el = $(el); + node = node || {}; + node.x = el.attr('data-gs-x'); + node.y = el.attr('data-gs-y'); + node.width = el.attr('data-gs-width'); + node.height = el.attr('data-gs-height'); + node.autoPosition = Utils.toBool(el.attr('data-gs-auto-position')); + node.maxWidth = el.attr('data-gs-max-width'); + node.minWidth = el.attr('data-gs-min-width'); + node.maxHeight = el.attr('data-gs-max-height'); + node.minHeight = el.attr('data-gs-min-height'); + node.noResize = Utils.toBool(el.attr('data-gs-no-resize')); + node.noMove = Utils.toBool(el.attr('data-gs-no-move')); + node.locked = Utils.toBool(el.attr('data-gs-locked')); + node.resizeHandles = el.attr('data-gs-resize-handles'); + node.id = el.attr('data-gs-id'); + return node; + }; + + GridStack.prototype.setAnimation = function(enable) { + if (enable) { + this.container.addClass('grid-stack-animate'); + } else { + this.container.removeClass('grid-stack-animate'); + } + }; + + GridStack.prototype.addWidget = function(el, node, y, width, height, autoPosition, minWidth, maxWidth, minHeight, maxHeight, id) { + + // new way of calling with an object - make sure all items have been properly initialized + if (node === undefined || typeof node === 'object') { + // Tempting to initialize the passed in node with default and valid values, but this break knockout demos + // as the actual value are filled in when _prepareElement() calls el.attr('data-gs-xyz) before adding the node. + // node = this.grid._prepareNode(node); + node = node || {}; + } else { + // old legacy way of calling with items spelled out - call us back with single object instead (so we can properly initialized values) + return this.addWidget(el, {x: node, y: y, width: width, height: height, autoPosition: autoPosition, + minWidth: minWidth, maxWidth: maxWidth, minHeight: minHeight, maxHeight: maxHeight, id: id}); + } + + el = $(el); + this._writeAttr(el, node); + this.container.append(el); + return this.makeWidget(el); + }; + + GridStack.prototype.makeWidget = function(el) { + el = $(el); + this._prepareElement(el, true); + this._updateContainerHeight(); + this._triggerAddEvent(); + this._triggerChangeEvent(true); // trigger any other changes + + return el; + }; + + GridStack.prototype.willItFit = function(x, y, width, height, autoPosition) { + var node = {x: x, y: y, width: width, height: height, autoPosition: autoPosition}; + return this.grid.canBePlacedWithRespectToHeight(node); + }; + + GridStack.prototype.removeWidget = function(el, detachNode) { + detachNode = (detachNode === undefined ? true : detachNode); + el = $(el); + var node = el.data('_gridstack_node'); + // For Meteor support: https://github.com/gridstack/gridstack.js/pull/272 + if (!node) { + node = this.grid.getNodeDataByDOMEl(el); + } + + el.removeData('_gridstack_node'); + this.grid.removeNode(node, detachNode); + this._triggerRemoveEvent(); + this._triggerChangeEvent(true); // trigger any other changes + }; + + GridStack.prototype.removeAll = function(detachNode) { + if (detachNode !== false) { + // remove our data structure before list gets emptied and DOM elements stay behind + this.grid.nodes.forEach(function(node) { node.el.removeData('_gridstack_node') }); + } + this.grid.removeAll(detachNode); + this._triggerRemoveEvent(); + }; + + GridStack.prototype.destroy = function(detachGrid) { + $(window).off('resize', this.onResizeHandler); + this.disable(); + if (detachGrid !== undefined && !detachGrid) { + this.removeAll(false); + this.container.removeData('gridstack'); + } else { + this.container.remove(); + } + Utils.removeStylesheet(this._stylesId); + if (this.grid) { + this.grid = null; + } + }; + + GridStack.prototype.resizable = function(el, val) { + var self = this; + el = $(el); + el.each(function(index, el) { + el = $(el); + var node = el.data('_gridstack_node'); + if (!node) { return; } + node.noResize = !(val || false); + if (node.noResize) { + self.dd.resizable(el, 'disable'); + } else { + self.dd.resizable(el, 'enable'); + } + }); + return this; + }; + + GridStack.prototype.movable = function(el, val) { + var self = this; + el = $(el); + el.each(function(index, el) { + el = $(el); + var node = el.data('_gridstack_node'); + if (!node) { return; } + node.noMove = !(val || false); + if (node.noMove) { + self.dd.draggable(el, 'disable'); + el.removeClass('ui-draggable-handle'); + } else { + self.dd.draggable(el, 'enable'); + el.addClass('ui-draggable-handle'); + } + }); + return this; + }; + + GridStack.prototype.enableMove = function(doEnable, includeNewWidgets) { + this.movable(this.container.children('.' + this.opts.itemClass), doEnable); + if (includeNewWidgets) { + this.opts.disableDrag = !doEnable; + } + }; + + GridStack.prototype.enableResize = function(doEnable, includeNewWidgets) { + this.resizable(this.container.children('.' + this.opts.itemClass), doEnable); + if (includeNewWidgets) { + this.opts.disableResize = !doEnable; + } + }; + + GridStack.prototype.disable = function() { + this.movable(this.container.children('.' + this.opts.itemClass), false); + this.resizable(this.container.children('.' + this.opts.itemClass), false); + this.container.trigger('disable'); + }; + + GridStack.prototype.enable = function() { + this.movable(this.container.children('.' + this.opts.itemClass), true); + this.resizable(this.container.children('.' + this.opts.itemClass), true); + this.container.trigger('enable'); + }; + + GridStack.prototype.locked = function(el, val) { + el = $(el); + el.each(function(index, el) { + el = $(el); + var node = el.data('_gridstack_node'); + if (!node) { return; } + node.locked = (val || false); + el.attr('data-gs-locked', node.locked ? 'yes' : null); + }); + return this; + }; + + GridStack.prototype.maxHeight = function(el, val) { + el = $(el); + el.each(function(index, el) { + el = $(el); + var node = el.data('_gridstack_node'); + if (!node) { return; } + if (!isNaN(val)) { + node.maxHeight = (val || false); + el.attr('data-gs-max-height', val); + } + }); + return this; + }; + + GridStack.prototype.minHeight = function(el, val) { + el = $(el); + el.each(function(index, el) { + el = $(el); + var node = el.data('_gridstack_node'); + if (!node) { return; } + if (!isNaN(val)) { + node.minHeight = (val || false); + el.attr('data-gs-min-height', val); + } + }); + return this; + }; + + GridStack.prototype.maxWidth = function(el, val) { + el = $(el); + el.each(function(index, el) { + el = $(el); + var node = el.data('_gridstack_node'); + if (!node) { return; } + if (!isNaN(val)) { + node.maxWidth = (val || false); + el.attr('data-gs-max-width', val); + } + }); + return this; + }; + + GridStack.prototype.minWidth = function(el, val) { + el = $(el); + el.each(function(index, el) { + el = $(el); + var node = el.data('_gridstack_node'); + if (!node) { return; } + if (!isNaN(val)) { + node.minWidth = (val || false); + el.attr('data-gs-min-width', val); + } + }); + return this; + }; + + GridStack.prototype._updateElement = function(el, callback) { + el = $(el).first(); + var node = el.data('_gridstack_node'); + if (!node) { return; } + var self = this; + + self.grid.cleanNodes(); + self.grid.beginUpdate(node); + + callback.call(this, el, node); + + self._updateContainerHeight(); + self._triggerChangeEvent(); + + self.grid.endUpdate(); + }; + + GridStack.prototype.resize = function(el, width, height) { + this._updateElement(el, function(el, node) { + width = (width !== null && width !== undefined) ? width : node.width; + height = (height !== null && height !== undefined) ? height : node.height; + + this.grid.moveNode(node, node.x, node.y, width, height); + }); + }; + + GridStack.prototype.move = function(el, x, y) { + this._updateElement(el, function(el, node) { + x = (x !== null && x !== undefined) ? x : node.x; + y = (y !== null && y !== undefined) ? y : node.y; + + this.grid.moveNode(node, x, y, node.width, node.height); + }); + }; + + GridStack.prototype.update = function(el, x, y, width, height) { + this._updateElement(el, function(el, node) { + x = (x !== null && x !== undefined) ? x : node.x; + y = (y !== null && y !== undefined) ? y : node.y; + width = (width !== null && width !== undefined) ? width : node.width; + height = (height !== null && height !== undefined) ? height : node.height; + + this.grid.moveNode(node, x, y, width, height); + }); + }; + + /** + * relayout grid items to reclaim any empty space + */ + GridStack.prototype.compact = function() { + if (this.grid.nodes.length === 0) { return; } + this.batchUpdate(); + this.grid._sortNodes(); + var nodes = this.grid.nodes; + this.grid.nodes = []; // pretend we have no nodes to conflict layout to start with... + nodes.forEach(function(node) { + if (!node.noMove && !node.locked) { + node.autoPosition = true; + } + this.grid.addNode(node, false); // 'false' for add event trigger... + node._dirty = true; // force attr update + }, this); + this.commit(); + }; + + GridStack.prototype.verticalMargin = function(val, noUpdate) { + if (val === undefined) { + return this.opts.verticalMargin; + } + + var heightData = Utils.parseHeight(val); + + if (this.opts.verticalMarginUnit === heightData.unit && this.opts.maxRow === heightData.height) { + return ; + } + this.opts.verticalMarginUnit = heightData.unit; + this.opts.verticalMargin = heightData.height; + + if (!noUpdate) { + this._updateStyles(); + } + }; + + /** set/get the current cell height value */ + GridStack.prototype.cellHeight = function(val, noUpdate) { + // getter - returns the opts stored height else compute it... + if (val === undefined) { + if (this.opts.cellHeight && this.opts.cellHeight !== 'auto') { + return this.opts.cellHeight; + } + // compute the height taking margin into account (each row has margin other than last one) + var o = this.container.children('.' + this.opts.itemClass).first(); + var height = o.attr('data-gs-height'); + var verticalMargin = this.opts.verticalMargin; + return Math.round((o.outerHeight() - (height - 1) * verticalMargin) / height); + } + + // setter - updates the cellHeight value if they changed + var heightData = Utils.parseHeight(val); + if (this.opts.cellHeightUnit === heightData.unit && this.opts.cellHeight === heightData.height) { + return ; + } + this.opts.cellHeightUnit = heightData.unit; + this.opts.cellHeight = heightData.height; + + if (!noUpdate) { + this._updateStyles(); + } + }; + + GridStack.prototype.cellWidth = function() { + // TODO: take margin into account ($horizontal_padding in .scss) to make cellHeight='auto' square ? (see 810-many-columns.html) + return Math.round(this.container.outerWidth() / this.opts.column); + }; + + GridStack.prototype.getCellFromPixel = function(position, useOffset) { + var containerPos = (useOffset !== undefined && useOffset) ? + this.container.offset() : this.container.position(); + var relativeLeft = position.left - containerPos.left; + var relativeTop = position.top - containerPos.top; + + var columnWidth = Math.floor(this.container.width() / this.opts.column); + var rowHeight = Math.floor(this.container.height() / parseInt(this.container.attr('data-gs-current-height'))); + + return {x: Math.floor(relativeLeft / columnWidth), y: Math.floor(relativeTop / rowHeight)}; + }; + + GridStack.prototype.batchUpdate = function() { + this.grid.batchUpdate(); + }; + + GridStack.prototype.commit = function() { + this.grid.commit(); + this._triggerRemoveEvent(); + this._triggerAddEvent(); + this._triggerChangeEvent(); + }; + + GridStack.prototype.isAreaEmpty = function(x, y, width, height) { + return this.grid.isAreaEmpty(x, y, width, height); + }; + + GridStack.prototype.setStatic = function(staticValue) { + this.opts.staticGrid = (staticValue === true); + this.enableMove(!staticValue); + this.enableResize(!staticValue); + this._setStaticClass(); + }; + + GridStack.prototype._setStaticClass = function() { + var staticClassName = 'grid-stack-static'; + + if (this.opts.staticGrid === true) { + this.container.addClass(staticClassName); + } else { + this.container.removeClass(staticClassName); + } + }; + + /** called whenever a node is added or moved - updates the cached layouts */ + GridStackEngine.prototype._layoutsNodesChange = function(nodes) { + if (!this._layouts || this._ignoreLayoutsNodeChange) return; + // remove smaller layouts - we will re-generate those on the fly... larger ones need to update + this._layouts.forEach(function(layout, column) { + if (!layout || column === this.column) return; + if (column < this.column) { + this._layouts[column] = undefined; + } + else { + // we save the original x,y,w (h isn't cached) to see what actually changed to propagate better. + // Note: we don't need to check against out of bound scaling/moving as that will be done when using those cache values. + nodes.forEach(function(node) { + var n = layout.find(function(l) { return l._id === node._id }); + if (!n) return; // no cache for new nodes. Will use those values. + var ratio = column / this.column; + // Y changed, push down same amount + // TODO: detect doing item 'swaps' will help instead of move (especially in 1 column mode) + if (node.y !== node._origY) { + n.y += (node.y - node._origY); + } + // X changed, scale from new position + if (node.x !== node._origX) { + n.x = Math.round(node.x * ratio); + } + // width changed, scale from new width + if (node.width !== node._origW) { + n.width = Math.round(node.width * ratio); + } + // ...height always carries over from cache + }, this); + } + }, this); + } + + /** + * Called to scale the widget width & position up/down based on the column change. + * Note we store previous layouts (especially original ones) to make it possible to go + * from say 12 -> 1 -> 12 and get back to where we were. + * + * oldColumn: previous number of columns + * column: new column number + * nodes?: different sorted list (ex: DOM order) instead of current list + */ + GridStackEngine.prototype._updateNodeWidths = function(oldColumn, column, nodes) { + if (!this.nodes.length || oldColumn === column) { return; } + + // cache the current layout in case they want to go back (like 12 -> 1 -> 12) as it requires original data + var copy = [this.nodes.length]; + this.nodes.forEach(function(n, i) {copy[i] = {x: n.x, y: n.y, width: n.width, _id: n._id}}); // only thing we change is x,y,w and id to find it back + this._layouts = this._layouts || []; // use array to find larger quick + this._layouts[oldColumn] = copy; + + // if we're going to 1 column and using DOM order rather than default sorting, then generate that layout + if (column === 1 && nodes && nodes.length) { + var top = 0; + nodes.forEach(function(n) { + n.x = 0; + n.width = 1; + n.y = Math.max(n.y, top); + top = n.y + n.height; + }); + } else { + nodes = Utils.sort(this.nodes, -1, oldColumn); // current column reverse sorting so we can insert last to front (limit collision) + } + + // see if we have cached previous layout. + var cacheNodes = this._layouts[column] || []; + // if not AND we are going up in size start with the largest layout as down-scaling is more accurate + var lastIndex = this._layouts.length - 1; + if (cacheNodes.length === 0 && column > oldColumn && column < lastIndex) { + cacheNodes = this._layouts[lastIndex] || []; + if (cacheNodes.length) { + // pretend we came from that larger column by assigning those values as starting point + oldColumn = lastIndex; + cacheNodes.forEach(function(cacheNode) { + var j = nodes.findIndex(function(n) {return n && n._id === cacheNode._id}); + if (j !== -1) { + // still current, use cache info positions + nodes[j].x = cacheNode.x; + nodes[j].y = cacheNode.y; + nodes[j].width = cacheNode.width; + } + }); + cacheNodes = []; // we still don't have new column cached data... will generate from larger one. + } + } + + // if we found cache re-use those nodes that are still current + var newNodes = []; + cacheNodes.forEach(function(cacheNode) { + var j = nodes.findIndex(function(n) {return n && n._id === cacheNode._id}); + if (j !== -1) { + // still current, use cache info positions + nodes[j].x = cacheNode.x; + nodes[j].y = cacheNode.y; + nodes[j].width = cacheNode.width; + newNodes.push(nodes[j]); + nodes[j] = null; // erase it so we know what's left + } + }); + // ...and add any extra non-cached ones + var ratio = column / oldColumn; + nodes.forEach(function(node) { + if (!node) return; + node.x = (column === 1 ? 0 : Math.round(node.x * ratio)); + node.width = ((column === 1 || oldColumn === 1) ? 1 : (Math.round(node.width * ratio) || 1)); + newNodes.push(node); + }); + + // finally relayout them in reverse order (to get correct placement) + newNodes = Utils.sort(newNodes, -1, column); + this._ignoreLayoutsNodeChange = true; + this.batchUpdate(); + this.nodes = []; // pretend we have no nodes to start with (we use same structures) to simplify layout + newNodes.forEach(function(node) { + this.addNode(node, false); // 'false' for add event trigger + node._dirty = true; // force attr update + }, this); + this.commit(); + delete this._ignoreLayoutsNodeChange; + } + + /** called to save initial position/size */ + GridStackEngine.prototype._saveInitial = function() { + this.nodes.forEach(function(n) { + n._origX = n.x; + n._origY = n.y; + n._origW = n.width; + n._origH = n.height; + delete n._dirty; + }); + } + + /** + * Modify number of columns in the grid. Will attempt to update existing widgets + * to conform to new number of columns. Requires `gridstack-extra.css` or `gridstack-extra.min.css` for [1-11], + * else you will need to generate correct CSS (see https://github.com/gridstack/gridstack.js#change-grid-columns) + * @param column - Integer > 0 (default 12). + * @param doNotPropagate if true existing widgets will not be updated (optional) + */ + GridStack.prototype.setColumn = function(column, doNotPropagate) { + if (this.opts.column === column) { return; } + var oldColumn = this.opts.column; + + // if we go into 1 column mode (which happens if we're sized less than minWidth unless disableOneColumnMode is on) + // then remember the original columns so we can restore. + if (column === 1) { + this._prevColumn = oldColumn; + } else { + delete this._prevColumn; + } + + this.container.removeClass('grid-stack-' + oldColumn); + this.container.addClass('grid-stack-' + column); + this.opts.column = this.grid.column = column; + + if (doNotPropagate === true) { return; } + + // update the items now - see if the dom order nodes should be passed instead (else default to current list) + var domNodes; + if (this.opts.oneColumnModeDomSort && column === 1) { + domNodes = []; + this.container.children('.' + this.opts.itemClass).each(function(index, el) { + var node = $(el).data('_gridstack_node'); + if (node) { domNodes.push(node); } + }); + if (!domNodes.length) { domNodes = undefined; } + } + this.grid._updateNodeWidths(oldColumn, column, domNodes); + + // and trigger our event last... + this.grid._ignoreLayoutsNodeChange = true; + this._triggerChangeEvent(); + delete this.grid._ignoreLayoutsNodeChange; + }; + + GridStack.prototype.float = function(val) { + // getter - returns the opts stored mode + if (val === undefined) { + return this.opts.float || false; + } + // setter - updates the mode and relayout if gravity is back on + if (this.opts.float === val) { return; } + this.opts.float = this.grid.float = val || false; + if (!val) { + this.grid._packNodes(); + this.grid._notify(); + this._triggerChangeEvent(); + } + }; + + // legacy method renames + GridStack.prototype.setGridWidth = obsolete(GridStack.prototype.setColumn, + 'setGridWidth', 'setColumn', 'v0.5.3'); + + scope.GridStackUI = GridStack; + + scope.GridStackUI.Utils = Utils; + scope.GridStackUI.Engine = GridStackEngine; + scope.GridStackUI.GridStackDragDropPlugin = GridStackDragDropPlugin; + + $.fn.gridstack = function(opts) { + return this.each(function() { + var o = $(this); + if (!o.data('gridstack')) { + o + .data('gridstack', new GridStack(this, opts)); + } + }); + }; + + return scope.GridStackUI; +}); diff --git a/software/flow/node_modules/gridstack/dist/gridstack.min.css b/software/flow/node_modules/gridstack/dist/gridstack.min.css new file mode 100644 index 0000000..b874768 --- /dev/null +++ b/software/flow/node_modules/gridstack/dist/gridstack.min.css @@ -0,0 +1,6 @@ +/*! + * required gridstack 0.6.4 CSS for default 12 and 1 columnMode size. Use gridstack-extra.css for others + * https://gridstackjs.com/ + * (c) 2014-2020 Alain Dumesny, Dylan Weiss, Pavel Reznikov + * gridstack.js may be freely distributed under the MIT license. +*/:root .grid-stack-item>.ui-resizable-handle{filter:none}.grid-stack{position:relative}.grid-stack.grid-stack-rtl{direction:ltr}.grid-stack.grid-stack-rtl>.grid-stack-item{direction:rtl}.grid-stack .grid-stack-placeholder>.placeholder-content{border:1px dashed #d3d3d3;margin:0;position:absolute;top:0;left:10px;right:10px;bottom:0;width:auto;z-index:0!important;text-align:center}.grid-stack>.grid-stack-item{min-width:8.3333333333%;position:absolute;padding:0}.grid-stack>.grid-stack-item>.grid-stack-item-content{margin:0;position:absolute;top:0;left:10px;right:10px;bottom:0;width:auto;overflow-x:hidden;overflow-y:auto}.grid-stack>.grid-stack-item>.ui-resizable-handle{position:absolute;font-size:.1px;display:block;-ms-touch-action:none;touch-action:none}.grid-stack>.grid-stack-item.ui-resizable-autohide>.ui-resizable-handle,.grid-stack>.grid-stack-item.ui-resizable-disabled>.ui-resizable-handle{display:none}.grid-stack>.grid-stack-item.ui-draggable-dragging,.grid-stack>.grid-stack-item.ui-resizable-resizing{z-index:100}.grid-stack>.grid-stack-item.ui-draggable-dragging>.grid-stack-item-content,.grid-stack>.grid-stack-item.ui-resizable-resizing>.grid-stack-item-content{box-shadow:1px 4px 6px rgba(0,0,0,.2);opacity:.8}.grid-stack>.grid-stack-item>.ui-resizable-se,.grid-stack>.grid-stack-item>.ui-resizable-sw{background-image:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0i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MTksMy42MTcsNy45MDEsNS40MjYsMTIuODUsNS40MjYgICBoMzYuNTQ1djI5Mi4zNThoLTM2LjU0MmMtNC45NTIsMC05LjIzNSwxLjgwOC0xMi44NSw1LjQyMWMtMy42MTcsMy42MjEtNS40MjQsNy45MDUtNS40MjQsMTIuODU0ICAgYzAsNC45NDUsMS44MDcsOS4yMjcsNS40MjQsMTIuODQ3bDczLjA4OSw3My4wODhjMy42MTcsMy42MTcsNy44OTgsNS40MjQsMTIuODQ3LDUuNDI0YzQuOTUsMCw5LjIzNC0xLjgwNywxMi44NDktNS40MjQgICBsNzMuMDg3LTczLjA4OGMzLjYxMy0zLjYyLDUuNDIxLTcuOTAxLDUuNDIxLTEyLjg0N2MwLTQuOTQ4LTEuODA4LTkuMjMyLTUuNDIxLTEyLjg1NCAgIEMzMzguMTQyLDQwMy44MDIsMzMzLjg1Nyw0MDEuOTk0LDMyOC45MDYsNDAxLjk5NHoiIGZpbGw9IiM2NjY2NjYiLz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8Zz4KPC9nPgo8L3N2Zz4K);background-repeat:no-repeat;background-position:center;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);-o-transform:rotate(45deg);transform:rotate(45deg)}.grid-stack>.grid-stack-item>.ui-resizable-se{-webkit-transform:rotate(-45deg);-moz-transform:rotate(-45deg);-ms-transform:rotate(-45deg);-o-transform:rotate(-45deg);transform:rotate(-45deg)}.grid-stack>.grid-stack-item>.ui-resizable-nw{cursor:nw-resize;width:20px;height:20px;left:10px;top:0}.grid-stack>.grid-stack-item>.ui-resizable-n{cursor:n-resize;height:10px;top:0;left:25px;right:25px}.grid-stack>.grid-stack-item>.ui-resizable-ne{cursor:ne-resize;width:20px;height:20px;right:10px;top:0}.grid-stack>.grid-stack-item>.ui-resizable-e{cursor:e-resize;width:10px;right:10px;top:15px;bottom:15px}.grid-stack>.grid-stack-item>.ui-resizable-se{cursor:se-resize;width:20px;height:20px;right:10px;bottom:0}.grid-stack>.grid-stack-item>.ui-resizable-s{cursor:s-resize;height:10px;left:25px;bottom:0;right:25px}.grid-stack>.grid-stack-item>.ui-resizable-sw{cursor:sw-resize;width:20px;height:20px;left:10px;bottom:0}.grid-stack>.grid-stack-item>.ui-resizable-w{cursor:w-resize;width:10px;left:10px;top:15px;bottom:15px}.grid-stack>.grid-stack-item.ui-draggable-dragging>.ui-resizable-handle{display:none!important}.grid-stack>.grid-stack-item[data-gs-width='1']{width:8.3333333333%}.grid-stack>.grid-stack-item[data-gs-x='1']{left:8.3333333333%}.grid-stack>.grid-stack-item[data-gs-min-width='1']{min-width:8.3333333333%}.grid-stack>.grid-stack-item[data-gs-max-width='1']{max-width:8.3333333333%}.grid-stack>.grid-stack-item[data-gs-width='2']{width:16.6666666667%}.grid-stack>.grid-stack-item[data-gs-x='2']{left:16.6666666667%}.grid-stack>.grid-stack-item[data-gs-min-width='2']{min-width:16.6666666667%}.grid-stack>.grid-stack-item[data-gs-max-width='2']{max-width:16.6666666667%}.grid-stack>.grid-stack-item[data-gs-width='3']{width:25%}.grid-stack>.grid-stack-item[data-gs-x='3']{left:25%}.grid-stack>.grid-stack-item[data-gs-min-width='3']{min-width:25%}.grid-stack>.grid-stack-item[data-gs-max-width='3']{max-width:25%}.grid-stack>.grid-stack-item[data-gs-width='4']{width:33.3333333333%}.grid-stack>.grid-stack-item[data-gs-x='4']{left:33.3333333333%}.grid-stack>.grid-stack-item[data-gs-min-width='4']{min-width:33.3333333333%}.grid-stack>.grid-stack-item[data-gs-max-width='4']{max-width:33.3333333333%}.grid-stack>.grid-stack-item[data-gs-width='5']{width:41.6666666667%}.grid-stack>.grid-stack-item[data-gs-x='5']{left:41.6666666667%}.grid-stack>.grid-stack-item[data-gs-min-width='5']{min-width:41.6666666667%}.grid-stack>.grid-stack-item[data-gs-max-width='5']{max-width:41.6666666667%}.grid-stack>.grid-stack-item[data-gs-width='6']{width:50%}.grid-stack>.grid-stack-item[data-gs-x='6']{left:50%}.grid-stack>.grid-stack-item[data-gs-min-width='6']{min-width:50%}.grid-stack>.grid-stack-item[data-gs-max-width='6']{max-width:50%}.grid-stack>.grid-stack-item[data-gs-width='7']{width:58.3333333333%}.grid-stack>.grid-stack-item[data-gs-x='7']{left:58.3333333333%}.grid-stack>.grid-stack-item[data-gs-min-width='7']{min-width:58.3333333333%}.grid-stack>.grid-stack-item[data-gs-max-width='7']{max-width:58.3333333333%}.grid-stack>.grid-stack-item[data-gs-width='8']{width:66.6666666667%}.grid-stack>.grid-stack-item[data-gs-x='8']{left:66.6666666667%}.grid-stack>.grid-stack-item[data-gs-min-width='8']{min-width:66.6666666667%}.grid-stack>.grid-stack-item[data-gs-max-width='8']{max-width:66.6666666667%}.grid-stack>.grid-stack-item[data-gs-width='9']{width:75%}.grid-stack>.grid-stack-item[data-gs-x='9']{left:75%}.grid-stack>.grid-stack-item[data-gs-min-width='9']{min-width:75%}.grid-stack>.grid-stack-item[data-gs-max-width='9']{max-width:75%}.grid-stack>.grid-stack-item[data-gs-width='10']{width:83.3333333333%}.grid-stack>.grid-stack-item[data-gs-x='10']{left:83.3333333333%}.grid-stack>.grid-stack-item[data-gs-min-width='10']{min-width:83.3333333333%}.grid-stack>.grid-stack-item[data-gs-max-width='10']{max-width:83.3333333333%}.grid-stack>.grid-stack-item[data-gs-width='11']{width:91.6666666667%}.grid-stack>.grid-stack-item[data-gs-x='11']{left:91.6666666667%}.grid-stack>.grid-stack-item[data-gs-min-width='11']{min-width:91.6666666667%}.grid-stack>.grid-stack-item[data-gs-max-width='11']{max-width:91.6666666667%}.grid-stack>.grid-stack-item[data-gs-width='12']{width:100%}.grid-stack>.grid-stack-item[data-gs-x='12']{left:100%}.grid-stack>.grid-stack-item[data-gs-min-width='12']{min-width:100%}.grid-stack>.grid-stack-item[data-gs-max-width='12']{max-width:100%}.grid-stack.grid-stack-1>.grid-stack-item{min-width:100%}.grid-stack.grid-stack-1>.grid-stack-item[data-gs-width='1']{width:100%}.grid-stack.grid-stack-1>.grid-stack-item[data-gs-x='1']{left:100%}.grid-stack.grid-stack-1>.grid-stack-item[data-gs-min-width='1']{min-width:100%}.grid-stack.grid-stack-1>.grid-stack-item[data-gs-max-width='1']{max-width:100%}.grid-stack.grid-stack-animate,.grid-stack.grid-stack-animate .grid-stack-item{-webkit-transition:left .3s,top .3s,height .3s,width .3s;-moz-transition:left .3s,top .3s,height .3s,width .3s;-ms-transition:left .3s,top .3s,height .3s,width .3s;-o-transition:left .3s,top .3s,height .3s,width .3s;transition:left .3s,top .3s,height .3s,width .3s}.grid-stack.grid-stack-animate .grid-stack-item.grid-stack-placeholder,.grid-stack.grid-stack-animate .grid-stack-item.ui-draggable-dragging,.grid-stack.grid-stack-animate .grid-stack-item.ui-resizable-resizing{-webkit-transition:left 0s,top 0s,height 0s,width 0s;-moz-transition:left 0s,top 0s,height 0s,width 0s;-ms-transition:left 0s,top 0s,height 0s,width 0s;-o-transition:left 0s,top 0s,height 0s,width 0s;transition:left 0s,top 0s,height 0s,width 0s} \ No newline at end of file diff --git a/software/flow/node_modules/gridstack/dist/gridstack.min.js b/software/flow/node_modules/gridstack/dist/gridstack.min.js new file mode 100644 index 0000000..af781f3 --- /dev/null +++ b/software/flow/node_modules/gridstack/dist/gridstack.min.js @@ -0,0 +1,9 @@ +/** + * gridstack.js 0.6.4 + * https://gridstackjs.com/ + * (c) 2014-2020 Alain Dumesny, Dylan Weiss, Pavel Reznikov + * gridstack.js may be freely distributed under the MIT license. + * @preserve +*/ +!function(t){if("function"==typeof define&&define.amd)define(["jquery","exports"],t);else if("undefined"!=typeof exports){var e;try{e=require("jquery")}catch(t){}t(e||window.jQuery,exports)}else t(window.jQuery,window)}(function(m,t){function n(t,e,i,o){void 0!==t[e]&&(t[i]=t[e],console.warn("gridstack.js: Option `"+e+"` is deprecated in "+o+" and has been replaced with `"+i+"`. It will be **completely** removed in v1.0"))}function d(t,e,i,o){var a=t.attr(e);void 0!==a&&(t.attr(i,a),console.warn("gridstack.js: attribute `"+e+"`="+a+" is deprecated on this object in "+o+" and has been replaced with `"+i+"`. It will be **completely** removed in v1.0"))}var f={isIntercepted:function(t,e){return!(t.x+t.width<=e.x||e.x+e.width<=t.x||t.y+t.height<=e.y||e.y+e.height<=t.y)},sort:function(t,e,i){if(!i){var o=t.map(function(t){return t.x+t.width});i=Math.max.apply(Math,o)}return-1===e?f.sortBy(t,function(t){return-(t.x+t.y*i)}):f.sortBy(t,function(t){return t.x+t.y*i})},createStylesheet:function(t,e){var i=document.createElement("style");return i.setAttribute("type","text/css"),i.setAttribute("data-gs-style-id",t),i.styleSheet?i.styleSheet.cssText="":i.appendChild(document.createTextNode("")),(e=e||document.getElementsByTagName("head")[0]).insertBefore(i,e.firstChild),i.sheet},removeStylesheet:function(t){m("STYLE[data-gs-style-id="+t+"]").remove()},insertCSSRule:function(t,e,i,o){"function"==typeof t.insertRule?t.insertRule(e+"{"+i+"}",o):"function"==typeof t.addRule&&t.addRule(e,i,o)},toBool:function(t){return"boolean"==typeof t?t:"string"==typeof t?!(""===(t=t.toLowerCase())||"no"===t||"false"===t||"0"===t):Boolean(t)},_collisionNodeCheck:function(t){return t!==this.node&&f.isIntercepted(t,this.nn)},_didCollide:function(t){return f.isIntercepted({x:this.n.x,y:this.newY,width:this.n.width,height:this.n.height},t)},_isAddNodeIntercepted:function(t){return f.isIntercepted({x:this.x,y:this.y,width:this.node.width,height:this.node.height},t)},parseHeight:function(t){var e=t,i="px";if(e&&"string"==typeof e){var o=e.match(/^(-[0-9]+\.[0-9]+|[0-9]*\.[0-9]+|-[0-9]+|[0-9]+)(px|em|rem|vh|vw|%)?$/);if(!o)throw new Error("Invalid height");i=o[2]||"px",e=parseFloat(o[1])}return{height:e,unit:i}},without:function(t,e){var i=t.indexOf(e);return-1!==i&&(t=t.slice(0)).splice(i,1),t},sortBy:function(t,a){return t.slice(0).sort(function(t,e){var i=a(t),o=a(e);return o===i?0:ot.clientHeight?t:f.getScrollParent(t.parentNode)},updateScrollPosition:function(t,e,i){var o=t.getBoundingClientRect(),a=window.innerHeight||document.documentElement.clientHeight;if(o.top<0||o.bottom>a){var s=o.bottom-a,r=o.top,n=f.getScrollParent(t);if(null!==n){var d=n.scrollTop;o.top<0&&i<0?t.offsetHeight>a?n.scrollTop+=i:n.scrollTop+=Math.abs(r)>Math.abs(i)?i:r:0a?n.scrollTop+=i:n.scrollTop+=i=t._packY;){this.nodes.slice(0,e).find(f._didCollide,{n:t,newY:i})||(t._dirty=!0,t.y=i),--i}},this):this.nodes.forEach(function(t,e){if(!t.locked)for(;0this.column?t.width=this.column:t.width<1&&(t.width=1),t.height<1&&(t.height=1),t.x<0&&(t.x=0),t.x+t.width>this.column&&(e?t.width=this.column-t.x:t.x=this.column-t.width),t.y<0&&(t.y=0),t},l.prototype._notify=function(){if(!this._batchMode){var t=Array.prototype.slice.call(arguments,0);t[0]=void 0===t[0]?[]:Array.isArray(t[0])?t[0]:[t[0]],t[1]=void 0===t[1]||t[1];var e=t[0].concat(this.getDirtyNodes());this.onchange(e,t[1])}},l.prototype.cleanNodes=function(){this._batchMode||this.nodes.forEach(function(t){delete t._dirty})},l.prototype.getDirtyNodes=function(t){if(t){var e=[];return this.nodes.forEach(function(t){t._dirty&&(t.y===t._origY&&t.x===t._origX&&t.width===t._origW&&t.height===t._origH?delete t._dirty:e.push(t))}),e}return this.nodes.filter(function(t){return t._dirty})},l.prototype.addNode=function(t,e){if(void 0!==(t=this._prepareNode(t)).maxWidth&&(t.width=Math.min(t.width,t.maxWidth)),void 0!==t.maxHeight&&(t.height=Math.min(t.height,t.maxHeight)),void 0!==t.minWidth&&(t.width=Math.max(t.width,t.minWidth)),void 0!==t.minHeight&&(t.height=Math.max(t.height,t.minHeight)),t._id=t._id||++s,t.autoPosition){this._sortNodes();for(var i=0;;++i){var o=i%this.column,a=Math.floor(i/this.column);if(!(o+t.width>this.column)&&!this.nodes.find(f._isAddNodeIntercepted,{x:o,y:a,node:t})){t.x=o,t.y=a,delete t.autoPosition;break}}}return this.nodes.push(t),e&&this._addedNodes.push(t),this._fixCollisions(t),this._packNodes(),this._notify(),t},l.prototype.removeNode=function(t,e){e=void 0===e||e,this._removedNodes.push(t),t._id=null,this.nodes=f.without(this.nodes,t),this._packNodes(),this._notify(t,e)},l.prototype.removeAll=function(t){delete this._layouts,0!==this.nodes.length&&(t=void 0===t||t,this.nodes.forEach(function(t){t._id=null}),this._removedNodes=this.nodes,this.nodes=[],this._notify(this._removedNodes,t))},l.prototype.canMoveNode=function(e,t,i,o,a){if(!this.isNodeChangedPosition(e,t,i,o,a))return!1;var s,r=Boolean(this.nodes.find(function(t){return t.locked}));if(!this.maxRow&&!r)return!0;var n=new l(this.column,null,this.float,0,this.nodes.map(function(t){return t===e?s=m.extend({},t):m.extend({},t)}));if(!s)return!0;n.moveNode(s,t,i,o,a);var d=!0;return r&&(d&=!Boolean(n.nodes.find(function(t){return t!==s&&Boolean(t.locked)&&Boolean(t._dirty)}))),this.maxRow&&(d&=n.getGridHeight()<=this.maxRow),d},l.prototype.canBePlacedWithRespectToHeight=function(t){if(!this.maxRow)return!0;var e=new l(this.column,null,this.float,0,this.nodes.map(function(t){return m.extend({},t)}));return e.addNode(t),e.getGridHeight()<=this.maxRow},l.prototype.isNodeChangedPosition=function(t,e,i,o,a){return"number"!=typeof e&&(e=t.x),"number"!=typeof i&&(i=t.y),"number"!=typeof o&&(o=t.width),"number"!=typeof a&&(a=t.height),void 0!==t.maxWidth&&(o=Math.min(o,t.maxWidth)),void 0!==t.maxHeight&&(a=Math.min(a,t.maxHeight)),void 0!==t.minWidth&&(o=Math.max(o,t.minWidth)),void 0!==t.minHeight&&(a=Math.max(a,t.minHeight)),t.x!==e||t.y!==i||t.width!==o||t.height!==a},l.prototype.moveNode=function(t,e,i,o,a,s){if("number"!=typeof e&&(e=t.x),"number"!=typeof i&&(i=t.y),"number"!=typeof o&&(o=t.width),"number"!=typeof a&&(a=t.height),void 0!==t.maxWidth&&(o=Math.min(o,t.maxWidth)),void 0!==t.maxHeight&&(a=Math.min(a,t.maxHeight)),void 0!==t.minWidth&&(o=Math.max(o,t.minWidth)),void 0!==t.minHeight&&(a=Math.max(a,t.minHeight)),t.x===e&&t.y===i&&t.width===o&&t.height===a)return t;var r=t.width!==o;return t._dirty=!0,t.x=e,t.y=i,t.width=o,t.height=a,t.lastTriedX=e,t.lastTriedY=i,t.lastTriedWidth=o,t.lastTriedHeight=a,t=this._prepareNode(t,r),this._fixCollisions(t),s||(this._packNodes(),this._notify()),t},l.prototype.getGridHeight=function(){return this.nodes.reduce(function(t,e){return Math.max(t,e.y+e.height)},0)},l.prototype.beginUpdate=function(t){t._updating||(t._updating=!0,this.nodes.forEach(function(t){t._packY=t.y}))},l.prototype.endUpdate=function(){var t=this.nodes.find(function(t){return t._updating});t&&(t._updating=!1,this.nodes.forEach(function(t){delete t._packY}))};function i(t,e){var i,c=this;e=e||{},this.container=m(t),n(e,"width","column","v0.5.3"),n(e,"height","maxRow","v0.5.3"),function(t,e,i,o){void 0!==t[e]&&console.warn("gridstack.js: Option `"+e+"` is deprecated in "+i+o)}(e,"oneColumnModeClass","v0.6.3",". Use class `.grid-stack-1` instead"),d(this.container,"data-gs-width","data-gs-column","v0.5.3"),d(this.container,"data-gs-height","data-gs-max-row","v0.5.3"),e.itemClass=e.itemClass||"grid-stack-item";var o=0
'+this.opts.placeholderText+"
").hide(),this._updateContainerHeight(),this._updateHeightsOnResize=f.throttle(function(){c.cellHeight(c.cellWidth(),!1)},100),this.onResizeHandler=function(){if(i&&c._updateHeightsOnResize(),!c.opts.staticGrid)if(!c.opts.disableOneColumnMode&&(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)<=c.opts.minWidth){if(c.oneColumnMode)return;c.oneColumnMode=!0,c.setColumn(1)}else{if(!c.oneColumnMode)return;c.oneColumnMode=!1,c.setColumn(c._prevColumn)}},m(window).resize(this.onResizeHandler),this.onResizeHandler(),!c.opts.staticGrid&&"string"==typeof c.opts.removable){var r=m(c.opts.removable);this.dd.isDroppable(r)||this.dd.droppable(r,c.opts.removableOptions),this.dd.on(r,"dropover",function(t,e){var i=m(e.draggable),o=i.data("_gridstack_node");o&&o._grid===c&&(i.data("inTrashZone",!0),c._setupRemovingTimeout(i))}).on(r,"dropout",function(t,e){var i=m(e.draggable),o=i.data("_gridstack_node");o&&o._grid===c&&(i.data("inTrashZone",!1),c._clearRemovingTimeout(i))})}if(!c.opts.staticGrid&&c.opts.acceptWidgets){function p(t,e){var i=u,o=i.data("_gridstack_node"),a=c.getCellFromPixel({left:t.pageX,top:t.pageY},!0),s=Math.max(0,a.x),r=Math.max(0,a.y);o._added||(o._added=!0,o.el=i,o.autoPosition=!0,o.x=s,o.y=r,c.grid.cleanNodes(),c.grid.beginUpdate(o),c.grid.addNode(o),c.container.append(c.placeholder),c.placeholder.attr("data-gs-x",o.x).attr("data-gs-y",o.y).attr("data-gs-width",o.width).attr("data-gs-height",o.height).show(),o.el=c.placeholder,o._beforeDragX=o.x,o._beforeDragY=o.y,c._updateContainerHeight()),c.grid.canMoveNode(o,s,r)&&(c.grid.moveNode(o,s,r),c._updateContainerHeight())}var u=null;this.dd.droppable(c.container,{accept:function(t){var e=(t=m(t)).data("_gridstack_node");return(!e||e._grid!==c)&&t.is(!0===c.opts.acceptWidgets?".grid-stack-item":c.opts.acceptWidgets)}}).on(c.container,"dropover",function(t,e){var i,o,a=m(e.draggable),s=a.data("_gridstack_node");if(!s||!s.width||!s.height){var r=parseInt(a.attr("data-gs-width"));0this._styles._max)){for(var a=this._styles._max;a=p.grid.column||s<0||!p.grid.float&&s>p.grid.getGridHeight()){if(l._temporaryRemoved)return;!0===p.opts.removable&&p._setupRemovingTimeout(h),a=l._beforeDragX,s=l._beforeDragY,p.placeholder.detach(),p.placeholder.hide(),p.grid.removeNode(l),p._updateContainerHeight(),l._temporaryRemoved=!0}else p._clearRemovingTimeout(h),l._temporaryRemoved&&(p.grid.addNode(l),p.placeholder.attr("data-gs-x",a).attr("data-gs-y",s).attr("data-gs-width",i).attr("data-gs-height",o).show(),p.container.append(p.placeholder),l.el=p.placeholder,l._temporaryRemoved=!1)}else if("resize"===t.type&&a<0)return;var n=void 0!==i?i:l.lastTriedWidth,d=void 0!==o?o:l.lastTriedHeight;!p.grid.canMoveNode(l,a,s,i,o)||l.lastTriedX===a&&l.lastTriedY===s&&l.lastTriedWidth===n&&l.lastTriedHeight===d||(l.lastTriedX=a,l.lastTriedY=s,l.lastTriedWidth=i,l.lastTriedHeight=o,p.grid.moveNode(l,a,s,i,o),p._updateContainerHeight(),"resize"===t.type&&m(t.target).trigger("gsresize",l))}function e(t,e){p.container.append(p.placeholder);var i=m(this);p.grid.cleanNodes(),p.grid.beginUpdate(l),g=p.cellWidth();var o=p.cellHeight();c=p.container.height()/parseInt(p.container.attr("data-gs-current-height")),p.placeholder.attr("data-gs-x",i.attr("data-gs-x")).attr("data-gs-y",i.attr("data-gs-y")).attr("data-gs-width",i.attr("data-gs-width")).attr("data-gs-height",i.attr("data-gs-height")).show(),l.el=p.placeholder,l._beforeDragX=l.x,l._beforeDragY=l.y,l._prevYPix=e.position.top;var a=l.minHeight||1,s=p.opts.verticalMargin;p.dd.resizable(h,"option","minWidth",g*(l.minWidth||1)),p.dd.resizable(h,"option","minHeight",o*a+(a-1)*s),"resizestart"===t.type&&i.find(".grid-stack-item").trigger("resizestart")}function i(t,e){var i=m(this);if(i.data("_gridstack_node")){if(p.placeholder.detach(),l.el=i,p.placeholder.hide(),l._isAboutToRemove)h.data("_gridstack_node")._grid._triggerRemoveEvent(),h.removeData("_gridstack_node"),h.remove();else p._clearRemovingTimeout(h),l._temporaryRemoved?(f.removePositioningStyles(i),i.attr("data-gs-x",l._beforeDragX).attr("data-gs-y",l._beforeDragY).attr("data-gs-width",l.width).attr("data-gs-height",l.height),l.x=l._beforeDragX,l.y=l._beforeDragY,l._temporaryRemoved=!1,p.grid.addNode(l)):(f.removePositioningStyles(i),i.attr("data-gs-x",l.x).attr("data-gs-y",l.y).attr("data-gs-width",l.width).attr("data-gs-height",l.height));p._updateContainerHeight(),p._triggerChangeEvent(),p.grid.endUpdate();var o=i.find(".grid-stack");o.length&&"resizestop"===t.type&&(o.each(function(t,e){m(e).data("gridstack").onResizeHandler()}),i.find(".grid-stack-item").trigger("resizestop"),i.find(".grid-stack-item").trigger("gsresizestop")),"resizestop"===t.type&&p.container.trigger("gsresizestop",i)}}var g,c,p=this;this.dd.draggable(h,{start:e,stop:i,drag:t}).resizable(h,{start:e,stop:i,resize:t}),(l.noMove||this.opts.disableDrag||this.opts.staticGrid)&&this.dd.draggable(h,"disable"),(l.noResize||this.opts.disableResize||this.opts.staticGrid)&&this.dd.resizable(h,"disable"),this._writeAttr(h,l)},i.prototype._prepareElement=function(t,e){e=void 0!==e&&e;(t=m(t)).addClass(this.opts.itemClass);var i=this._readAttr(t,{el:t,_grid:this});i=this.grid.addNode(i,e),t.data("_gridstack_node",i),this._prepareElementsByNode(t,i)},i.prototype._writeAttr=function(t,e){t=m(t),void 0!==(e=e||{}).x&&t.attr("data-gs-x",e.x),void 0!==e.y&&t.attr("data-gs-y",e.y),void 0!==e.width&&t.attr("data-gs-width",e.width),void 0!==e.height&&t.attr("data-gs-height",e.height),void 0!==e.autoPosition&&t.attr("data-gs-auto-position",!!e.autoPosition||null),void 0!==e.minWidth&&t.attr("data-gs-min-width",e.minWidth),void 0!==e.maxWidth&&t.attr("data-gs-max-width",e.maxWidth),void 0!==e.minHeight&&t.attr("data-gs-min-height",e.minHeight),void 0!==e.maxHeight&&t.attr("data-gs-max-height",e.maxHeight),void 0!==e.noResize&&t.attr("data-gs-no-resize",!!e.noResize||null),void 0!==e.noMove&&t.attr("data-gs-no-move",!!e.noMove||null),void 0!==e.locked&&t.attr("data-gs-locked",!!e.locked||null),void 0!==e.resizeHandles&&t.attr("data-gs-resize-handles",e.resizeHandles),void 0!==e.id&&t.attr("data-gs-id",e.id)},i.prototype._readAttr=function(t,e){return t=m(t),(e=e||{}).x=t.attr("data-gs-x"),e.y=t.attr("data-gs-y"),e.width=t.attr("data-gs-width"),e.height=t.attr("data-gs-height"),e.autoPosition=f.toBool(t.attr("data-gs-auto-position")),e.maxWidth=t.attr("data-gs-max-width"),e.minWidth=t.attr("data-gs-min-width"),e.maxHeight=t.attr("data-gs-max-height"),e.minHeight=t.attr("data-gs-min-height"),e.noResize=f.toBool(t.attr("data-gs-no-resize")),e.noMove=f.toBool(t.attr("data-gs-no-move")),e.locked=f.toBool(t.attr("data-gs-locked")),e.resizeHandles=t.attr("data-gs-resize-handles"),e.id=t.attr("data-gs-id"),e},i.prototype.setAnimation=function(t){t?this.container.addClass("grid-stack-animate"):this.container.removeClass("grid-stack-animate")},i.prototype.addWidget=function(t,e,i,o,a,s,r,n,d,h,l){return void 0!==e&&"object"!=typeof e?this.addWidget(t,{x:e,y:i,width:o,height:a,autoPosition:s,minWidth:r,maxWidth:n,minHeight:d,maxHeight:h,id:l}):(e=e||{},t=m(t),this._writeAttr(t,e),this.container.append(t),this.makeWidget(t))},i.prototype.makeWidget=function(t){return t=m(t),this._prepareElement(t,!0),this._updateContainerHeight(),this._triggerAddEvent(),this._triggerChangeEvent(!0),t},i.prototype.willItFit=function(t,e,i,o,a){var s={x:t,y:e,width:i,height:o,autoPosition:a};return this.grid.canBePlacedWithRespectToHeight(s)},i.prototype.removeWidget=function(t,e){e=void 0===e||e;var i=(t=m(t)).data("_gridstack_node");i=i||this.grid.getNodeDataByDOMEl(t),t.removeData("_gridstack_node"),this.grid.removeNode(i,e),this._triggerRemoveEvent(),this._triggerChangeEvent(!0)},i.prototype.removeAll=function(t){!1!==t&&this.grid.nodes.forEach(function(t){t.el.removeData("_gridstack_node")}),this.grid.removeAll(t),this._triggerRemoveEvent()},i.prototype.destroy=function(t){m(window).off("resize",this.onResizeHandler),this.disable(),void 0===t||t?this.container.remove():(this.removeAll(!1),this.container.removeData("gridstack")),f.removeStylesheet(this._stylesId),this.grid&&(this.grid=null)},i.prototype.resizable=function(t,o){var a=this;return(t=m(t)).each(function(t,e){var i=(e=m(e)).data("_gridstack_node");i&&(i.noResize=!o,i.noResize?a.dd.resizable(e,"disable"):a.dd.resizable(e,"enable"))}),this},i.prototype.movable=function(t,o){var a=this;return(t=m(t)).each(function(t,e){var i=(e=m(e)).data("_gridstack_node");i&&(i.noMove=!o,i.noMove?(a.dd.draggable(e,"disable"),e.removeClass("ui-draggable-handle")):(a.dd.draggable(e,"enable"),e.addClass("ui-draggable-handle")))}),this},i.prototype.enableMove=function(t,e){this.movable(this.container.children("."+this.opts.itemClass),t),e&&(this.opts.disableDrag=!t)},i.prototype.enableResize=function(t,e){this.resizable(this.container.children("."+this.opts.itemClass),t),e&&(this.opts.disableResize=!t)},i.prototype.disable=function(){this.movable(this.container.children("."+this.opts.itemClass),!1),this.resizable(this.container.children("."+this.opts.itemClass),!1),this.container.trigger("disable")},i.prototype.enable=function(){this.movable(this.container.children("."+this.opts.itemClass),!0),this.resizable(this.container.children("."+this.opts.itemClass),!0),this.container.trigger("enable")},i.prototype.locked=function(t,o){return(t=m(t)).each(function(t,e){var i=(e=m(e)).data("_gridstack_node");i&&(i.locked=o||!1,e.attr("data-gs-locked",i.locked?"yes":null))}),this},i.prototype.maxHeight=function(t,o){return(t=m(t)).each(function(t,e){var i=(e=m(e)).data("_gridstack_node");i&&(isNaN(o)||(i.maxHeight=o||!1,e.attr("data-gs-max-height",o)))}),this},i.prototype.minHeight=function(t,o){return(t=m(t)).each(function(t,e){var i=(e=m(e)).data("_gridstack_node");i&&(isNaN(o)||(i.minHeight=o||!1,e.attr("data-gs-min-height",o)))}),this},i.prototype.maxWidth=function(t,o){return(t=m(t)).each(function(t,e){var i=(e=m(e)).data("_gridstack_node");i&&(isNaN(o)||(i.maxWidth=o||!1,e.attr("data-gs-max-width",o)))}),this},i.prototype.minWidth=function(t,o){return(t=m(t)).each(function(t,e){var i=(e=m(e)).data("_gridstack_node");i&&(isNaN(o)||(i.minWidth=o||!1,e.attr("data-gs-min-width",o)))}),this},i.prototype._updateElement=function(t,e){var i=(t=m(t).first()).data("_gridstack_node");if(i){var o=this;o.grid.cleanNodes(),o.grid.beginUpdate(i),e.call(this,t,i),o._updateContainerHeight(),o._triggerChangeEvent(),o.grid.endUpdate()}},i.prototype.resize=function(t,i,o){this._updateElement(t,function(t,e){i=null!=i?i:e.width,o=null!=o?o:e.height,this.grid.moveNode(e,e.x,e.y,i,o)})},i.prototype.move=function(t,i,o){this._updateElement(t,function(t,e){i=null!=i?i:e.x,o=null!=o?o:e.y,this.grid.moveNode(e,i,o,e.width,e.height)})},i.prototype.update=function(t,i,o,a,s){this._updateElement(t,function(t,e){i=null!=i?i:e.x,o=null!=o?o:e.y,a=null!=a?a:e.width,s=null!=s?s:e.height,this.grid.moveNode(e,i,o,a,s)})},i.prototype.compact=function(){if(0!==this.grid.nodes.length){this.batchUpdate(),this.grid._sortNodes();var t=this.grid.nodes;this.grid.nodes=[],t.forEach(function(t){t.noMove||t.locked||(t.autoPosition=!0),this.grid.addNode(t,!1),t._dirty=!0},this),this.commit()}},i.prototype.verticalMargin=function(t,e){if(void 0===t)return this.opts.verticalMargin;var i=f.parseHeight(t);this.opts.verticalMarginUnit===i.unit&&this.opts.maxRow===i.height||(this.opts.verticalMarginUnit=i.unit,this.opts.verticalMargin=i.height,e||this._updateStyles())},i.prototype.cellHeight=function(t,e){if(void 0===t){if(this.opts.cellHeight&&"auto"!==this.opts.cellHeight)return this.opts.cellHeight;var i=this.container.children("."+this.opts.itemClass).first(),o=i.attr("data-gs-height"),a=this.opts.verticalMargin;return Math.round((i.outerHeight()-(o-1)*a)/o)}var s=f.parseHeight(t);this.opts.cellHeightUnit===s.unit&&this.opts.cellHeight===s.height||(this.opts.cellHeightUnit=s.unit,this.opts.cellHeight=s.height,e||this._updateStyles())},i.prototype.cellWidth=function(){return Math.round(this.container.outerWidth()/this.opts.column)},i.prototype.getCellFromPixel=function(t,e){var i=void 0!==e&&e?this.container.offset():this.container.position(),o=t.left-i.left,a=t.top-i.top,s=Math.floor(this.container.width()/this.opts.column),r=Math.floor(this.container.height()/parseInt(this.container.attr("data-gs-current-height")));return{x:Math.floor(o/s),y:Math.floor(a/r)}},i.prototype.batchUpdate=function(){this.grid.batchUpdate()},i.prototype.commit=function(){this.grid.commit(),this._triggerRemoveEvent(),this._triggerAddEvent(),this._triggerChangeEvent()},i.prototype.isAreaEmpty=function(t,e,i,o){return this.grid.isAreaEmpty(t,e,i,o)},i.prototype.setStatic=function(t){this.opts.staticGrid=!0===t,this.enableMove(!t),this.enableResize(!t),this._setStaticClass()},i.prototype._setStaticClass=function(){var t="grid-stack-static";!0===this.opts.staticGrid?this.container.addClass(t):this.container.removeClass(t)},l.prototype._layoutsNodesChange=function(t){this._layouts&&!this._ignoreLayoutsNodeChange&&this._layouts.forEach(function(o,a){o&&a!==this.column&&(a>label: Widget +//>>group: Core +//>>description: Provides a factory for creating stateful widgets with a common API. +//>>docs: http://api.jqueryui.com/jQuery.widget/ +//>>demos: http://jqueryui.com/widget/ + + + +var widgetUuid = 0; +var widgetSlice = Array.prototype.slice; + +$.cleanData = ( function( orig ) { + return function( elems ) { + var events, elem, i; + for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) { + try { + + // Only trigger remove when necessary to save time + events = $._data( elem, "events" ); + if ( events && events.remove ) { + $( elem ).triggerHandler( "remove" ); + } + + // Http://bugs.jquery.com/ticket/8235 + } catch ( e ) {} + } + orig( elems ); + }; +} )( $.cleanData ); + +$.widget = function( name, base, prototype ) { + var existingConstructor, constructor, basePrototype; + + // ProxiedPrototype allows the provided prototype to remain unmodified + // so that it can be used as a mixin for multiple widgets (#8876) + var proxiedPrototype = {}; + + var namespace = name.split( "." )[ 0 ]; + name = name.split( "." )[ 1 ]; + var fullName = namespace + "-" + name; + + if ( !prototype ) { + prototype = base; + base = $.Widget; + } + + if ( $.isArray( prototype ) ) { + prototype = $.extend.apply( null, [ {} ].concat( prototype ) ); + } + + // Create selector for plugin + $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { + return !!$.data( elem, fullName ); + }; + + $[ namespace ] = $[ namespace ] || {}; + existingConstructor = $[ namespace ][ name ]; + constructor = $[ namespace ][ name ] = function( options, element ) { + + // Allow instantiation without "new" keyword + if ( !this._createWidget ) { + return new constructor( options, element ); + } + + // Allow instantiation without initializing for simple inheritance + // must use "new" keyword (the code above always passes args) + if ( arguments.length ) { + this._createWidget( options, element ); + } + }; + + // Extend with the existing constructor to carry over any static properties + $.extend( constructor, existingConstructor, { + version: prototype.version, + + // Copy the object used to create the prototype in case we need to + // redefine the widget later + _proto: $.extend( {}, prototype ), + + // Track widgets that inherit from this widget in case this widget is + // redefined after a widget inherits from it + _childConstructors: [] + } ); + + basePrototype = new base(); + + // We need to make the options hash a property directly on the new instance + // otherwise we'll modify the options hash on the prototype that we're + // inheriting from + basePrototype.options = $.widget.extend( {}, basePrototype.options ); + $.each( prototype, function( prop, value ) { + if ( !$.isFunction( value ) ) { + proxiedPrototype[ prop ] = value; + return; + } + proxiedPrototype[ prop ] = ( function() { + function _super() { + return base.prototype[ prop ].apply( this, arguments ); + } + + function _superApply( args ) { + return base.prototype[ prop ].apply( this, args ); + } + + return function() { + var __super = this._super; + var __superApply = this._superApply; + var returnValue; + + this._super = _super; + this._superApply = _superApply; + + returnValue = value.apply( this, arguments ); + + this._super = __super; + this._superApply = __superApply; + + return returnValue; + }; + } )(); + } ); + constructor.prototype = $.widget.extend( basePrototype, { + + // TODO: remove support for widgetEventPrefix + // always use the name + a colon as the prefix, e.g., draggable:start + // don't prefix for widgets that aren't DOM-based + widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name + }, proxiedPrototype, { + constructor: constructor, + namespace: namespace, + widgetName: name, + widgetFullName: fullName + } ); + + // If this widget is being redefined then we need to find all widgets that + // are inheriting from it and redefine all of them so that they inherit from + // the new version of this widget. We're essentially trying to replace one + // level in the prototype chain. + if ( existingConstructor ) { + $.each( existingConstructor._childConstructors, function( i, child ) { + var childPrototype = child.prototype; + + // Redefine the child widget using the same prototype that was + // originally used, but inherit from the new version of the base + $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, + child._proto ); + } ); + + // Remove the list of existing child constructors from the old constructor + // so the old child constructors can be garbage collected + delete existingConstructor._childConstructors; + } else { + base._childConstructors.push( constructor ); + } + + $.widget.bridge( name, constructor ); + + return constructor; +}; + +$.widget.extend = function( target ) { + var input = widgetSlice.call( arguments, 1 ); + var inputIndex = 0; + var inputLength = input.length; + var key; + var value; + + for ( ; inputIndex < inputLength; inputIndex++ ) { + for ( key in input[ inputIndex ] ) { + value = input[ inputIndex ][ key ]; + if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { + + // Clone objects + if ( $.isPlainObject( value ) ) { + target[ key ] = $.isPlainObject( target[ key ] ) ? + $.widget.extend( {}, target[ key ], value ) : + + // Don't extend strings, arrays, etc. with objects + $.widget.extend( {}, value ); + + // Copy everything else by reference + } else { + target[ key ] = value; + } + } + } + } + return target; +}; + +$.widget.bridge = function( name, object ) { + var fullName = object.prototype.widgetFullName || name; + $.fn[ name ] = function( options ) { + var isMethodCall = typeof options === "string"; + var args = widgetSlice.call( arguments, 1 ); + var returnValue = this; + + if ( isMethodCall ) { + + // If this is an empty collection, we need to have the instance method + // return undefined instead of the jQuery instance + if ( !this.length && options === "instance" ) { + returnValue = undefined; + } else { + this.each( function() { + var methodValue; + var instance = $.data( this, fullName ); + + if ( options === "instance" ) { + returnValue = instance; + return false; + } + + if ( !instance ) { + return $.error( "cannot call methods on " + name + + " prior to initialization; " + + "attempted to call method '" + options + "'" ); + } + + if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) { + return $.error( "no such method '" + options + "' for " + name + + " widget instance" ); + } + + methodValue = instance[ options ].apply( instance, args ); + + if ( methodValue !== instance && methodValue !== undefined ) { + returnValue = methodValue && methodValue.jquery ? + returnValue.pushStack( methodValue.get() ) : + methodValue; + return false; + } + } ); + } + } else { + + // Allow multiple hashes to be passed on init + if ( args.length ) { + options = $.widget.extend.apply( null, [ options ].concat( args ) ); + } + + this.each( function() { + var instance = $.data( this, fullName ); + if ( instance ) { + instance.option( options || {} ); + if ( instance._init ) { + instance._init(); + } + } else { + $.data( this, fullName, new object( options, this ) ); + } + } ); + } + + return returnValue; + }; +}; + +$.Widget = function( /* options, element */ ) {}; +$.Widget._childConstructors = []; + +$.Widget.prototype = { + widgetName: "widget", + widgetEventPrefix: "", + defaultElement: "
", + + options: { + classes: {}, + disabled: false, + + // Callbacks + create: null + }, + + _createWidget: function( options, element ) { + element = $( element || this.defaultElement || this )[ 0 ]; + this.element = $( element ); + this.uuid = widgetUuid++; + this.eventNamespace = "." + this.widgetName + this.uuid; + + this.bindings = $(); + this.hoverable = $(); + this.focusable = $(); + this.classesElementLookup = {}; + + if ( element !== this ) { + $.data( element, this.widgetFullName, this ); + this._on( true, this.element, { + remove: function( event ) { + if ( event.target === element ) { + this.destroy(); + } + } + } ); + this.document = $( element.style ? + + // Element within the document + element.ownerDocument : + + // Element is window or document + element.document || element ); + this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow ); + } + + this.options = $.widget.extend( {}, + this.options, + this._getCreateOptions(), + options ); + + this._create(); + + if ( this.options.disabled ) { + this._setOptionDisabled( this.options.disabled ); + } + + this._trigger( "create", null, this._getCreateEventData() ); + this._init(); + }, + + _getCreateOptions: function() { + return {}; + }, + + _getCreateEventData: $.noop, + + _create: $.noop, + + _init: $.noop, + + destroy: function() { + var that = this; + + this._destroy(); + $.each( this.classesElementLookup, function( key, value ) { + that._removeClass( value, key ); + } ); + + // We can probably remove the unbind calls in 2.0 + // all event bindings should go through this._on() + this.element + .off( this.eventNamespace ) + .removeData( this.widgetFullName ); + this.widget() + .off( this.eventNamespace ) + .removeAttr( "aria-disabled" ); + + // Clean up events and states + this.bindings.off( this.eventNamespace ); + }, + + _destroy: $.noop, + + widget: function() { + return this.element; + }, + + option: function( key, value ) { + var options = key; + var parts; + var curOption; + var i; + + if ( arguments.length === 0 ) { + + // Don't return a reference to the internal hash + return $.widget.extend( {}, this.options ); + } + + if ( typeof key === "string" ) { + + // Handle nested keys, e.g., "foo.bar" = { foo: { bar: ___ } } + options = {}; + parts = key.split( "." ); + key = parts.shift(); + if ( parts.length ) { + curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); + for ( i = 0; i < parts.length - 1; i++ ) { + curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; + curOption = curOption[ parts[ i ] ]; + } + key = parts.pop(); + if ( arguments.length === 1 ) { + return curOption[ key ] === undefined ? null : curOption[ key ]; + } + curOption[ key ] = value; + } else { + if ( arguments.length === 1 ) { + return this.options[ key ] === undefined ? null : this.options[ key ]; + } + options[ key ] = value; + } + } + + this._setOptions( options ); + + return this; + }, + + _setOptions: function( options ) { + var key; + + for ( key in options ) { + this._setOption( key, options[ key ] ); + } + + return this; + }, + + _setOption: function( key, value ) { + if ( key === "classes" ) { + this._setOptionClasses( value ); + } + + this.options[ key ] = value; + + if ( key === "disabled" ) { + this._setOptionDisabled( value ); + } + + return this; + }, + + _setOptionClasses: function( value ) { + var classKey, elements, currentElements; + + for ( classKey in value ) { + currentElements = this.classesElementLookup[ classKey ]; + if ( value[ classKey ] === this.options.classes[ classKey ] || + !currentElements || + !currentElements.length ) { + continue; + } + + // We are doing this to create a new jQuery object because the _removeClass() call + // on the next line is going to destroy the reference to the current elements being + // tracked. We need to save a copy of this collection so that we can add the new classes + // below. + elements = $( currentElements.get() ); + this._removeClass( currentElements, classKey ); + + // We don't use _addClass() here, because that uses this.options.classes + // for generating the string of classes. We want to use the value passed in from + // _setOption(), this is the new value of the classes option which was passed to + // _setOption(). We pass this value directly to _classes(). + elements.addClass( this._classes( { + element: elements, + keys: classKey, + classes: value, + add: true + } ) ); + } + }, + + _setOptionDisabled: function( value ) { + this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value ); + + // If the widget is becoming disabled, then nothing is interactive + if ( value ) { + this._removeClass( this.hoverable, null, "ui-state-hover" ); + this._removeClass( this.focusable, null, "ui-state-focus" ); + } + }, + + enable: function() { + return this._setOptions( { disabled: false } ); + }, + + disable: function() { + return this._setOptions( { disabled: true } ); + }, + + _classes: function( options ) { + var full = []; + var that = this; + + options = $.extend( { + element: this.element, + classes: this.options.classes || {} + }, options ); + + function processClassString( classes, checkOption ) { + var current, i; + for ( i = 0; i < classes.length; i++ ) { + current = that.classesElementLookup[ classes[ i ] ] || $(); + if ( options.add ) { + current = $( $.unique( current.get().concat( options.element.get() ) ) ); + } else { + current = $( current.not( options.element ).get() ); + } + that.classesElementLookup[ classes[ i ] ] = current; + full.push( classes[ i ] ); + if ( checkOption && options.classes[ classes[ i ] ] ) { + full.push( options.classes[ classes[ i ] ] ); + } + } + } + + this._on( options.element, { + "remove": "_untrackClassesElement" + } ); + + if ( options.keys ) { + processClassString( options.keys.match( /\S+/g ) || [], true ); + } + if ( options.extra ) { + processClassString( options.extra.match( /\S+/g ) || [] ); + } + + return full.join( " " ); + }, + + _untrackClassesElement: function( event ) { + var that = this; + $.each( that.classesElementLookup, function( key, value ) { + if ( $.inArray( event.target, value ) !== -1 ) { + that.classesElementLookup[ key ] = $( value.not( event.target ).get() ); + } + } ); + }, + + _removeClass: function( element, keys, extra ) { + return this._toggleClass( element, keys, extra, false ); + }, + + _addClass: function( element, keys, extra ) { + return this._toggleClass( element, keys, extra, true ); + }, + + _toggleClass: function( element, keys, extra, add ) { + add = ( typeof add === "boolean" ) ? add : extra; + var shift = ( typeof element === "string" || element === null ), + options = { + extra: shift ? keys : extra, + keys: shift ? element : keys, + element: shift ? this.element : element, + add: add + }; + options.element.toggleClass( this._classes( options ), add ); + return this; + }, + + _on: function( suppressDisabledCheck, element, handlers ) { + var delegateElement; + var instance = this; + + // No suppressDisabledCheck flag, shuffle arguments + if ( typeof suppressDisabledCheck !== "boolean" ) { + handlers = element; + element = suppressDisabledCheck; + suppressDisabledCheck = false; + } + + // No element argument, shuffle and use this.element + if ( !handlers ) { + handlers = element; + element = this.element; + delegateElement = this.widget(); + } else { + element = delegateElement = $( element ); + this.bindings = this.bindings.add( element ); + } + + $.each( handlers, function( event, handler ) { + function handlerProxy() { + + // Allow widgets to customize the disabled handling + // - disabled as an array instead of boolean + // - disabled class as method for disabling individual parts + if ( !suppressDisabledCheck && + ( instance.options.disabled === true || + $( this ).hasClass( "ui-state-disabled" ) ) ) { + return; + } + return ( typeof handler === "string" ? instance[ handler ] : handler ) + .apply( instance, arguments ); + } + + // Copy the guid so direct unbinding works + if ( typeof handler !== "string" ) { + handlerProxy.guid = handler.guid = + handler.guid || handlerProxy.guid || $.guid++; + } + + var match = event.match( /^([\w:-]*)\s*(.*)$/ ); + var eventName = match[ 1 ] + instance.eventNamespace; + var selector = match[ 2 ]; + + if ( selector ) { + delegateElement.on( eventName, selector, handlerProxy ); + } else { + element.on( eventName, handlerProxy ); + } + } ); + }, + + _off: function( element, eventName ) { + eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) + + this.eventNamespace; + element.off( eventName ).off( eventName ); + + // Clear the stack to avoid memory leaks (#10056) + this.bindings = $( this.bindings.not( element ).get() ); + this.focusable = $( this.focusable.not( element ).get() ); + this.hoverable = $( this.hoverable.not( element ).get() ); + }, + + _delay: function( handler, delay ) { + function handlerProxy() { + return ( typeof handler === "string" ? instance[ handler ] : handler ) + .apply( instance, arguments ); + } + var instance = this; + return setTimeout( handlerProxy, delay || 0 ); + }, + + _hoverable: function( element ) { + this.hoverable = this.hoverable.add( element ); + this._on( element, { + mouseenter: function( event ) { + this._addClass( $( event.currentTarget ), null, "ui-state-hover" ); + }, + mouseleave: function( event ) { + this._removeClass( $( event.currentTarget ), null, "ui-state-hover" ); + } + } ); + }, + + _focusable: function( element ) { + this.focusable = this.focusable.add( element ); + this._on( element, { + focusin: function( event ) { + this._addClass( $( event.currentTarget ), null, "ui-state-focus" ); + }, + focusout: function( event ) { + this._removeClass( $( event.currentTarget ), null, "ui-state-focus" ); + } + } ); + }, + + _trigger: function( type, event, data ) { + var prop, orig; + var callback = this.options[ type ]; + + data = data || {}; + event = $.Event( event ); + event.type = ( type === this.widgetEventPrefix ? + type : + this.widgetEventPrefix + type ).toLowerCase(); + + // The original event may come from any element + // so we need to reset the target on the new event + event.target = this.element[ 0 ]; + + // Copy original event properties over to the new event + orig = event.originalEvent; + if ( orig ) { + for ( prop in orig ) { + if ( !( prop in event ) ) { + event[ prop ] = orig[ prop ]; + } + } + } + + this.element.trigger( event, data ); + return !( $.isFunction( callback ) && + callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false || + event.isDefaultPrevented() ); + } +}; + +$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { + $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { + if ( typeof options === "string" ) { + options = { effect: options }; + } + + var hasOptions; + var effectName = !options ? + method : + options === true || typeof options === "number" ? + defaultEffect : + options.effect || defaultEffect; + + options = options || {}; + if ( typeof options === "number" ) { + options = { duration: options }; + } + + hasOptions = !$.isEmptyObject( options ); + options.complete = callback; + + if ( options.delay ) { + element.delay( options.delay ); + } + + if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { + element[ method ]( options ); + } else if ( effectName !== method && element[ effectName ] ) { + element[ effectName ]( options.duration, options.easing, callback ); + } else { + element.queue( function( next ) { + $( this )[ method ](); + if ( callback ) { + callback.call( element[ 0 ] ); + } + next(); + } ); + } + }; +} ); + +var widget = $.widget; + + +/*! + * jQuery UI :data 1.12.1 + * http://jqueryui.com + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license. + * http://jquery.org/license + */ + +//>>label: :data Selector +//>>group: Core +//>>description: Selects elements which have data stored under the specified key. +//>>docs: http://api.jqueryui.com/data-selector/ + + +var data = $.extend( $.expr[ ":" ], { + data: $.expr.createPseudo ? + $.expr.createPseudo( function( dataName ) { + return function( elem ) { + return !!$.data( elem, dataName ); + }; + } ) : + + // Support: jQuery <1.8 + function( elem, i, match ) { + return !!$.data( elem, match[ 3 ] ); + } +} ); + +/*! + * jQuery UI Disable Selection 1.12.1 + * http://jqueryui.com + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license. + * http://jquery.org/license + */ + +//>>label: disableSelection +//>>group: Core +//>>description: Disable selection of text content within the set of matched elements. +//>>docs: http://api.jqueryui.com/disableSelection/ + +// This file is deprecated + + +var disableSelection = $.fn.extend( { + disableSelection: ( function() { + var eventType = "onselectstart" in document.createElement( "div" ) ? + "selectstart" : + "mousedown"; + + return function() { + return this.on( eventType + ".ui-disableSelection", function( event ) { + event.preventDefault(); + } ); + }; + } )(), + + enableSelection: function() { + return this.off( ".ui-disableSelection" ); + } +} ); + + +/*! + * jQuery UI Scroll Parent 1.12.1 + * http://jqueryui.com + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license. + * http://jquery.org/license + */ + +//>>label: scrollParent +//>>group: Core +//>>description: Get the closest ancestor element that is scrollable. +//>>docs: http://api.jqueryui.com/scrollParent/ + + + +var scrollParent = $.fn.scrollParent = function( includeHidden ) { + var position = this.css( "position" ), + excludeStaticParent = position === "absolute", + overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/, + scrollParent = this.parents().filter( function() { + var parent = $( this ); + if ( excludeStaticParent && parent.css( "position" ) === "static" ) { + return false; + } + return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + + parent.css( "overflow-x" ) ); + } ).eq( 0 ); + + return position === "fixed" || !scrollParent.length ? + $( this[ 0 ].ownerDocument || document ) : + scrollParent; +}; + + + + +// This file is deprecated +var ie = $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); + +/*! + * jQuery UI Mouse 1.12.1 + * http://jqueryui.com + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license. + * http://jquery.org/license + */ + +//>>label: Mouse +//>>group: Widgets +//>>description: Abstracts mouse-based interactions to assist in creating certain widgets. +//>>docs: http://api.jqueryui.com/mouse/ + + + +var mouseHandled = false; +$( document ).on( "mouseup", function() { + mouseHandled = false; +} ); + +var widgetsMouse = $.widget( "ui.mouse", { + version: "1.12.1", + options: { + cancel: "input, textarea, button, select, option", + distance: 1, + delay: 0 + }, + _mouseInit: function() { + var that = this; + + this.element + .on( "mousedown." + this.widgetName, function( event ) { + return that._mouseDown( event ); + } ) + .on( "click." + this.widgetName, function( event ) { + if ( true === $.data( event.target, that.widgetName + ".preventClickEvent" ) ) { + $.removeData( event.target, that.widgetName + ".preventClickEvent" ); + event.stopImmediatePropagation(); + return false; + } + } ); + + this.started = false; + }, + + // TODO: make sure destroying one instance of mouse doesn't mess with + // other instances of mouse + _mouseDestroy: function() { + this.element.off( "." + this.widgetName ); + if ( this._mouseMoveDelegate ) { + this.document + .off( "mousemove." + this.widgetName, this._mouseMoveDelegate ) + .off( "mouseup." + this.widgetName, this._mouseUpDelegate ); + } + }, + + _mouseDown: function( event ) { + + // don't let more than one widget handle mouseStart + if ( mouseHandled ) { + return; + } + + this._mouseMoved = false; + + // We may have missed mouseup (out of window) + ( this._mouseStarted && this._mouseUp( event ) ); + + this._mouseDownEvent = event; + + var that = this, + btnIsLeft = ( event.which === 1 ), + + // event.target.nodeName works around a bug in IE 8 with + // disabled inputs (#7620) + elIsCancel = ( typeof this.options.cancel === "string" && event.target.nodeName ? + $( event.target ).closest( this.options.cancel ).length : false ); + if ( !btnIsLeft || elIsCancel || !this._mouseCapture( event ) ) { + return true; + } + + this.mouseDelayMet = !this.options.delay; + if ( !this.mouseDelayMet ) { + this._mouseDelayTimer = setTimeout( function() { + that.mouseDelayMet = true; + }, this.options.delay ); + } + + if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) { + this._mouseStarted = ( this._mouseStart( event ) !== false ); + if ( !this._mouseStarted ) { + event.preventDefault(); + return true; + } + } + + // Click event may never have fired (Gecko & Opera) + if ( true === $.data( event.target, this.widgetName + ".preventClickEvent" ) ) { + $.removeData( event.target, this.widgetName + ".preventClickEvent" ); + } + + // These delegates are required to keep context + this._mouseMoveDelegate = function( event ) { + return that._mouseMove( event ); + }; + this._mouseUpDelegate = function( event ) { + return that._mouseUp( event ); + }; + + this.document + .on( "mousemove." + this.widgetName, this._mouseMoveDelegate ) + .on( "mouseup." + this.widgetName, this._mouseUpDelegate ); + + event.preventDefault(); + + mouseHandled = true; + return true; + }, + + _mouseMove: function( event ) { + + // Only check for mouseups outside the document if you've moved inside the document + // at least once. This prevents the firing of mouseup in the case of IE<9, which will + // fire a mousemove event if content is placed under the cursor. See #7778 + // Support: IE <9 + if ( this._mouseMoved ) { + + // IE mouseup check - mouseup happened when mouse was out of window + if ( $.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && + !event.button ) { + return this._mouseUp( event ); + + // Iframe mouseup check - mouseup occurred in another document + } else if ( !event.which ) { + + // Support: Safari <=8 - 9 + // Safari sets which to 0 if you press any of the following keys + // during a drag (#14461) + if ( event.originalEvent.altKey || event.originalEvent.ctrlKey || + event.originalEvent.metaKey || event.originalEvent.shiftKey ) { + this.ignoreMissingWhich = true; + } else if ( !this.ignoreMissingWhich ) { + return this._mouseUp( event ); + } + } + } + + if ( event.which || event.button ) { + this._mouseMoved = true; + } + + if ( this._mouseStarted ) { + this._mouseDrag( event ); + return event.preventDefault(); + } + + if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) { + this._mouseStarted = + ( this._mouseStart( this._mouseDownEvent, event ) !== false ); + ( this._mouseStarted ? this._mouseDrag( event ) : this._mouseUp( event ) ); + } + + return !this._mouseStarted; + }, + + _mouseUp: function( event ) { + this.document + .off( "mousemove." + this.widgetName, this._mouseMoveDelegate ) + .off( "mouseup." + this.widgetName, this._mouseUpDelegate ); + + if ( this._mouseStarted ) { + this._mouseStarted = false; + + if ( event.target === this._mouseDownEvent.target ) { + $.data( event.target, this.widgetName + ".preventClickEvent", true ); + } + + this._mouseStop( event ); + } + + if ( this._mouseDelayTimer ) { + clearTimeout( this._mouseDelayTimer ); + delete this._mouseDelayTimer; + } + + this.ignoreMissingWhich = false; + mouseHandled = false; + event.preventDefault(); + }, + + _mouseDistanceMet: function( event ) { + return ( Math.max( + Math.abs( this._mouseDownEvent.pageX - event.pageX ), + Math.abs( this._mouseDownEvent.pageY - event.pageY ) + ) >= this.options.distance + ); + }, + + _mouseDelayMet: function( /* event */ ) { + return this.mouseDelayMet; + }, + + // These are placeholder methods, to be overriden by extending plugin + _mouseStart: function( /* event */ ) {}, + _mouseDrag: function( /* event */ ) {}, + _mouseStop: function( /* event */ ) {}, + _mouseCapture: function( /* event */ ) { return true; } +} ); + + + + +// $.ui.plugin is deprecated. Use $.widget() extensions instead. +var plugin = $.ui.plugin = { + add: function( module, option, set ) { + var i, + proto = $.ui[ module ].prototype; + for ( i in set ) { + proto.plugins[ i ] = proto.plugins[ i ] || []; + proto.plugins[ i ].push( [ option, set[ i ] ] ); + } + }, + call: function( instance, name, args, allowDisconnected ) { + var i, + set = instance.plugins[ name ]; + + if ( !set ) { + return; + } + + if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || + instance.element[ 0 ].parentNode.nodeType === 11 ) ) { + return; + } + + for ( i = 0; i < set.length; i++ ) { + if ( instance.options[ set[ i ][ 0 ] ] ) { + set[ i ][ 1 ].apply( instance.element, args ); + } + } + } +}; + + + +var safeActiveElement = $.ui.safeActiveElement = function( document ) { + var activeElement; + + // Support: IE 9 only + // IE9 throws an "Unspecified error" accessing document.activeElement from an \x3c!--
The url {{ }} cannot be loaded into an iframe.
--\x3e
'),e.put("partials/toast.html",'

{{::toast.title}}

'),e.put("components/ui-card-panel/ui-card-panel.html",'

{{group.header.name}}

'),e.put("components/ui-chart-js/ui-chart-js.html",'
'),e.put("components/ui-icon/ui-icon.html",'
{{icon.substr(3)}}
'),e.put("components/ui-gauge/ui-gauge.html","
"),e.put("components/ui-component/templates/button.html",' '),e.put("components/ui-component/templates/chart.html",'

{{ me.item.nodata }}

'),e.put("components/ui-component/templates/colour-picker.html",'

'),e.put("components/ui-component/templates/date-picker.html",'

'),e.put("components/ui-component/templates/dropdown.html",'

{{ opt.label }} {{ opt.label }}
'),e.put("components/ui-component/templates/form.html",'

{{opt.label}} {{opt.label}} \x3c!-- --\x3e
{{me.item.submit}} {{me.item.cancel}}
cancel'),e.put("components/ui-component/templates/gauge.html",'

'),e.put("components/ui-component/templates/numeric.html",'

'),e.put("components/ui-component/templates/slider.html",'

'),e.put("components/ui-component/templates/spacer.html",' '),e.put("components/ui-component/templates/switch.html",'

'),e.put("components/ui-component/templates/template.html",' '),e.put("components/ui-component/templates/text-input-CR.html",' '),e.put("components/ui-component/templates/text-input.html",' '),e.put("components/ui-component/templates/text.html",'

')}]); diff --git a/software/flow/node_modules/node-red-dashboard/dist/js/tinycolor-min.js b/software/flow/node_modules/node-red-dashboard/dist/js/tinycolor-min.js new file mode 100644 index 0000000..64bf76d --- /dev/null +++ b/software/flow/node_modules/node-red-dashboard/dist/js/tinycolor-min.js @@ -0,0 +1,4 @@ +// TinyColor v1.4.2 +// https://github.com/bgrins/TinyColor +// 2020-09-25, Brian Grinstead, MIT License +!function(a){function b(a,d){if(a=a?a:"",d=d||{},a instanceof b)return a;if(!(this instanceof b))return new b(a,d);var e=c(a);this._originalInput=a,this._r=e.r,this._g=e.g,this._b=e.b,this._a=e.a,this._roundA=P(100*this._a)/100,this._format=d.format||e.format,this._gradientType=d.gradientType,this._r<1&&(this._r=P(this._r)),this._g<1&&(this._g=P(this._g)),this._b<1&&(this._b=P(this._b)),this._ok=e.ok,this._tc_id=O++}function c(a){var b={r:0,g:0,b:0},c=1,e=null,g=null,i=null,j=!1,k=!1;return"string"==typeof a&&(a=K(a)),"object"==typeof a&&(J(a.r)&&J(a.g)&&J(a.b)?(b=d(a.r,a.g,a.b),j=!0,k="%"===String(a.r).substr(-1)?"prgb":"rgb"):J(a.h)&&J(a.s)&&J(a.v)?(e=G(a.s),g=G(a.v),b=h(a.h,e,g),j=!0,k="hsv"):J(a.h)&&J(a.s)&&J(a.l)&&(e=G(a.s),i=G(a.l),b=f(a.h,e,i),j=!0,k="hsl"),a.hasOwnProperty("a")&&(c=a.a)),c=z(c),{ok:j,format:a.format||k,r:Q(255,R(b.r,0)),g:Q(255,R(b.g,0)),b:Q(255,R(b.b,0)),a:c}}function d(a,b,c){return{r:255*A(a,255),g:255*A(b,255),b:255*A(c,255)}}function e(a,b,c){a=A(a,255),b=A(b,255),c=A(c,255);var d,e,f=R(a,b,c),g=Q(a,b,c),h=(f+g)/2;if(f==g)d=e=0;else{var i=f-g;switch(e=h>.5?i/(2-f-g):i/(f+g),f){case a:d=(b-c)/i+(c>b?6:0);break;case b:d=(c-a)/i+2;break;case c:d=(a-b)/i+4}d/=6}return{h:d,s:e,l:h}}function f(a,b,c){function d(a,b,c){return 0>c&&(c+=1),c>1&&(c-=1),1/6>c?a+6*(b-a)*c:.5>c?b:2/3>c?a+(b-a)*(2/3-c)*6:a}var e,f,g;if(a=A(a,360),b=A(b,100),c=A(c,100),0===b)e=f=g=c;else{var h=.5>c?c*(1+b):c+b-c*b,i=2*c-h;e=d(i,h,a+1/3),f=d(i,h,a),g=d(i,h,a-1/3)}return{r:255*e,g:255*f,b:255*g}}function g(a,b,c){a=A(a,255),b=A(b,255),c=A(c,255);var d,e,f=R(a,b,c),g=Q(a,b,c),h=f,i=f-g;if(e=0===f?0:i/f,f==g)d=0;else{switch(f){case a:d=(b-c)/i+(c>b?6:0);break;case b:d=(c-a)/i+2;break;case c:d=(a-b)/i+4}d/=6}return{h:d,s:e,v:h}}function h(b,c,d){b=6*A(b,360),c=A(c,100),d=A(d,100);var e=a.floor(b),f=b-e,g=d*(1-c),h=d*(1-f*c),i=d*(1-(1-f)*c),j=e%6,k=[d,h,g,g,i,d][j],l=[i,d,d,h,g,g][j],m=[g,g,i,d,d,h][j];return{r:255*k,g:255*l,b:255*m}}function i(a,b,c,d){var e=[F(P(a).toString(16)),F(P(b).toString(16)),F(P(c).toString(16))];return d&&e[0].charAt(0)==e[0].charAt(1)&&e[1].charAt(0)==e[1].charAt(1)&&e[2].charAt(0)==e[2].charAt(1)?e[0].charAt(0)+e[1].charAt(0)+e[2].charAt(0):e.join("")}function j(a,b,c,d,e){var f=[F(P(a).toString(16)),F(P(b).toString(16)),F(P(c).toString(16)),F(H(d))];return e&&f[0].charAt(0)==f[0].charAt(1)&&f[1].charAt(0)==f[1].charAt(1)&&f[2].charAt(0)==f[2].charAt(1)&&f[3].charAt(0)==f[3].charAt(1)?f[0].charAt(0)+f[1].charAt(0)+f[2].charAt(0)+f[3].charAt(0):f.join("")}function k(a,b,c,d){var e=[F(H(d)),F(P(a).toString(16)),F(P(b).toString(16)),F(P(c).toString(16))];return e.join("")}function l(a,c){c=0===c?0:c||10;var d=b(a).toHsl();return d.s-=c/100,d.s=B(d.s),b(d)}function m(a,c){c=0===c?0:c||10;var d=b(a).toHsl();return d.s+=c/100,d.s=B(d.s),b(d)}function n(a){return b(a).desaturate(100)}function o(a,c){c=0===c?0:c||10;var d=b(a).toHsl();return d.l+=c/100,d.l=B(d.l),b(d)}function p(a,c){c=0===c?0:c||10;var d=b(a).toRgb();return d.r=R(0,Q(255,d.r-P(255*-(c/100)))),d.g=R(0,Q(255,d.g-P(255*-(c/100)))),d.b=R(0,Q(255,d.b-P(255*-(c/100)))),b(d)}function q(a,c){c=0===c?0:c||10;var d=b(a).toHsl();return d.l-=c/100,d.l=B(d.l),b(d)}function r(a,c){var d=b(a).toHsl(),e=(d.h+c)%360;return d.h=0>e?360+e:e,b(d)}function s(a){var c=b(a).toHsl();return c.h=(c.h+180)%360,b(c)}function t(a){var c=b(a).toHsl(),d=c.h;return[b(a),b({h:(d+120)%360,s:c.s,l:c.l}),b({h:(d+240)%360,s:c.s,l:c.l})]}function u(a){var c=b(a).toHsl(),d=c.h;return[b(a),b({h:(d+90)%360,s:c.s,l:c.l}),b({h:(d+180)%360,s:c.s,l:c.l}),b({h:(d+270)%360,s:c.s,l:c.l})]}function v(a){var c=b(a).toHsl(),d=c.h;return[b(a),b({h:(d+72)%360,s:c.s,l:c.l}),b({h:(d+216)%360,s:c.s,l:c.l})]}function w(a,c,d){c=c||6,d=d||30;var e=b(a).toHsl(),f=360/d,g=[b(a)];for(e.h=(e.h-(f*c>>1)+720)%360;--c;)e.h=(e.h+f)%360,g.push(b(e));return g}function x(a,c){c=c||6;for(var d=b(a).toHsv(),e=d.h,f=d.s,g=d.v,h=[],i=1/c;c--;)h.push(b({h:e,s:f,v:g})),g=(g+i)%1;return h}function y(a){var b={};for(var c in a)a.hasOwnProperty(c)&&(b[a[c]]=c);return b}function z(a){return a=parseFloat(a),(isNaN(a)||0>a||a>1)&&(a=1),a}function A(b,c){D(b)&&(b="100%");var d=E(b);return b=Q(c,R(0,parseFloat(b))),d&&(b=parseInt(b*c,10)/100),a.abs(b-c)<1e-6?1:b%c/parseFloat(c)}function B(a){return Q(1,R(0,a))}function C(a){return parseInt(a,16)}function D(a){return"string"==typeof a&&-1!=a.indexOf(".")&&1===parseFloat(a)}function E(a){return"string"==typeof a&&-1!=a.indexOf("%")}function F(a){return 1==a.length?"0"+a:""+a}function G(a){return 1>=a&&(a=100*a+"%"),a}function H(b){return a.round(255*parseFloat(b)).toString(16)}function I(a){return C(a)/255}function J(a){return!!V.CSS_UNIT.exec(a)}function K(a){a=a.replace(M,"").replace(N,"").toLowerCase();var b=!1;if(T[a])a=T[a],b=!0;else if("transparent"==a)return{r:0,g:0,b:0,a:0,format:"name"};var c;return(c=V.rgb.exec(a))?{r:c[1],g:c[2],b:c[3]}:(c=V.rgba.exec(a))?{r:c[1],g:c[2],b:c[3],a:c[4]}:(c=V.hsl.exec(a))?{h:c[1],s:c[2],l:c[3]}:(c=V.hsla.exec(a))?{h:c[1],s:c[2],l:c[3],a:c[4]}:(c=V.hsv.exec(a))?{h:c[1],s:c[2],v:c[3]}:(c=V.hsva.exec(a))?{h:c[1],s:c[2],v:c[3],a:c[4]}:(c=V.hex8.exec(a))?{r:C(c[1]),g:C(c[2]),b:C(c[3]),a:I(c[4]),format:b?"name":"hex8"}:(c=V.hex6.exec(a))?{r:C(c[1]),g:C(c[2]),b:C(c[3]),format:b?"name":"hex"}:(c=V.hex4.exec(a))?{r:C(c[1]+""+c[1]),g:C(c[2]+""+c[2]),b:C(c[3]+""+c[3]),a:I(c[4]+""+c[4]),format:b?"name":"hex8"}:(c=V.hex3.exec(a))?{r:C(c[1]+""+c[1]),g:C(c[2]+""+c[2]),b:C(c[3]+""+c[3]),format:b?"name":"hex"}:!1}function L(a){var b,c;return a=a||{level:"AA",size:"small"},b=(a.level||"AA").toUpperCase(),c=(a.size||"small").toLowerCase(),"AA"!==b&&"AAA"!==b&&(b="AA"),"small"!==c&&"large"!==c&&(c="small"),{level:b,size:c}}var M=/^\s+/,N=/\s+$/,O=0,P=a.round,Q=a.min,R=a.max,S=a.random;b.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var a=this.toRgb();return(299*a.r+587*a.g+114*a.b)/1e3},getLuminance:function(){var b,c,d,e,f,g,h=this.toRgb();return b=h.r/255,c=h.g/255,d=h.b/255,e=.03928>=b?b/12.92:a.pow((b+.055)/1.055,2.4),f=.03928>=c?c/12.92:a.pow((c+.055)/1.055,2.4),g=.03928>=d?d/12.92:a.pow((d+.055)/1.055,2.4),.2126*e+.7152*f+.0722*g},setAlpha:function(a){return this._a=z(a),this._roundA=P(100*this._a)/100,this},toHsv:function(){var a=g(this._r,this._g,this._b);return{h:360*a.h,s:a.s,v:a.v,a:this._a}},toHsvString:function(){var a=g(this._r,this._g,this._b),b=P(360*a.h),c=P(100*a.s),d=P(100*a.v);return 1==this._a?"hsv("+b+", "+c+"%, "+d+"%)":"hsva("+b+", "+c+"%, "+d+"%, "+this._roundA+")"},toHsl:function(){var a=e(this._r,this._g,this._b);return{h:360*a.h,s:a.s,l:a.l,a:this._a}},toHslString:function(){var a=e(this._r,this._g,this._b),b=P(360*a.h),c=P(100*a.s),d=P(100*a.l);return 1==this._a?"hsl("+b+", "+c+"%, "+d+"%)":"hsla("+b+", "+c+"%, "+d+"%, "+this._roundA+")"},toHex:function(a){return i(this._r,this._g,this._b,a)},toHexString:function(a){return"#"+this.toHex(a)},toHex8:function(a){return j(this._r,this._g,this._b,this._a,a)},toHex8String:function(a){return"#"+this.toHex8(a)},toRgb:function(){return{r:P(this._r),g:P(this._g),b:P(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+P(this._r)+", "+P(this._g)+", "+P(this._b)+")":"rgba("+P(this._r)+", "+P(this._g)+", "+P(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:P(100*A(this._r,255))+"%",g:P(100*A(this._g,255))+"%",b:P(100*A(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+P(100*A(this._r,255))+"%, "+P(100*A(this._g,255))+"%, "+P(100*A(this._b,255))+"%)":"rgba("+P(100*A(this._r,255))+"%, "+P(100*A(this._g,255))+"%, "+P(100*A(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":this._a<1?!1:U[i(this._r,this._g,this._b,!0)]||!1},toFilter:function(a){var c="#"+k(this._r,this._g,this._b,this._a),d=c,e=this._gradientType?"GradientType = 1, ":"";if(a){var f=b(a);d="#"+k(f._r,f._g,f._b,f._a)}return"progid:DXImageTransform.Microsoft.gradient("+e+"startColorstr="+c+",endColorstr="+d+")"},toString:function(a){var b=!!a;a=a||this._format;var c=!1,d=this._a<1&&this._a>=0,e=!b&&d&&("hex"===a||"hex6"===a||"hex3"===a||"hex4"===a||"hex8"===a||"name"===a);return e?"name"===a&&0===this._a?this.toName():this.toRgbString():("rgb"===a&&(c=this.toRgbString()),"prgb"===a&&(c=this.toPercentageRgbString()),("hex"===a||"hex6"===a)&&(c=this.toHexString()),"hex3"===a&&(c=this.toHexString(!0)),"hex4"===a&&(c=this.toHex8String(!0)),"hex8"===a&&(c=this.toHex8String()),"name"===a&&(c=this.toName()),"hsl"===a&&(c=this.toHslString()),"hsv"===a&&(c=this.toHsvString()),c||this.toHexString())},clone:function(){return b(this.toString())},_applyModification:function(a,b){var c=a.apply(null,[this].concat([].slice.call(b)));return this._r=c._r,this._g=c._g,this._b=c._b,this.setAlpha(c._a),this},lighten:function(){return this._applyModification(o,arguments)},brighten:function(){return this._applyModification(p,arguments)},darken:function(){return this._applyModification(q,arguments)},desaturate:function(){return this._applyModification(l,arguments)},saturate:function(){return this._applyModification(m,arguments)},greyscale:function(){return this._applyModification(n,arguments)},spin:function(){return this._applyModification(r,arguments)},_applyCombination:function(a,b){return a.apply(null,[this].concat([].slice.call(b)))},analogous:function(){return this._applyCombination(w,arguments)},complement:function(){return this._applyCombination(s,arguments)},monochromatic:function(){return this._applyCombination(x,arguments)},splitcomplement:function(){return this._applyCombination(v,arguments)},triad:function(){return this._applyCombination(t,arguments)},tetrad:function(){return this._applyCombination(u,arguments)}},b.fromRatio=function(a,c){if("object"==typeof a){var d={};for(var e in a)a.hasOwnProperty(e)&&("a"===e?d[e]=a[e]:d[e]=G(a[e]));a=d}return b(a,c)},b.equals=function(a,c){return a&&c?b(a).toRgbString()==b(c).toRgbString():!1},b.random=function(){return b.fromRatio({r:S(),g:S(),b:S()})},b.mix=function(a,c,d){d=0===d?0:d||50;var e=b(a).toRgb(),f=b(c).toRgb(),g=d/100,h={r:(f.r-e.r)*g+e.r,g:(f.g-e.g)*g+e.g,b:(f.b-e.b)*g+e.b,a:(f.a-e.a)*g+e.a};return b(h)},b.readability=function(c,d){var e=b(c),f=b(d);return(a.max(e.getLuminance(),f.getLuminance())+.05)/(a.min(e.getLuminance(),f.getLuminance())+.05)},b.isReadable=function(a,c,d){var e,f,g=b.readability(a,c);switch(f=!1,e=L(d),e.level+e.size){case"AAsmall":case"AAAlarge":f=g>=4.5;break;case"AAlarge":f=g>=3;break;case"AAAsmall":f=g>=7}return f},b.mostReadable=function(a,c,d){var e,f,g,h,i=null,j=0;d=d||{},f=d.includeFallbackColors,g=d.level,h=d.size;for(var k=0;kj&&(j=e,i=b(c[k]));return b.isReadable(a,i,{level:g,size:h})||!f?i:(d.includeFallbackColors=!1,b.mostReadable(a,["#fff","#000"],d))};var T=b.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},U=b.hexNames=y(T),V=function(){var a="[-\\+]?\\d+%?",b="[-\\+]?\\d*\\.\\d+%?",c="(?:"+b+")|(?:"+a+")",d="[\\s|\\(]+("+c+")[,|\\s]+("+c+")[,|\\s]+("+c+")\\s*\\)?",e="[\\s|\\(]+("+c+")[,|\\s]+("+c+")[,|\\s]+("+c+")[,|\\s]+("+c+")\\s*\\)?";return{CSS_UNIT:new RegExp(c),rgb:new RegExp("rgb"+d),rgba:new RegExp("rgba"+e),hsl:new RegExp("hsl"+d),hsla:new RegExp("hsla"+e),hsv:new RegExp("hsv"+d),hsva:new RegExp("hsva"+e),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();"undefined"!=typeof module&&module.exports?module.exports=b:"function"==typeof define&&define.amd?define(function(){return b}):window.tinycolor=b}(Math); diff --git a/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.d.ts b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.d.ts new file mode 100644 index 0000000..93d02a9 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.d.ts @@ -0,0 +1,7 @@ +/// +import { EventEmitter } from 'events'; +import { EventNames, EventListenerParameters, AbortSignal } from './types'; +export interface OnceOptions { + signal?: AbortSignal; +} +export default function once>(emitter: Emitter, name: Event, { signal }?: OnceOptions): Promise>; diff --git a/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.js b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.js new file mode 100644 index 0000000..ca6385b --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function once(emitter, name, { signal } = {}) { + return new Promise((resolve, reject) => { + function cleanup() { + signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', cleanup); + emitter.removeListener(name, onEvent); + emitter.removeListener('error', onError); + } + function onEvent(...args) { + cleanup(); + resolve(args); + } + function onError(err) { + cleanup(); + reject(err); + } + signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', cleanup); + emitter.on(name, onEvent); + emitter.on('error', onError); + }); +} +exports.default = once; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.js.map b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.js.map new file mode 100644 index 0000000..61708ca --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAOA,SAAwB,IAAI,CAI3B,OAAgB,EAChB,IAAW,EACX,EAAE,MAAM,KAAkB,EAAE;IAE5B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,SAAS,OAAO;YACf,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC9C,OAAO,CAAC,cAAc,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YACtC,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC1C,CAAC;QACD,SAAS,OAAO,CAAC,GAAG,IAAW;YAC9B,OAAO,EAAE,CAAC;YACV,OAAO,CAAC,IAA+C,CAAC,CAAC;QAC1D,CAAC;QACD,SAAS,OAAO,CAAC,GAAU;YAC1B,OAAO,EAAE,CAAC;YACV,MAAM,CAAC,GAAG,CAAC,CAAC;QACb,CAAC;QACD,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC3C,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC1B,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC9B,CAAC,CAAC,CAAC;AACJ,CAAC;AA1BD,uBA0BC"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.d.ts b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.d.ts new file mode 100644 index 0000000..eb2bbc6 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.d.ts @@ -0,0 +1,231 @@ +export declare type OverloadedParameters = T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; + (...args: infer A16): any; + (...args: infer A17): any; + (...args: infer A18): any; + (...args: infer A19): any; + (...args: infer A20): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16 | A17 | A18 | A19 | A20 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; + (...args: infer A16): any; + (...args: infer A17): any; + (...args: infer A18): any; + (...args: infer A19): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16 | A17 | A18 | A19 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; + (...args: infer A16): any; + (...args: infer A17): any; + (...args: infer A18): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16 | A17 | A18 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; + (...args: infer A16): any; + (...args: infer A17): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16 | A17 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; + (...args: infer A16): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 | A16 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; + (...args: infer A15): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 | A15 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; + (...args: infer A14): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 | A14 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; + (...args: infer A13): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 | A13 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; + (...args: infer A12): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; + (...args: infer A11): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; + (...args: infer A10): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; + (...args: infer A9): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; + (...args: infer A8): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; + (...args: infer A7): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 | A7 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; + (...args: infer A6): any; +} ? A1 | A2 | A3 | A4 | A5 | A6 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; + (...args: infer A5): any; +} ? A1 | A2 | A3 | A4 | A5 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; + (...args: infer A4): any; +} ? A1 | A2 | A3 | A4 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; + (...args: infer A3): any; +} ? A1 | A2 | A3 : T extends { + (...args: infer A1): any; + (...args: infer A2): any; +} ? A1 | A2 : T extends { + (...args: infer A1): any; +} ? A1 : any; diff --git a/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.js b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.js new file mode 100644 index 0000000..207186d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=overloaded-parameters.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.js.map b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.js.map new file mode 100644 index 0000000..863f146 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/overloaded-parameters.js.map @@ -0,0 +1 @@ +{"version":3,"file":"overloaded-parameters.js","sourceRoot":"","sources":["../src/overloaded-parameters.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.d.ts b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.d.ts new file mode 100644 index 0000000..58be828 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.d.ts @@ -0,0 +1,17 @@ +/// +import { EventEmitter } from 'events'; +import { OverloadedParameters } from './overloaded-parameters'; +export declare type FirstParameter = T extends [infer R, ...any[]] ? R : never; +export declare type EventListener = F extends [ + T, + infer R, + ...any[] +] ? R : never; +export declare type EventParameters = OverloadedParameters; +export declare type EventNames = FirstParameter>; +export declare type EventListenerParameters> = WithDefault, Event>>, unknown[]>; +export declare type WithDefault = [T] extends [never] ? D : T; +export interface AbortSignal { + addEventListener: (name: string, listener: (...args: any[]) => any) => void; + removeEventListener: (name: string, listener: (...args: any[]) => any) => void; +} diff --git a/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.js b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.js new file mode 100644 index 0000000..11e638d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.js.map b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.js.map new file mode 100644 index 0000000..c768b79 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/@tootallnate/once/dist/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.d.ts b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.d.ts new file mode 100644 index 0000000..75852fb --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.d.ts @@ -0,0 +1,43 @@ +import { EventTarget } from "event-target-shim" + +type Events = { + abort: any +} +type EventAttributes = { + onabort: any +} +/** + * The signal class. + * @see https://dom.spec.whatwg.org/#abortsignal + */ +declare class AbortSignal extends EventTarget { + /** + * AbortSignal cannot be constructed directly. + */ + constructor() + /** + * Returns `true` if this `AbortSignal`"s `AbortController` has signaled to abort, and `false` otherwise. + */ + readonly aborted: boolean +} +/** + * The AbortController. + * @see https://dom.spec.whatwg.org/#abortcontroller + */ +declare class AbortController { + /** + * Initialize this controller. + */ + constructor() + /** + * Returns the `AbortSignal` object associated with this object. + */ + readonly signal: AbortSignal + /** + * Abort and signal to any observers that the associated activity is to be aborted. + */ + abort(): void +} + +export default AbortController +export { AbortController, AbortSignal } diff --git a/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.js b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.js new file mode 100644 index 0000000..49af739 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.js @@ -0,0 +1,127 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var eventTargetShim = require('event-target-shim'); + +/** + * The signal class. + * @see https://dom.spec.whatwg.org/#abortsignal + */ +class AbortSignal extends eventTargetShim.EventTarget { + /** + * AbortSignal cannot be constructed directly. + */ + constructor() { + super(); + throw new TypeError("AbortSignal cannot be constructed directly"); + } + /** + * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. + */ + get aborted() { + const aborted = abortedFlags.get(this); + if (typeof aborted !== "boolean") { + throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); + } + return aborted; + } +} +eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort"); +/** + * Create an AbortSignal object. + */ +function createAbortSignal() { + const signal = Object.create(AbortSignal.prototype); + eventTargetShim.EventTarget.call(signal); + abortedFlags.set(signal, false); + return signal; +} +/** + * Abort a given signal. + */ +function abortSignal(signal) { + if (abortedFlags.get(signal) !== false) { + return; + } + abortedFlags.set(signal, true); + signal.dispatchEvent({ type: "abort" }); +} +/** + * Aborted flag for each instances. + */ +const abortedFlags = new WeakMap(); +// Properties should be enumerable. +Object.defineProperties(AbortSignal.prototype, { + aborted: { enumerable: true }, +}); +// `toString()` should return `"[object AbortSignal]"` +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortSignal", + }); +} + +/** + * The AbortController. + * @see https://dom.spec.whatwg.org/#abortcontroller + */ +class AbortController { + /** + * Initialize this controller. + */ + constructor() { + signals.set(this, createAbortSignal()); + } + /** + * Returns the `AbortSignal` object associated with this object. + */ + get signal() { + return getSignal(this); + } + /** + * Abort and signal to any observers that the associated activity is to be aborted. + */ + abort() { + abortSignal(getSignal(this)); + } +} +/** + * Associated signals. + */ +const signals = new WeakMap(); +/** + * Get the associated signal of a given controller. + */ +function getSignal(controller) { + const signal = signals.get(controller); + if (signal == null) { + throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); + } + return signal; +} +// Properties should be enumerable. +Object.defineProperties(AbortController.prototype, { + signal: { enumerable: true }, + abort: { enumerable: true }, +}); +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortController", + }); +} + +exports.AbortController = AbortController; +exports.AbortSignal = AbortSignal; +exports.default = AbortController; + +module.exports = AbortController +module.exports.AbortController = module.exports["default"] = AbortController +module.exports.AbortSignal = AbortSignal +//# sourceMappingURL=abort-controller.js.map diff --git a/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.js.map b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.js.map new file mode 100644 index 0000000..cfdcafd --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abort-controller.js","sources":["../src/abort-signal.ts","../src/abort-controller.ts"],"sourcesContent":["import {\n // Event,\n EventTarget,\n // Type,\n defineEventAttribute,\n} from \"event-target-shim\"\n\n// Known Limitation\n// Use `any` because the type of `AbortSignal` in `lib.dom.d.ts` is wrong and\n// to make assignable our `AbortSignal` into that.\n// https://github.com/Microsoft/TSJS-lib-generator/pull/623\ntype Events = {\n abort: any // Event & Type<\"abort\">\n}\ntype EventAttributes = {\n onabort: any // Event & Type<\"abort\">\n}\n\n/**\n * The signal class.\n * @see https://dom.spec.whatwg.org/#abortsignal\n */\nexport default class AbortSignal extends EventTarget {\n /**\n * AbortSignal cannot be constructed directly.\n */\n public constructor() {\n super()\n throw new TypeError(\"AbortSignal cannot be constructed directly\")\n }\n\n /**\n * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.\n */\n public get aborted(): boolean {\n const aborted = abortedFlags.get(this)\n if (typeof aborted !== \"boolean\") {\n throw new TypeError(\n `Expected 'this' to be an 'AbortSignal' object, but got ${\n this === null ? \"null\" : typeof this\n }`,\n )\n }\n return aborted\n }\n}\ndefineEventAttribute(AbortSignal.prototype, \"abort\")\n\n/**\n * Create an AbortSignal object.\n */\nexport function createAbortSignal(): AbortSignal {\n const signal = Object.create(AbortSignal.prototype)\n EventTarget.call(signal)\n abortedFlags.set(signal, false)\n return signal\n}\n\n/**\n * Abort a given signal.\n */\nexport function abortSignal(signal: AbortSignal): void {\n if (abortedFlags.get(signal) !== false) {\n return\n }\n\n abortedFlags.set(signal, true)\n signal.dispatchEvent<\"abort\">({ type: \"abort\" })\n}\n\n/**\n * Aborted flag for each instances.\n */\nconst abortedFlags = new WeakMap()\n\n// Properties should be enumerable.\nObject.defineProperties(AbortSignal.prototype, {\n aborted: { enumerable: true },\n})\n\n// `toString()` should return `\"[object AbortSignal]\"`\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortSignal\",\n })\n}\n","import AbortSignal, { abortSignal, createAbortSignal } from \"./abort-signal\"\n\n/**\n * The AbortController.\n * @see https://dom.spec.whatwg.org/#abortcontroller\n */\nexport default class AbortController {\n /**\n * Initialize this controller.\n */\n public constructor() {\n signals.set(this, createAbortSignal())\n }\n\n /**\n * Returns the `AbortSignal` object associated with this object.\n */\n public get signal(): AbortSignal {\n return getSignal(this)\n }\n\n /**\n * Abort and signal to any observers that the associated activity is to be aborted.\n */\n public abort(): void {\n abortSignal(getSignal(this))\n }\n}\n\n/**\n * Associated signals.\n */\nconst signals = new WeakMap()\n\n/**\n * Get the associated signal of a given controller.\n */\nfunction getSignal(controller: AbortController): AbortSignal {\n const signal = signals.get(controller)\n if (signal == null) {\n throw new TypeError(\n `Expected 'this' to be an 'AbortController' object, but got ${\n controller === null ? \"null\" : typeof controller\n }`,\n )\n }\n return signal\n}\n\n// Properties should be enumerable.\nObject.defineProperties(AbortController.prototype, {\n signal: { enumerable: true },\n abort: { enumerable: true },\n})\n\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortController\",\n })\n}\n\nexport { AbortController, AbortSignal }\n"],"names":["EventTarget","defineEventAttribute"],"mappings":";;;;;;;;;;AAkBA;;;;AAIA,MAAqB,WAAY,SAAQA,2BAAoC;;;;IAIzE;QACI,KAAK,EAAE,C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WAAW,EAAE;QAC7D,YAAY,EAAE,IAAI;QAClB,KAAK,EAAE,aAAa;KACvB,CAAC,CAAA;CACL;;ACpFD;;;;AAIA,MAAqB,eAAe;;;;IAIhC;QACI,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,iBAAiB,EAAE,CAAC,CAAA;KACzC;;;;IAKD,IAAW,MAAM;QACb,OAAO,SAAS,CAAC,IAAI,CAAC,CAAA;KACzB;;;;IAKM,KAAK;QACR,WAAW,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;KAC/B;CACJ;;;;AAKD,MAAM,OAAO,GAAG,IAAI,OAAO,EAAgC,CAAA;;;;AAK3D,SAAS,SAAS,CAAC,UAA2B;IAC1C,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAA;IACtC,IAAI,MAAM,IAAI,IAAI,EAAE;QAChB,MAAM,IAAI,SAAS,CACf,8DACI,UAAU,KAAK,IAAI,GAAG,MAAM,GAAG,OAAO,UAC1C,EAAE,CACL,CAAA;KACJ;IACD,OAAO,MAAM,CAAA;CAChB;;AAGD,MAAM,CAAC,gBAAgB,CAAC,eAAe,CAAC,SAAS,EAAE;IAC/C,MAAM,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE;IAC5B,KAAK,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE;CAC9B,CAAC,CAAA;AAEF,IAAI,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,WAAW,KAAK,QAAQ,EAAE;IACxE,MAAM,CAAC,cAAc,CAAC,eAAe,CAAC,SAAS,EAAE,MAAM,CAAC,WAAW,EAAE;QACjE,YAAY,EAAE,IAAI;QAClB,KAAK,EAAE,iBAAiB;KAC3B,CAAC,CAAA;CACL;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.mjs b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.mjs new file mode 100644 index 0000000..88ba22d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.mjs @@ -0,0 +1,118 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ +import { EventTarget, defineEventAttribute } from 'event-target-shim'; + +/** + * The signal class. + * @see https://dom.spec.whatwg.org/#abortsignal + */ +class AbortSignal extends EventTarget { + /** + * AbortSignal cannot be constructed directly. + */ + constructor() { + super(); + throw new TypeError("AbortSignal cannot be constructed directly"); + } + /** + * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. + */ + get aborted() { + const aborted = abortedFlags.get(this); + if (typeof aborted !== "boolean") { + throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); + } + return aborted; + } +} +defineEventAttribute(AbortSignal.prototype, "abort"); +/** + * Create an AbortSignal object. + */ +function createAbortSignal() { + const signal = Object.create(AbortSignal.prototype); + EventTarget.call(signal); + abortedFlags.set(signal, false); + return signal; +} +/** + * Abort a given signal. + */ +function abortSignal(signal) { + if (abortedFlags.get(signal) !== false) { + return; + } + abortedFlags.set(signal, true); + signal.dispatchEvent({ type: "abort" }); +} +/** + * Aborted flag for each instances. + */ +const abortedFlags = new WeakMap(); +// Properties should be enumerable. +Object.defineProperties(AbortSignal.prototype, { + aborted: { enumerable: true }, +}); +// `toString()` should return `"[object AbortSignal]"` +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortSignal", + }); +} + +/** + * The AbortController. + * @see https://dom.spec.whatwg.org/#abortcontroller + */ +class AbortController { + /** + * Initialize this controller. + */ + constructor() { + signals.set(this, createAbortSignal()); + } + /** + * Returns the `AbortSignal` object associated with this object. + */ + get signal() { + return getSignal(this); + } + /** + * Abort and signal to any observers that the associated activity is to be aborted. + */ + abort() { + abortSignal(getSignal(this)); + } +} +/** + * Associated signals. + */ +const signals = new WeakMap(); +/** + * Get the associated signal of a given controller. + */ +function getSignal(controller) { + const signal = signals.get(controller); + if (signal == null) { + throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); + } + return signal; +} +// Properties should be enumerable. +Object.defineProperties(AbortController.prototype, { + signal: { enumerable: true }, + abort: { enumerable: true }, +}); +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortController", + }); +} + +export default AbortController; +export { AbortController, AbortSignal }; +//# sourceMappingURL=abort-controller.mjs.map diff --git a/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.mjs.map b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.mjs.map new file mode 100644 index 0000000..1e8fa6b --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"abort-controller.mjs","sources":["../src/abort-signal.ts","../src/abort-controller.ts"],"sourcesContent":["import {\n // Event,\n EventTarget,\n // Type,\n defineEventAttribute,\n} from \"event-target-shim\"\n\n// Known Limitation\n// Use `any` because the type of `AbortSignal` in `lib.dom.d.ts` is wrong and\n// to make assignable our `AbortSignal` into that.\n// https://github.com/Microsoft/TSJS-lib-generator/pull/623\ntype Events = {\n abort: any // Event & Type<\"abort\">\n}\ntype EventAttributes = {\n onabort: any // Event & Type<\"abort\">\n}\n\n/**\n * The signal class.\n * @see https://dom.spec.whatwg.org/#abortsignal\n */\nexport default class AbortSignal extends EventTarget {\n /**\n * AbortSignal cannot be constructed directly.\n */\n public constructor() {\n super()\n throw new TypeError(\"AbortSignal cannot be constructed directly\")\n }\n\n /**\n * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.\n */\n public get aborted(): boolean {\n const aborted = abortedFlags.get(this)\n if (typeof aborted !== \"boolean\") {\n throw new TypeError(\n `Expected 'this' to be an 'AbortSignal' object, but got ${\n this === null ? \"null\" : typeof this\n }`,\n )\n }\n return aborted\n }\n}\ndefineEventAttribute(AbortSignal.prototype, \"abort\")\n\n/**\n * Create an AbortSignal object.\n */\nexport function createAbortSignal(): AbortSignal {\n const signal = Object.create(AbortSignal.prototype)\n EventTarget.call(signal)\n abortedFlags.set(signal, false)\n return signal\n}\n\n/**\n * Abort a given signal.\n */\nexport function abortSignal(signal: AbortSignal): void {\n if (abortedFlags.get(signal) !== false) {\n return\n }\n\n abortedFlags.set(signal, true)\n signal.dispatchEvent<\"abort\">({ type: \"abort\" })\n}\n\n/**\n * Aborted flag for each instances.\n */\nconst abortedFlags = new WeakMap()\n\n// Properties should be enumerable.\nObject.defineProperties(AbortSignal.prototype, {\n aborted: { enumerable: true },\n})\n\n// `toString()` should return `\"[object AbortSignal]\"`\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortSignal\",\n })\n}\n","import AbortSignal, { abortSignal, createAbortSignal } from \"./abort-signal\"\n\n/**\n * The AbortController.\n * @see https://dom.spec.whatwg.org/#abortcontroller\n */\nexport default class AbortController {\n /**\n * Initialize this controller.\n */\n public constructor() {\n signals.set(this, createAbortSignal())\n }\n\n /**\n * Returns the `AbortSignal` object associated with this object.\n */\n public get signal(): AbortSignal {\n return getSignal(this)\n }\n\n /**\n * Abort and signal to any observers that the associated activity is to be aborted.\n */\n public abort(): void {\n abortSignal(getSignal(this))\n }\n}\n\n/**\n * Associated signals.\n */\nconst signals = new WeakMap()\n\n/**\n * Get the associated signal of a given controller.\n */\nfunction getSignal(controller: AbortController): AbortSignal {\n const signal = signals.get(controller)\n if (signal == null) {\n throw new TypeError(\n `Expected 'this' to be an 'AbortController' object, but got ${\n controller === null ? \"null\" : typeof controller\n }`,\n )\n }\n return signal\n}\n\n// Properties should be enumerable.\nObject.defineProperties(AbortController.prototype, {\n signal: { enumerable: true },\n abort: { enumerable: true },\n})\n\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortController\",\n })\n}\n\nexport { AbortController, AbortSignal }\n"],"names":[],"mappings":";;;;;;AAkBA;;;;AAIA,MAAqB,WAAY,SAAQ,WAAoC;;;;IAIzE;QACI,KAAK,EAAE,CAAA;QACP,MAAM,IAAI,SAAS,CAAC,4CAA4C,CAAC,CAAA;KACpE;;;;IAKD,IAAW,OAAO;QACd,MAAM,OAAO,GAAG,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QACtC,IAAI,OAAO,OAAO,KAAK,SAAS,EAAE;YAC9B,MAAM,IAAI,SAAS,CACf,0DACI,IAAI,KAAK,IAAI,GAAG,MAAM,GAAG,OAAO,IACpC,EAAE,CACL,CAAA;SACJ;QACD,OAAO,OAAO,CAAA;KACjB;CACJ;AACD,oBAAoB,CAAC,WAAW,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;;;;AAKpD,SAAgB,iBAAiB;IAC7B,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC,SAAS,CAAC,CAAA;IACnD,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IACxB,YAAY,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;IAC/B,OAAO,MAAM,CAAA;CAChB;;;;AAKD,SAAgB,WAAW,CAAC,MAAmB;IAC3C,IAAI,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,KAAK,EAAE;QACpC,OAAM;KACT;IAED,YAAY,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;IAC9B,MAAM,CAAC,aAAa,CAAU,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAA;CACnD;;;;AAKD,MAAM,YAAY,GAAG,IAAI,OAAO,EAAwB,CAAA;;AAGxD,MAAM,CAAC,gBAAgB,CAAC,WAAW,CA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AM,CAAC,WAAW,EAAE;QACjE,YAAY,EAAE,IAAI;QAClB,KAAK,EAAE,iBAAiB;KAC3B,CAAC,CAAA;CACL;;;;;"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.umd.js b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.umd.js new file mode 100644 index 0000000..f643cfd --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/abort-controller/dist/abort-controller.umd.js @@ -0,0 +1,5 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */(function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):(a=a||self,b(a.AbortControllerShim={}))})(this,function(a){'use strict';function b(a){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},b(a)}function c(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function d(a,b){for(var c,d=0;d\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap}\n * @private\n */\nconst privateData = new WeakMap();\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap();\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event);\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n );\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n );\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true;\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault();\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n });\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true });\n\n // Define accessors\n const keys = Object.keys(event);\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key));\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget;\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this);\n\n data.stopped = true;\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation();\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this);\n\n data.stopped = true;\n data.immediateStopped = true;\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation();\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this));\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this);\n\n data.stopped = true;\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true;\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this));\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n};\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n});\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype);\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event);\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value;\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event;\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto);\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event);\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n });\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key);\n const isFunc = typeof descriptor.value === \"function\";\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n );\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto);\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);\n wrappers.set(proto, wrapper);\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nfunction wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event));\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nfunction isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nfunction setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase;\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nfunction setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget;\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nfunction setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener;\n}\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap();\n\n// Listener types\nconst CAPTURE = 1;\nconst BUBBLE = 2;\nconst ATTRIBUTE = 3;\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget);\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this);\n let node = listeners.get(eventName);\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next;\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null; // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this);\n\n // Traverse to the tail while removing old value.\n let prev = null;\n let node = listeners.get(eventName);\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next;\n } else if (node.next !== null) {\n listeners.set(eventName, node.next);\n } else {\n listeners.delete(eventName);\n }\n } else {\n prev = node;\n }\n\n node = node.next;\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n };\n if (prev === null) {\n listeners.set(eventName, newNode);\n } else {\n prev.next = newNode;\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n );\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this);\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n });\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map());\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length);\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i];\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this);\n const optionsIsObj = isObject(options);\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options);\n const listenerType = capture ? CAPTURE : BUBBLE;\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n };\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName);\n if (node === undefined) {\n listeners.set(eventName, newNode);\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null;\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node;\n node = node.next;\n }\n\n // Add it.\n prev.next = newNode;\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this);\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options);\n const listenerType = capture ? CAPTURE : BUBBLE;\n\n let prev = null;\n let node = listeners.get(eventName);\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next;\n } else if (node.next !== null) {\n listeners.set(eventName, node.next);\n } else {\n listeners.delete(eventName);\n }\n return\n }\n\n prev = node;\n node = node.next;\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this);\n const eventName = event.type;\n let node = listeners.get(eventName);\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event);\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null;\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next;\n } else if (node.next !== null) {\n listeners.set(eventName, node.next);\n } else {\n listeners.delete(eventName);\n }\n } else {\n prev = node;\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n );\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent);\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err);\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent);\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next;\n }\n setPassiveListener(wrappedEvent, null);\n setEventPhase(wrappedEvent, 0);\n setCurrentTarget(wrappedEvent, null);\n\n return !wrappedEvent.defaultPrevented\n },\n};\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n});\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);\n}\n\nexport default EventTarget;\nexport { defineEventAttribute, EventTarget };\n//# sourceMappingURL=event-target-shim.mjs.map\n","import {\n // Event,\n EventTarget,\n // Type,\n defineEventAttribute,\n} from \"event-target-shim\"\n\n// Known Limitation\n// Use `any` because the type of `AbortSignal` in `lib.dom.d.ts` is wrong and\n// to make assignable our `AbortSignal` into that.\n// https://github.com/Microsoft/TSJS-lib-generator/pull/623\ntype Events = {\n abort: any // Event & Type<\"abort\">\n}\ntype EventAttributes = {\n onabort: any // Event & Type<\"abort\">\n}\n\n/**\n * The signal class.\n * @see https://dom.spec.whatwg.org/#abortsignal\n */\nexport default class AbortSignal extends EventTarget {\n /**\n * AbortSignal cannot be constructed directly.\n */\n public constructor() {\n super()\n throw new TypeError(\"AbortSignal cannot be constructed directly\")\n }\n\n /**\n * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.\n */\n public get aborted(): boolean {\n const aborted = abortedFlags.get(this)\n if (typeof aborted !== \"boolean\") {\n throw new TypeError(\n `Expected 'this' to be an 'AbortSignal' object, but got ${\n this === null ? \"null\" : typeof this\n }`,\n )\n }\n return aborted\n }\n}\ndefineEventAttribute(AbortSignal.prototype, \"abort\")\n\n/**\n * Create an AbortSignal object.\n */\nexport function createAbortSignal(): AbortSignal {\n const signal = Object.create(AbortSignal.prototype)\n EventTarget.call(signal)\n abortedFlags.set(signal, false)\n return signal\n}\n\n/**\n * Abort a given signal.\n */\nexport function abortSignal(signal: AbortSignal): void {\n if (abortedFlags.get(signal) !== false) {\n return\n }\n\n abortedFlags.set(signal, true)\n signal.dispatchEvent<\"abort\">({ type: \"abort\" })\n}\n\n/**\n * Aborted flag for each instances.\n */\nconst abortedFlags = new WeakMap()\n\n// Properties should be enumerable.\nObject.defineProperties(AbortSignal.prototype, {\n aborted: { enumerable: true },\n})\n\n// `toString()` should return `\"[object AbortSignal]\"`\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortSignal\",\n })\n}\n","import AbortSignal, { abortSignal, createAbortSignal } from \"./abort-signal\"\n\n/**\n * The AbortController.\n * @see https://dom.spec.whatwg.org/#abortcontroller\n */\nexport default class AbortController {\n /**\n * Initialize this controller.\n */\n public constructor() {\n signals.set(this, createAbortSignal())\n }\n\n /**\n * Returns the `AbortSignal` object associated with this object.\n */\n public get signal(): AbortSignal {\n return getSignal(this)\n }\n\n /**\n * Abort and signal to any observers that the associated activity is to be aborted.\n */\n public abort(): void {\n abortSignal(getSignal(this))\n }\n}\n\n/**\n * Associated signals.\n */\nconst signals = new WeakMap()\n\n/**\n * Get the associated signal of a given controller.\n */\nfunction getSignal(controller: AbortController): AbortSignal {\n const signal = signals.get(controller)\n if (signal == null) {\n throw new TypeError(\n `Expected 'this' to be an 'AbortController' object, but got ${\n controller === null ? \"null\" : typeof controller\n }`,\n )\n }\n return signal\n}\n\n// Properties should be enumerable.\nObject.defineProperties(AbortController.prototype, {\n signal: { enumerable: true },\n abort: { enumerable: true },\n})\n\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortController\",\n })\n}\n\nexport { AbortController, AbortSignal }\n"],"names":["pd","event","retv","privateData","get","console","assert","setCancelFlag","data","passiveListener","cancelable","canceled","preventDefault","error","Event","eventTarget","set","eventPhase","currentTarget","stopped","immediateStopped","timeStamp","Date","now","Object","defineProperty","value","enumerable","key","keys","i","length","defineRedirectDescriptor","configurable","defineCallDescriptor","apply","arguments","defineWrapper","BaseEvent","proto","CustomEvent","call","prototype","create","constructor","writable","descriptor","getOwnPropertyDescriptor","isFunc","getWrapper","wrapper","wrappers","getPrototypeOf","wrapEvent","Wrapper","isStopped","setEventPhase","setCurrentTarget","setPassiveListener","createAbortSignal","signal","AbortSignal","EventTarget","abortedFlags","abortSignal","dispatchEvent","type","getSignal","controller","signals","TypeError","WeakMap","target","composedPath","NONE","CAPTURING_PHASE","AT_TARGET","BUBBLING_PHASE","stopPropagation","stopImmediatePropagation","bubbles","defaultPrevented","composed","srcElement","cancelBubble","returnValue","initEvent","window","setPrototypeOf","aborted","defineEventAttribute","defineProperties","Symbol","_typeof","toStringTag","AbortController","abort"],"mappings":";;;+3CAkCA,QAASA,CAAAA,CAAT,CAAYC,CAAZ,CAAmB,IACTC,CAAAA,CAAI,CAAGC,CAAW,CAACC,GAAZ,CAAgBH,CAAhB,QACbI,CAAAA,OAAO,CAACC,MAAR,CACY,IAAR,EAAAJ,CADJ,CAEI,6CAFJ,CAGID,CAHJ,EAKOC,EAOX,QAASK,CAAAA,CAAT,CAAuBC,CAAvB,CAA6B,OACG,KAAxB,EAAAA,CAAI,CAACC,eADgB,MAarB,CAACD,CAAI,CAACP,KAAL,CAAWS,UAbS,GAiBzBF,CAAI,CAACG,QAAL,GAjByB,CAkBgB,UAArC,QAAOH,CAAAA,CAAI,CAACP,KAAL,CAAWW,cAlBG,EAmBrBJ,CAAI,CAACP,KAAL,CAAWW,cAAX,EAnBqB,QAGE,WAAnB,QAAOP,CAAAA,OAAP,EACyB,UAAzB,QAAOA,CAAAA,OAAO,CAACQ,KAJE,EAMjBR,OAAO,CAACQ,KAAR,CACI,oEADJ,CAEIL,CAAI,CAACC,eAFT,CANiB,EAiC7B,QAASK,CAAAA,CAAT,CAAeC,CAAf,CAA4Bd,CAA5B,CAAmC,CAC/BE,CAAW,CAACa,GAAZ,CAAgB,IAAhB,CAAsB,CAClBD,WAAW,CAAXA,CADkB,CAElBd,KAAK,CAALA,CAFkB,CAGlBgB,UAAU,CAAE,CAHM,CAIlBC,aAAa,CAAEH,CAJG,CAKlBJ,QAAQ,GALU,CAMlBQ,OAAO,GANW,CAOlBC,gBAAgB,GAPE,CAQlBX,eAAe,CAAE,IARC,CASlBY,SAAS,CAAEpB,CAAK,CAACoB,SAAN,EAAmBC,IAAI,CAACC,GAAL,EATZ,CAAtB,CAD+B,CAc/BC,MAAM,CAACC,cAAP,CAAsB,IAAtB,CAA4B,WAA5B,CAAyC,CAAEC,KAAK,GAAP,CAA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H,EAKsB,UAAlB,QAAOoE,CAAAA,MAAP,EAA8D,QAA9B,GAAAC,EAAOD,MAAM,CAACE,cAC9CtE,MAAM,CAACC,cAAPD,CAAsBuE,CAAe,CAACrD,SAAtClB,CAAiDoE,MAAM,CAACE,WAAxDtE,CAAqE,CACjES,YAAY,GADqD,CAEjEP,KAAK,CAAE,iBAF0D,CAArEF"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.d.ts b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.d.ts new file mode 100644 index 0000000..bc4ab74 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.d.ts @@ -0,0 +1,78 @@ +/// +import net from 'net'; +import http from 'http'; +import https from 'https'; +import { Duplex } from 'stream'; +import { EventEmitter } from 'events'; +declare function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent; +declare function createAgent(callback: createAgent.AgentCallback, opts?: createAgent.AgentOptions): createAgent.Agent; +declare namespace createAgent { + interface ClientRequest extends http.ClientRequest { + _last?: boolean; + _hadError?: boolean; + method: string; + } + interface AgentRequestOptions { + host?: string; + path?: string; + port: number; + } + interface HttpRequestOptions extends AgentRequestOptions, Omit { + secureEndpoint: false; + } + interface HttpsRequestOptions extends AgentRequestOptions, Omit { + secureEndpoint: true; + } + type RequestOptions = HttpRequestOptions | HttpsRequestOptions; + type AgentLike = Pick | http.Agent; + type AgentCallbackReturn = Duplex | AgentLike; + type AgentCallbackCallback = (err?: Error | null, socket?: createAgent.AgentCallbackReturn) => void; + type AgentCallbackPromise = (req: createAgent.ClientRequest, opts: createAgent.RequestOptions) => createAgent.AgentCallbackReturn | Promise; + type AgentCallback = typeof Agent.prototype.callback; + type AgentOptions = { + timeout?: number; + }; + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends EventEmitter { + timeout: number | null; + maxFreeSockets: number; + maxTotalSockets: number; + maxSockets: number; + sockets: { + [key: string]: net.Socket[]; + }; + freeSockets: { + [key: string]: net.Socket[]; + }; + requests: { + [key: string]: http.IncomingMessage[]; + }; + options: https.AgentOptions; + private promisifiedCallback?; + private explicitDefaultPort?; + private explicitProtocol?; + constructor(callback?: createAgent.AgentCallback | createAgent.AgentOptions, _opts?: createAgent.AgentOptions); + get defaultPort(): number; + set defaultPort(v: number); + get protocol(): string; + set protocol(v: string); + callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions, fn: createAgent.AgentCallbackCallback): void; + callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions): createAgent.AgentCallbackReturn | Promise; + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req: ClientRequest, _opts: RequestOptions): void; + freeSocket(socket: net.Socket, opts: AgentOptions): void; + destroy(): void; + } +} +export = createAgent; diff --git a/software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.js b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.js new file mode 100644 index 0000000..bfd9e22 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.js @@ -0,0 +1,203 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const events_1 = require("events"); +const debug_1 = __importDefault(require("debug")); +const promisify_1 = __importDefault(require("./promisify")); +const debug = debug_1.default('agent-base'); +function isAgent(v) { + return Boolean(v) && typeof v.addRequest === 'function'; +} +function isSecureEndpoint() { + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} +function createAgent(callback, opts) { + return new createAgent.Agent(callback, opts); +} +(function (createAgent) { + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends events_1.EventEmitter { + constructor(callback, _opts) { + super(); + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } + else if (callback) { + opts = callback; + } + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + get defaultPort() { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + set defaultPort(v) { + this.explicitDefaultPort = v; + } + get protocol() { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + set protocol(v) { + this.explicitProtocol = v; + } + callback(req, opts, fn) { + throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); + } + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req, _opts) { + const opts = Object.assign({}, _opts); + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + if (opts.host == null) { + opts.host = 'localhost'; + } + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + let timedOut = false; + let timeoutId = null; + const timeoutMs = opts.timeout || this.timeout; + const onerror = (err) => { + if (req._hadError) + return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); + err.code = 'ETIMEOUT'; + onerror(err); + }; + const callbackError = (err) => { + if (timedOut) + return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + const onsocket = (socket) => { + if (timedOut) + return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug('Callback returned another Agent instance %o', socket.constructor.name); + socket.addRequest(req, opts); + return; + } + if (socket) { + socket.once('free', () => { + this.freeSocket(socket, opts); + }); + req.onSocket(socket); + return; + } + const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); + onerror(err); + }; + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify_1.default(this.callback); + } + else { + this.promisifiedCallback = this.callback; + } + } + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + try { + debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); + Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + } + catch (err) { + Promise.reject(err).catch(callbackError); + } + } + freeSocket(socket, opts) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + createAgent.Agent = Agent; + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +})(createAgent || (createAgent = {})); +module.exports = createAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.js.map b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.js.map new file mode 100644 index 0000000..bd118ab --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;AAIA,mCAAsC;AACtC,kDAAgC;AAChC,4DAAoC;AAEpC,MAAM,KAAK,GAAG,eAAW,CAAC,YAAY,CAAC,CAAC;AAExC,SAAS,OAAO,CAAC,CAAM;IACtB,OAAO,OAAO,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC;AACzD,CAAC;AAED,SAAS,gBAAgB;IACxB,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,KAAK,EAAE,CAAC;IAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC5C,OAAO,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,IAAK,CAAC,CAAC,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACxG,CAAC;AAOD,SAAS,WAAW,CACnB,QAA+D,EAC/D,IAA+B;IAE/B,OAAO,IAAI,WAAW,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AAC9C,CAAC;AAED,WAAU,WAAW;IAmDpB;;;;;;OAMG;IACH,MAAa,KAAM,SAAQ,qBAAY;QAmBtC,YACC,QAA+D,EAC/D,KAAgC;YAEhC,KAAK,EAAE,CAAC;YAER,IAAI,IAAI,GAAG,KAAK,CAAC;YACjB,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;gBACnC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;aACzB;iBAAM,IAAI,QAAQ,EAAE;gBACpB,IAAI,GAAG,QAAQ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GAAG,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,IAAI,EAAE,CAC3B,CAAC;gBACF,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CACxD,QAAQ,EACR,aAAa,CACb,CAAC;aACF;YAAC,OAAO,GAAG,EAAE;gBACb,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;aACzC;QACF,CAAC;QAED,UAAU,CAAC,MAAkB,EAAE,IAAkB;YAChD,KAAK,CAAC,sBAAsB,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAC7D,MAAM,CAAC,OAAO,EAAE,CAAC;QAClB,CAAC;QAED,OAAO;YACN,KAAK,CAAC,qBAAqB,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QACrD,CAAC;KACD;IAxPY,iBAAK,QAwPjB,CAAA;IAED,uCAAuC;IACvC,WAAW,CAAC,SAAS,GAAG,WAAW,CAAC,KAAK,CAAC,SAAS,CAAC;AACrD,CAAC,EAtTS,WAAW,KAAX,WAAW,QAsTpB;AAED,iBAAS,WAAW,CAAC"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.d.ts b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.d.ts new file mode 100644 index 0000000..0268869 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.d.ts @@ -0,0 +1,4 @@ +import { ClientRequest, RequestOptions, AgentCallbackCallback, AgentCallbackPromise } from './index'; +declare type LegacyCallback = (req: ClientRequest, opts: RequestOptions, fn: AgentCallbackCallback) => void; +export default function promisify(fn: LegacyCallback): AgentCallbackPromise; +export {}; diff --git a/software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.js b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.js new file mode 100644 index 0000000..b2f6132 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function promisify(fn) { + return function (req, opts) { + return new Promise((resolve, reject) => { + fn.call(this, req, opts, (err, rtn) => { + if (err) { + reject(err); + } + else { + resolve(rtn); + } + }); + }); + }; +} +exports.default = promisify; +//# sourceMappingURL=promisify.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.js.map b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.js.map new file mode 100644 index 0000000..4bff9bf --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/agent-base/dist/src/promisify.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promisify.js","sourceRoot":"","sources":["../../src/promisify.ts"],"names":[],"mappings":";;AAeA,SAAwB,SAAS,CAAC,EAAkB;IACnD,OAAO,UAAsB,GAAkB,EAAE,IAAoB;QACpE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACtC,EAAE,CAAC,IAAI,CACN,IAAI,EACJ,GAAG,EACH,IAAI,EACJ,CAAC,GAA6B,EAAE,GAAyB,EAAE,EAAE;gBAC5D,IAAI,GAAG,EAAE;oBACR,MAAM,CAAC,GAAG,CAAC,CAAC;iBACZ;qBAAM;oBACN,OAAO,CAAC,GAAG,CAAC,CAAC;iBACb;YACF,CAAC,CACD,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC;AAjBD,4BAiBC"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/diff/dist/diff.js b/software/flow/node_modules/npm/node_modules/diff/dist/diff.js new file mode 100644 index 0000000..7fa3a55 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/diff/dist/diff.js @@ -0,0 +1,1627 @@ +/*! + + diff v5.1.0 + +Software License Agreement (BSD License) + +Copyright (c) 2009-2015, Kevin Decker + +All rights reserved. + +Redistribution and use of this software in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the + following disclaimer in the documentation and/or other + materials provided with the distribution. + +* Neither the name of Kevin Decker nor the names of its + contributors may be used to endorse or promote products + derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +@license +*/ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.Diff = {})); +}(this, (function (exports) { 'use strict'; + + function Diff() {} + Diff.prototype = { + diff: function diff(oldString, newString) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + + if (options.maxEditLength) { + maxEditLength = Math.min(maxEditLength, options.maxEditLength); + } + + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = void 0; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced, or until the edit length exceeds options.maxEditLength (if given), + // in which case it will return undefined. + + + if (callback) { + (function exec() { + setTimeout(function () { + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return value.split(''); + }, + join: function join(chars) { + return chars.join(''); + } + }; + + function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; + } + + function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; + } + + var characterDiff = new Diff(); + function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); + } + + function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; + } + + // + // Ranges and exceptions: + // Latin-1 Supplement, 0080–00FF + // - U+00D7 × Multiplication sign + // - U+00F7 ÷ Division sign + // Latin Extended-A, 0100–017F + // Latin Extended-B, 0180–024F + // IPA Extensions, 0250–02AF + // Spacing Modifier Letters, 02B0–02FF + // - U+02C7 ˇ ˇ Caron + // - U+02D8 ˘ ˘ Breve + // - U+02D9 ˙ ˙ Dot Above + // - U+02DA ˚ ˚ Ring Above + // - U+02DB ˛ ˛ Ogonek + // - U+02DC ˜ ˜ Small Tilde + // - U+02DD ˝ ˝ Double Acute Accent + // Latin Extended Additional, 1E00–1EFF + + var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; + var reWhitespace = /\S/; + var wordDiff = new Diff(); + + wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); + }; + + wordDiff.tokenize = function (value) { + // All whitespace symbols except newline group into one token, each newline - in separate token + var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; + }; + + function diffWords(oldStr, newStr, options) { + options = generateOptions(options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); + } + function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); + } + + var lineDiff = new Diff(); + + lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; + }; + + function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); + } + function diffTrimmedLines(oldStr, newStr, callback) { + var options = generateOptions(callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); + } + + var sentenceDiff = new Diff(); + + sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); + }; + + function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); + } + + var cssDiff = new Diff(); + + cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); + }; + + function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); + } + + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); + } + + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); + } + + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); + } + + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); + } + + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); + } + + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + + return arr2; + } + + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var objectPrototypeToString = Object.prototype.toString; + var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a + // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + + jsonDiff.useLongestToken = true; + jsonDiff.tokenize = lineDiff.tokenize; + + jsonDiff.castInput = function (value) { + var _this$options = this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { + return typeof v === 'undefined' ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); + }; + + jsonDiff.equals = function (left, right) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); + }; + + function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); + } // This function handles the presence of circular references by bailing out when encountering an + // object that is already on the "stack" of items being processed. Accepts an optional replacer + + function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if (_typeof(obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; + } + + var arrayDiff = new Diff(); + + arrayDiff.tokenize = function (value) { + return value.slice(); + }; + + arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; + }; + + function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); + } + + function parsePatch(uniDiff) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + + if (header) { + index.index = header[1]; + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); + + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + var data = fileHeader[2].split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (/^".*"$/.test(fileName)) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], + newStart: +chunkHeader[3], + newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], + lines: [], + linedelimiters: [] + }; // Unified Diff Format quirk: If the chunk size is 0, + // the first number is one lower than one would expect. + // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 + + if (hunk.oldLines === 0) { + hunk.oldStart += 1; + } + + if (hunk.newLines === 0) { + hunk.newStart += 1; + } + + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; + } + + // Iterator that traverses in the range of [min, max], stepping + // by distance from a given start position. I.e. for [0, 4], with + // start of 2, this will iterate 2, 3, 1, 4, 0. + function distanceIterator (start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; + } + + function applyPatch(source, uniDiff) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { + return line === patchContent; + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = distanceIterator(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); + } // Wrapper that supports multiple file patches via callbacks. + + function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); + } + + function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = diffLines(oldStr, newStr, options); + + if (!diff) { + return; + } + + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + var _loop = function _loop(i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + var _curRange; + + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + var _curRange2; + + // Overlapping + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; + + // end the range and output + var contextSize = Math.min(lines.length, options.context); + + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + // however, if the old file is empty, do not output the no-nl line + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + _loop(i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; + } + function formatPatch(diff) { + var ret = []; + + if (diff.oldFileName == diff.newFileName) { + ret.push('Index: ' + diff.oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, + // the first number is one lower than one would expect. + // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 + + if (hunk.oldLines === 0) { + hunk.oldStart -= 1; + } + + if (hunk.newLines === 0) { + hunk.newStart -= 1; + } + + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; + } + function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); + } + function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); + } + + function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); + } + function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; + } + + function calcLineCount(hunk) { + var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } + } + function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; + } + + function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return parsePatch(param)[0]; + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return structuredPatch(undefined, undefined, base, param); + } + + return param; + } + + function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; + } + + function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } + } + + function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; + } + + function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; + } + + function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + var _hunk$lines; + + // Mine inserted + (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + var _hunk$lines2; + + // Theirs inserted + (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); + } + + function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + var _hunk$lines3; + + (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); + + return; + } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + var _hunk$lines4; + + (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); + + return; + } + } else if (arrayEqual(myChanges, theirChanges)) { + var _hunk$lines5; + + (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); + } + + function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + var _hunk$lines6; + + (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } + } + + function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); + } + + function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } + } + + function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } + } + + function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; + } + + function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; + } + + function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); + } + + function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; + } + + function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; + } + + // See: http://code.google.com/p/google-diff-match-patch/wiki/API + function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; + } + + function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); + } + + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; + } + + exports.Diff = Diff; + exports.applyPatch = applyPatch; + exports.applyPatches = applyPatches; + exports.canonicalize = canonicalize; + exports.convertChangesToDMP = convertChangesToDMP; + exports.convertChangesToXML = convertChangesToXML; + exports.createPatch = createPatch; + exports.createTwoFilesPatch = createTwoFilesPatch; + exports.diffArrays = diffArrays; + exports.diffChars = diffChars; + exports.diffCss = diffCss; + exports.diffJson = diffJson; + exports.diffLines = diffLines; + exports.diffSentences = diffSentences; + exports.diffTrimmedLines = diffTrimmedLines; + exports.diffWords = diffWords; + exports.diffWordsWithSpace = diffWordsWithSpace; + exports.merge = merge; + exports.parsePatch = parsePatch; + exports.structuredPatch = structuredPatch; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); diff --git a/software/flow/node_modules/npm/node_modules/diff/dist/diff.min.js b/software/flow/node_modules/npm/node_modules/diff/dist/diff.min.js new file mode 100644 index 0000000..80c20de --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/diff/dist/diff.min.js @@ -0,0 +1,38 @@ +/*! + + diff v5.1.0 + +Software License Agreement (BSD License) + +Copyright (c) 2009-2015, Kevin Decker + +All rights reserved. + +Redistribution and use of this software in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the + following disclaimer in the documentation and/or other + materials provided with the distribution. + +* Neither the name of Kevin Decker nor the names of its + contributors may be used to endorse or promote products + derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +@license +*/ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e=e||self).Diff={})}(this,function(e){"use strict";function t(){}t.prototype={diff:function(u,a,e){var n=2=c&&h<=i+1)return d([{value:this.join(a),count:a.length}]);function o(){for(var e,n=-1*p;n<=p;n+=2){var t=void 0,r=v[n-1],i=v[n+1],o=(i?i.newPos:0)-n;r&&(v[n-1]=void 0);var l=r&&r.newPos+1=c&&h<=o+1)return d(function(e,n,t,r,i){for(var o=0,l=n.length,s=0,u=0;oe.length?t:e}),d.value=e.join(f)):d.value=e.join(t.slice(s,s+d.count)),s+=d.count,d.added||(u+=d.count))}var c=n[l-1];1e.length)&&(n=e.length);for(var t=0,r=new Array(n);t=c.length-2&&u.length<=d.context&&(i=/\n$/.test(a),o=/\n$/.test(f),l=0==u.length&&g.length>r.oldLines,!i&&l&&0e.length)return!1;for(var t=0;t"):i.removed&&t.push(""),t.push((n=i.value,n.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""))),i.added?t.push(""):i.removed&&t.push("")}return t.join("")},e.createPatch=function(e,n,t,r,i,o){return y(e,e,n,t,r,i,o)},e.createTwoFilesPatch=y,e.diffArrays=function(e,n,t){return g.diff(e,n,t)},e.diffChars=function(e,n,t){return r.diff(e,n,t)},e.diffCss=function(e,n,t){return f.diff(e,n,t)},e.diffJson=function(e,n,t){return p.diff(e,n,t)},e.diffLines=L,e.diffSentences=function(e,n,t){return a.diff(e,n,t)},e.diffTrimmedLines=function(e,n,t){var r=i(t,{ignoreWhitespace:!0});return u.diff(e,n,r)},e.diffWords=function(e,n,t){return t=i(t,{ignoreWhitespace:!0}),s.diff(e,n,t)},e.diffWordsWithSpace=function(e,n,t){return s.diff(e,n,t)},e.merge=function(e,n,t){e=b(e,t),n=b(n,t);var r={};(e.index||n.index)&&(r.index=e.index||n.index),(e.newFileName||n.newFileName)&&(F(e)?F(n)?(r.oldFileName=N(r,e.oldFileName,n.oldFileName),r.newFileName=N(r,e.newFileName,n.newFileName),r.oldHeader=N(r,e.oldHeader,n.oldHeader),r.newHeader=N(r,e.newHeader,n.newHeader)):(r.oldFileName=e.oldFileName,r.newFileName=e.newFileName,r.oldHeader=e.oldHeader,r.newHeader=e.newHeader):(r.oldFileName=n.oldFileName||e.oldFileName,r.newFileName=n.newFileName||e.newFileName,r.oldHeader=n.oldHeader||e.oldHeader,r.newHeader=n.newHeader||e.newHeader)),r.hunks=[];for(var i=0,o=0,l=0,s=0;i + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +/** + * @typedef {object} PrivateData + * @property {EventTarget} eventTarget The event target. + * @property {{type:string}} event The original event object. + * @property {number} eventPhase The current event phase. + * @property {EventTarget|null} currentTarget The current event target. + * @property {boolean} canceled The flag to prevent default. + * @property {boolean} stopped The flag to stop propagation. + * @property {boolean} immediateStopped The flag to stop propagation immediately. + * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. + * @property {number} timeStamp The unix time. + * @private + */ + +/** + * Private data for event wrappers. + * @type {WeakMap} + * @private + */ +const privateData = new WeakMap(); + +/** + * Cache for wrapper classes. + * @type {WeakMap} + * @private + */ +const wrappers = new WeakMap(); + +/** + * Get private data. + * @param {Event} event The event object to get private data. + * @returns {PrivateData} The private data of the event. + * @private + */ +function pd(event) { + const retv = privateData.get(event); + console.assert( + retv != null, + "'this' is expected an Event object, but got", + event + ); + return retv +} + +/** + * https://dom.spec.whatwg.org/#set-the-canceled-flag + * @param data {PrivateData} private data. + */ +function setCancelFlag(data) { + if (data.passiveListener != null) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error( + "Unable to preventDefault inside passive event listener invocation.", + data.passiveListener + ); + } + return + } + if (!data.event.cancelable) { + return + } + + data.canceled = true; + if (typeof data.event.preventDefault === "function") { + data.event.preventDefault(); + } +} + +/** + * @see https://dom.spec.whatwg.org/#interface-event + * @private + */ +/** + * The event wrapper. + * @constructor + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Event|{type:string}} event The original event to wrap. + */ +function Event(eventTarget, event) { + privateData.set(this, { + eventTarget, + event, + eventPhase: 2, + currentTarget: eventTarget, + canceled: false, + stopped: false, + immediateStopped: false, + passiveListener: null, + timeStamp: event.timeStamp || Date.now(), + }); + + // https://heycam.github.io/webidl/#Unforgeable + Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); + + // Define accessors + const keys = Object.keys(event); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in this)) { + Object.defineProperty(this, key, defineRedirectDescriptor(key)); + } + } +} + +// Should be enumerable, but class methods are not enumerable. +Event.prototype = { + /** + * The type of this event. + * @type {string} + */ + get type() { + return pd(this).event.type + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get target() { + return pd(this).eventTarget + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get currentTarget() { + return pd(this).currentTarget + }, + + /** + * @returns {EventTarget[]} The composed path of this event. + */ + composedPath() { + const currentTarget = pd(this).currentTarget; + if (currentTarget == null) { + return [] + } + return [currentTarget] + }, + + /** + * Constant of NONE. + * @type {number} + */ + get NONE() { + return 0 + }, + + /** + * Constant of CAPTURING_PHASE. + * @type {number} + */ + get CAPTURING_PHASE() { + return 1 + }, + + /** + * Constant of AT_TARGET. + * @type {number} + */ + get AT_TARGET() { + return 2 + }, + + /** + * Constant of BUBBLING_PHASE. + * @type {number} + */ + get BUBBLING_PHASE() { + return 3 + }, + + /** + * The target of this event. + * @type {number} + */ + get eventPhase() { + return pd(this).eventPhase + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopPropagation() { + const data = pd(this); + + data.stopped = true; + if (typeof data.event.stopPropagation === "function") { + data.event.stopPropagation(); + } + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopImmediatePropagation() { + const data = pd(this); + + data.stopped = true; + data.immediateStopped = true; + if (typeof data.event.stopImmediatePropagation === "function") { + data.event.stopImmediatePropagation(); + } + }, + + /** + * The flag to be bubbling. + * @type {boolean} + */ + get bubbles() { + return Boolean(pd(this).event.bubbles) + }, + + /** + * The flag to be cancelable. + * @type {boolean} + */ + get cancelable() { + return Boolean(pd(this).event.cancelable) + }, + + /** + * Cancel this event. + * @returns {void} + */ + preventDefault() { + setCancelFlag(pd(this)); + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + */ + get defaultPrevented() { + return pd(this).canceled + }, + + /** + * The flag to be composed. + * @type {boolean} + */ + get composed() { + return Boolean(pd(this).event.composed) + }, + + /** + * The unix time of this event. + * @type {number} + */ + get timeStamp() { + return pd(this).timeStamp + }, + + /** + * The target of this event. + * @type {EventTarget} + * @deprecated + */ + get srcElement() { + return pd(this).eventTarget + }, + + /** + * The flag to stop event bubbling. + * @type {boolean} + * @deprecated + */ + get cancelBubble() { + return pd(this).stopped + }, + set cancelBubble(value) { + if (!value) { + return + } + const data = pd(this); + + data.stopped = true; + if (typeof data.event.cancelBubble === "boolean") { + data.event.cancelBubble = true; + } + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + * @deprecated + */ + get returnValue() { + return !pd(this).canceled + }, + set returnValue(value) { + if (!value) { + setCancelFlag(pd(this)); + } + }, + + /** + * Initialize this event object. But do nothing under event dispatching. + * @param {string} type The event type. + * @param {boolean} [bubbles=false] The flag to be possible to bubble up. + * @param {boolean} [cancelable=false] The flag to be possible to cancel. + * @deprecated + */ + initEvent() { + // Do nothing. + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(Event.prototype, "constructor", { + value: Event, + configurable: true, + writable: true, +}); + +// Ensure `event instanceof window.Event` is `true`. +if (typeof window !== "undefined" && typeof window.Event !== "undefined") { + Object.setPrototypeOf(Event.prototype, window.Event.prototype); + + // Make association for wrappers. + wrappers.set(window.Event.prototype, Event); +} + +/** + * Get the property descriptor to redirect a given property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to redirect the property. + * @private + */ +function defineRedirectDescriptor(key) { + return { + get() { + return pd(this).event[key] + }, + set(value) { + pd(this).event[key] = value; + }, + configurable: true, + enumerable: true, + } +} + +/** + * Get the property descriptor to call a given method property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to call the method property. + * @private + */ +function defineCallDescriptor(key) { + return { + value() { + const event = pd(this).event; + return event[key].apply(event, arguments) + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define new wrapper class. + * @param {Function} BaseEvent The base wrapper class. + * @param {Object} proto The prototype of the original event. + * @returns {Function} The defined wrapper class. + * @private + */ +function defineWrapper(BaseEvent, proto) { + const keys = Object.keys(proto); + if (keys.length === 0) { + return BaseEvent + } + + /** CustomEvent */ + function CustomEvent(eventTarget, event) { + BaseEvent.call(this, eventTarget, event); + } + + CustomEvent.prototype = Object.create(BaseEvent.prototype, { + constructor: { value: CustomEvent, configurable: true, writable: true }, + }); + + // Define accessors. + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in BaseEvent.prototype)) { + const descriptor = Object.getOwnPropertyDescriptor(proto, key); + const isFunc = typeof descriptor.value === "function"; + Object.defineProperty( + CustomEvent.prototype, + key, + isFunc + ? defineCallDescriptor(key) + : defineRedirectDescriptor(key) + ); + } + } + + return CustomEvent +} + +/** + * Get the wrapper class of a given prototype. + * @param {Object} proto The prototype of the original event to get its wrapper. + * @returns {Function} The wrapper class. + * @private + */ +function getWrapper(proto) { + if (proto == null || proto === Object.prototype) { + return Event + } + + let wrapper = wrappers.get(proto); + if (wrapper == null) { + wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); + wrappers.set(proto, wrapper); + } + return wrapper +} + +/** + * Wrap a given event to management a dispatching. + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Object} event The event to wrap. + * @returns {Event} The wrapper instance. + * @private + */ +function wrapEvent(eventTarget, event) { + const Wrapper = getWrapper(Object.getPrototypeOf(event)); + return new Wrapper(eventTarget, event) +} + +/** + * Get the immediateStopped flag of a given event. + * @param {Event} event The event to get. + * @returns {boolean} The flag to stop propagation immediately. + * @private + */ +function isStopped(event) { + return pd(event).immediateStopped +} + +/** + * Set the current event phase of a given event. + * @param {Event} event The event to set current target. + * @param {number} eventPhase New event phase. + * @returns {void} + * @private + */ +function setEventPhase(event, eventPhase) { + pd(event).eventPhase = eventPhase; +} + +/** + * Set the current target of a given event. + * @param {Event} event The event to set current target. + * @param {EventTarget|null} currentTarget New current target. + * @returns {void} + * @private + */ +function setCurrentTarget(event, currentTarget) { + pd(event).currentTarget = currentTarget; +} + +/** + * Set a passive listener of a given event. + * @param {Event} event The event to set current target. + * @param {Function|null} passiveListener New passive listener. + * @returns {void} + * @private + */ +function setPassiveListener(event, passiveListener) { + pd(event).passiveListener = passiveListener; +} + +/** + * @typedef {object} ListenerNode + * @property {Function} listener + * @property {1|2|3} listenerType + * @property {boolean} passive + * @property {boolean} once + * @property {ListenerNode|null} next + * @private + */ + +/** + * @type {WeakMap>} + * @private + */ +const listenersMap = new WeakMap(); + +// Listener types +const CAPTURE = 1; +const BUBBLE = 2; +const ATTRIBUTE = 3; + +/** + * Check whether a given value is an object or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an object. + */ +function isObject(x) { + return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax +} + +/** + * Get listeners. + * @param {EventTarget} eventTarget The event target to get. + * @returns {Map} The listeners. + * @private + */ +function getListeners(eventTarget) { + const listeners = listenersMap.get(eventTarget); + if (listeners == null) { + throw new TypeError( + "'this' is expected an EventTarget object, but got another value." + ) + } + return listeners +} + +/** + * Get the property descriptor for the event attribute of a given event. + * @param {string} eventName The event name to get property descriptor. + * @returns {PropertyDescriptor} The property descriptor. + * @private + */ +function defineEventAttributeDescriptor(eventName) { + return { + get() { + const listeners = getListeners(this); + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + return node.listener + } + node = node.next; + } + return null + }, + + set(listener) { + if (typeof listener !== "function" && !isObject(listener)) { + listener = null; // eslint-disable-line no-param-reassign + } + const listeners = getListeners(this); + + // Traverse to the tail while removing old value. + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + // Remove old value. + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + node = node.next; + } + + // Add new value. + if (listener !== null) { + const newNode = { + listener, + listenerType: ATTRIBUTE, + passive: false, + once: false, + next: null, + }; + if (prev === null) { + listeners.set(eventName, newNode); + } else { + prev.next = newNode; + } + } + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define an event attribute (e.g. `eventTarget.onclick`). + * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. + * @param {string} eventName The event name to define. + * @returns {void} + */ +function defineEventAttribute(eventTargetPrototype, eventName) { + Object.defineProperty( + eventTargetPrototype, + `on${eventName}`, + defineEventAttributeDescriptor(eventName) + ); +} + +/** + * Define a custom EventTarget with event attributes. + * @param {string[]} eventNames Event names for event attributes. + * @returns {EventTarget} The custom EventTarget. + * @private + */ +function defineCustomEventTarget(eventNames) { + /** CustomEventTarget */ + function CustomEventTarget() { + EventTarget.call(this); + } + + CustomEventTarget.prototype = Object.create(EventTarget.prototype, { + constructor: { + value: CustomEventTarget, + configurable: true, + writable: true, + }, + }); + + for (let i = 0; i < eventNames.length; ++i) { + defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); + } + + return CustomEventTarget +} + +/** + * EventTarget. + * + * - This is constructor if no arguments. + * - This is a function which returns a CustomEventTarget constructor if there are arguments. + * + * For example: + * + * class A extends EventTarget {} + * class B extends EventTarget("message") {} + * class C extends EventTarget("message", "error") {} + * class D extends EventTarget(["message", "error"]) {} + */ +function EventTarget() { + /*eslint-disable consistent-return */ + if (this instanceof EventTarget) { + listenersMap.set(this, new Map()); + return + } + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return defineCustomEventTarget(arguments[0]) + } + if (arguments.length > 0) { + const types = new Array(arguments.length); + for (let i = 0; i < arguments.length; ++i) { + types[i] = arguments[i]; + } + return defineCustomEventTarget(types) + } + throw new TypeError("Cannot call a class as a function") + /*eslint-enable consistent-return */ +} + +// Should be enumerable, but class methods are not enumerable. +EventTarget.prototype = { + /** + * Add a given listener to this event target. + * @param {string} eventName The event name to add. + * @param {Function} listener The listener to add. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + addEventListener(eventName, listener, options) { + if (listener == null) { + return + } + if (typeof listener !== "function" && !isObject(listener)) { + throw new TypeError("'listener' should be a function or an object.") + } + + const listeners = getListeners(this); + const optionsIsObj = isObject(options); + const capture = optionsIsObj + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + const newNode = { + listener, + listenerType, + passive: optionsIsObj && Boolean(options.passive), + once: optionsIsObj && Boolean(options.once), + next: null, + }; + + // Set it as the first node if the first node is null. + let node = listeners.get(eventName); + if (node === undefined) { + listeners.set(eventName, newNode); + return + } + + // Traverse to the tail while checking duplication.. + let prev = null; + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + // Should ignore duplication. + return + } + prev = node; + node = node.next; + } + + // Add it. + prev.next = newNode; + }, + + /** + * Remove a given listener from this event target. + * @param {string} eventName The event name to remove. + * @param {Function} listener The listener to remove. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + removeEventListener(eventName, listener, options) { + if (listener == null) { + return + } + + const listeners = getListeners(this); + const capture = isObject(options) + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + return + } + + prev = node; + node = node.next; + } + }, + + /** + * Dispatch a given event. + * @param {Event|{type:string}} event The event to dispatch. + * @returns {boolean} `false` if canceled. + */ + dispatchEvent(event) { + if (event == null || typeof event.type !== "string") { + throw new TypeError('"event.type" should be a string.') + } + + // If listeners aren't registered, terminate. + const listeners = getListeners(this); + const eventName = event.type; + let node = listeners.get(eventName); + if (node == null) { + return true + } + + // Since we cannot rewrite several properties, so wrap object. + const wrappedEvent = wrapEvent(this, event); + + // This doesn't process capturing phase and bubbling phase. + // This isn't participating in a tree. + let prev = null; + while (node != null) { + // Remove this listener if it's once + if (node.once) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + // Call this listener + setPassiveListener( + wrappedEvent, + node.passive ? node.listener : null + ); + if (typeof node.listener === "function") { + try { + node.listener.call(this, wrappedEvent); + } catch (err) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error(err); + } + } + } else if ( + node.listenerType !== ATTRIBUTE && + typeof node.listener.handleEvent === "function" + ) { + node.listener.handleEvent(wrappedEvent); + } + + // Break if `event.stopImmediatePropagation` was called. + if (isStopped(wrappedEvent)) { + break + } + + node = node.next; + } + setPassiveListener(wrappedEvent, null); + setEventPhase(wrappedEvent, 0); + setCurrentTarget(wrappedEvent, null); + + return !wrappedEvent.defaultPrevented + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(EventTarget.prototype, "constructor", { + value: EventTarget, + configurable: true, + writable: true, +}); + +// Ensure `eventTarget instanceof window.EventTarget` is `true`. +if ( + typeof window !== "undefined" && + typeof window.EventTarget !== "undefined" +) { + Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); +} + +exports.defineEventAttribute = defineEventAttribute; +exports.EventTarget = EventTarget; +exports.default = EventTarget; + +module.exports = EventTarget +module.exports.EventTarget = module.exports["default"] = EventTarget +module.exports.defineEventAttribute = defineEventAttribute +//# sourceMappingURL=event-target-shim.js.map diff --git a/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.js.map b/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.js.map new file mode 100644 index 0000000..83c5f62 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.js.map @@ -0,0 +1 @@ +{"version":3,"file":"event-target-shim.js","sources":["../src/event.mjs","../src/event-target.mjs"],"sourcesContent":["/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype)\n}\n\nexport { defineEventAttribute, EventTarget }\nexport default EventTarget\n"],"names":[],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,WAAW,GAAG,IAAI,OAAO,GAAE;;;;;;;AAOjC,MAAM,QAAQ,GAAG,IAAI,OAAO,GAAE;;;;;;;;AAQ9B,SAAS,EAAE,CAAC,KAAK,EAAE;IACf,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,CAAC,KAAK,EAAC;IACnC,OAAO,CAAC,MAAM;QACV,IAAI,IAAI,IAAI;QACZ,6CAA6C;QAC7C,KAAK;MACR;IACD,OAAO,IAAI;CACd;;;;;;AAMD,SAAS,aAAa,CAAC,IAAI,EAAE;IACzB,IAAI,IAAI,CAAC,eAAe,IAAI,IAAI,EAAE;QAC9B;YACI,OAAO,OAAO,KAAK,WAAW;YAC9B,OAAO,OAAO,CAAC,KAAK,KAAK,UAAU;UACrC;YACE,OAAO,CAAC,KAAK;gBACT,oEAAoE;gBACpE,IAAI,CAAC,eAAe;cACvB;SACJ;QACD,MAAM;KACT;IACD,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,EAAE;QACxB,MAAM;KACT;;IAED,IAAI,CAAC,QAAQ,GAAG,KAAI;IACpB,IAAI,OAAO,IAAI,CAAC,KAAK,CAAC,cAAc,KAAK,UAAU,EAAE;QACjD,IAAI,CAAC,KAAK,CAAC,cAAc,GAAE;KAC9B;CACJ;;;;;;;;;;;;AAYD,SAAS,KAAK,CAAC,WAAW,E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AAC,YAAY,CAAC,EAAE;gBACzB,KAAK;aACR;;YAED,IAAI,GAAG,IAAI,CAAC,KAAI;SACnB;QACD,kBAAkB,CAAC,YAAY,EAAE,IAAI,EAAC;QACtC,aAAa,CAAC,YAAY,EAAE,CAAC,EAAC;QAC9B,gBAAgB,CAAC,YAAY,EAAE,IAAI,EAAC;;QAEpC,OAAO,CAAC,YAAY,CAAC,gBAAgB;KACxC;EACJ;;;AAGD,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,aAAa,EAAE;IACxD,KAAK,EAAE,WAAW;IAClB,YAAY,EAAE,IAAI;IAClB,QAAQ,EAAE,IAAI;CACjB,EAAC;;;AAGF;IACI,OAAO,MAAM,KAAK,WAAW;IAC7B,OAAO,MAAM,CAAC,WAAW,KAAK,WAAW;EAC3C;IACE,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC,SAAS,EAAC;CAC7E;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.mjs b/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.mjs new file mode 100644 index 0000000..114f3a1 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.mjs @@ -0,0 +1,862 @@ +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ +/** + * @typedef {object} PrivateData + * @property {EventTarget} eventTarget The event target. + * @property {{type:string}} event The original event object. + * @property {number} eventPhase The current event phase. + * @property {EventTarget|null} currentTarget The current event target. + * @property {boolean} canceled The flag to prevent default. + * @property {boolean} stopped The flag to stop propagation. + * @property {boolean} immediateStopped The flag to stop propagation immediately. + * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. + * @property {number} timeStamp The unix time. + * @private + */ + +/** + * Private data for event wrappers. + * @type {WeakMap} + * @private + */ +const privateData = new WeakMap(); + +/** + * Cache for wrapper classes. + * @type {WeakMap} + * @private + */ +const wrappers = new WeakMap(); + +/** + * Get private data. + * @param {Event} event The event object to get private data. + * @returns {PrivateData} The private data of the event. + * @private + */ +function pd(event) { + const retv = privateData.get(event); + console.assert( + retv != null, + "'this' is expected an Event object, but got", + event + ); + return retv +} + +/** + * https://dom.spec.whatwg.org/#set-the-canceled-flag + * @param data {PrivateData} private data. + */ +function setCancelFlag(data) { + if (data.passiveListener != null) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error( + "Unable to preventDefault inside passive event listener invocation.", + data.passiveListener + ); + } + return + } + if (!data.event.cancelable) { + return + } + + data.canceled = true; + if (typeof data.event.preventDefault === "function") { + data.event.preventDefault(); + } +} + +/** + * @see https://dom.spec.whatwg.org/#interface-event + * @private + */ +/** + * The event wrapper. + * @constructor + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Event|{type:string}} event The original event to wrap. + */ +function Event(eventTarget, event) { + privateData.set(this, { + eventTarget, + event, + eventPhase: 2, + currentTarget: eventTarget, + canceled: false, + stopped: false, + immediateStopped: false, + passiveListener: null, + timeStamp: event.timeStamp || Date.now(), + }); + + // https://heycam.github.io/webidl/#Unforgeable + Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); + + // Define accessors + const keys = Object.keys(event); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in this)) { + Object.defineProperty(this, key, defineRedirectDescriptor(key)); + } + } +} + +// Should be enumerable, but class methods are not enumerable. +Event.prototype = { + /** + * The type of this event. + * @type {string} + */ + get type() { + return pd(this).event.type + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get target() { + return pd(this).eventTarget + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get currentTarget() { + return pd(this).currentTarget + }, + + /** + * @returns {EventTarget[]} The composed path of this event. + */ + composedPath() { + const currentTarget = pd(this).currentTarget; + if (currentTarget == null) { + return [] + } + return [currentTarget] + }, + + /** + * Constant of NONE. + * @type {number} + */ + get NONE() { + return 0 + }, + + /** + * Constant of CAPTURING_PHASE. + * @type {number} + */ + get CAPTURING_PHASE() { + return 1 + }, + + /** + * Constant of AT_TARGET. + * @type {number} + */ + get AT_TARGET() { + return 2 + }, + + /** + * Constant of BUBBLING_PHASE. + * @type {number} + */ + get BUBBLING_PHASE() { + return 3 + }, + + /** + * The target of this event. + * @type {number} + */ + get eventPhase() { + return pd(this).eventPhase + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopPropagation() { + const data = pd(this); + + data.stopped = true; + if (typeof data.event.stopPropagation === "function") { + data.event.stopPropagation(); + } + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopImmediatePropagation() { + const data = pd(this); + + data.stopped = true; + data.immediateStopped = true; + if (typeof data.event.stopImmediatePropagation === "function") { + data.event.stopImmediatePropagation(); + } + }, + + /** + * The flag to be bubbling. + * @type {boolean} + */ + get bubbles() { + return Boolean(pd(this).event.bubbles) + }, + + /** + * The flag to be cancelable. + * @type {boolean} + */ + get cancelable() { + return Boolean(pd(this).event.cancelable) + }, + + /** + * Cancel this event. + * @returns {void} + */ + preventDefault() { + setCancelFlag(pd(this)); + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + */ + get defaultPrevented() { + return pd(this).canceled + }, + + /** + * The flag to be composed. + * @type {boolean} + */ + get composed() { + return Boolean(pd(this).event.composed) + }, + + /** + * The unix time of this event. + * @type {number} + */ + get timeStamp() { + return pd(this).timeStamp + }, + + /** + * The target of this event. + * @type {EventTarget} + * @deprecated + */ + get srcElement() { + return pd(this).eventTarget + }, + + /** + * The flag to stop event bubbling. + * @type {boolean} + * @deprecated + */ + get cancelBubble() { + return pd(this).stopped + }, + set cancelBubble(value) { + if (!value) { + return + } + const data = pd(this); + + data.stopped = true; + if (typeof data.event.cancelBubble === "boolean") { + data.event.cancelBubble = true; + } + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + * @deprecated + */ + get returnValue() { + return !pd(this).canceled + }, + set returnValue(value) { + if (!value) { + setCancelFlag(pd(this)); + } + }, + + /** + * Initialize this event object. But do nothing under event dispatching. + * @param {string} type The event type. + * @param {boolean} [bubbles=false] The flag to be possible to bubble up. + * @param {boolean} [cancelable=false] The flag to be possible to cancel. + * @deprecated + */ + initEvent() { + // Do nothing. + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(Event.prototype, "constructor", { + value: Event, + configurable: true, + writable: true, +}); + +// Ensure `event instanceof window.Event` is `true`. +if (typeof window !== "undefined" && typeof window.Event !== "undefined") { + Object.setPrototypeOf(Event.prototype, window.Event.prototype); + + // Make association for wrappers. + wrappers.set(window.Event.prototype, Event); +} + +/** + * Get the property descriptor to redirect a given property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to redirect the property. + * @private + */ +function defineRedirectDescriptor(key) { + return { + get() { + return pd(this).event[key] + }, + set(value) { + pd(this).event[key] = value; + }, + configurable: true, + enumerable: true, + } +} + +/** + * Get the property descriptor to call a given method property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to call the method property. + * @private + */ +function defineCallDescriptor(key) { + return { + value() { + const event = pd(this).event; + return event[key].apply(event, arguments) + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define new wrapper class. + * @param {Function} BaseEvent The base wrapper class. + * @param {Object} proto The prototype of the original event. + * @returns {Function} The defined wrapper class. + * @private + */ +function defineWrapper(BaseEvent, proto) { + const keys = Object.keys(proto); + if (keys.length === 0) { + return BaseEvent + } + + /** CustomEvent */ + function CustomEvent(eventTarget, event) { + BaseEvent.call(this, eventTarget, event); + } + + CustomEvent.prototype = Object.create(BaseEvent.prototype, { + constructor: { value: CustomEvent, configurable: true, writable: true }, + }); + + // Define accessors. + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in BaseEvent.prototype)) { + const descriptor = Object.getOwnPropertyDescriptor(proto, key); + const isFunc = typeof descriptor.value === "function"; + Object.defineProperty( + CustomEvent.prototype, + key, + isFunc + ? defineCallDescriptor(key) + : defineRedirectDescriptor(key) + ); + } + } + + return CustomEvent +} + +/** + * Get the wrapper class of a given prototype. + * @param {Object} proto The prototype of the original event to get its wrapper. + * @returns {Function} The wrapper class. + * @private + */ +function getWrapper(proto) { + if (proto == null || proto === Object.prototype) { + return Event + } + + let wrapper = wrappers.get(proto); + if (wrapper == null) { + wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); + wrappers.set(proto, wrapper); + } + return wrapper +} + +/** + * Wrap a given event to management a dispatching. + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Object} event The event to wrap. + * @returns {Event} The wrapper instance. + * @private + */ +function wrapEvent(eventTarget, event) { + const Wrapper = getWrapper(Object.getPrototypeOf(event)); + return new Wrapper(eventTarget, event) +} + +/** + * Get the immediateStopped flag of a given event. + * @param {Event} event The event to get. + * @returns {boolean} The flag to stop propagation immediately. + * @private + */ +function isStopped(event) { + return pd(event).immediateStopped +} + +/** + * Set the current event phase of a given event. + * @param {Event} event The event to set current target. + * @param {number} eventPhase New event phase. + * @returns {void} + * @private + */ +function setEventPhase(event, eventPhase) { + pd(event).eventPhase = eventPhase; +} + +/** + * Set the current target of a given event. + * @param {Event} event The event to set current target. + * @param {EventTarget|null} currentTarget New current target. + * @returns {void} + * @private + */ +function setCurrentTarget(event, currentTarget) { + pd(event).currentTarget = currentTarget; +} + +/** + * Set a passive listener of a given event. + * @param {Event} event The event to set current target. + * @param {Function|null} passiveListener New passive listener. + * @returns {void} + * @private + */ +function setPassiveListener(event, passiveListener) { + pd(event).passiveListener = passiveListener; +} + +/** + * @typedef {object} ListenerNode + * @property {Function} listener + * @property {1|2|3} listenerType + * @property {boolean} passive + * @property {boolean} once + * @property {ListenerNode|null} next + * @private + */ + +/** + * @type {WeakMap>} + * @private + */ +const listenersMap = new WeakMap(); + +// Listener types +const CAPTURE = 1; +const BUBBLE = 2; +const ATTRIBUTE = 3; + +/** + * Check whether a given value is an object or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an object. + */ +function isObject(x) { + return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax +} + +/** + * Get listeners. + * @param {EventTarget} eventTarget The event target to get. + * @returns {Map} The listeners. + * @private + */ +function getListeners(eventTarget) { + const listeners = listenersMap.get(eventTarget); + if (listeners == null) { + throw new TypeError( + "'this' is expected an EventTarget object, but got another value." + ) + } + return listeners +} + +/** + * Get the property descriptor for the event attribute of a given event. + * @param {string} eventName The event name to get property descriptor. + * @returns {PropertyDescriptor} The property descriptor. + * @private + */ +function defineEventAttributeDescriptor(eventName) { + return { + get() { + const listeners = getListeners(this); + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + return node.listener + } + node = node.next; + } + return null + }, + + set(listener) { + if (typeof listener !== "function" && !isObject(listener)) { + listener = null; // eslint-disable-line no-param-reassign + } + const listeners = getListeners(this); + + // Traverse to the tail while removing old value. + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + // Remove old value. + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + node = node.next; + } + + // Add new value. + if (listener !== null) { + const newNode = { + listener, + listenerType: ATTRIBUTE, + passive: false, + once: false, + next: null, + }; + if (prev === null) { + listeners.set(eventName, newNode); + } else { + prev.next = newNode; + } + } + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define an event attribute (e.g. `eventTarget.onclick`). + * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. + * @param {string} eventName The event name to define. + * @returns {void} + */ +function defineEventAttribute(eventTargetPrototype, eventName) { + Object.defineProperty( + eventTargetPrototype, + `on${eventName}`, + defineEventAttributeDescriptor(eventName) + ); +} + +/** + * Define a custom EventTarget with event attributes. + * @param {string[]} eventNames Event names for event attributes. + * @returns {EventTarget} The custom EventTarget. + * @private + */ +function defineCustomEventTarget(eventNames) { + /** CustomEventTarget */ + function CustomEventTarget() { + EventTarget.call(this); + } + + CustomEventTarget.prototype = Object.create(EventTarget.prototype, { + constructor: { + value: CustomEventTarget, + configurable: true, + writable: true, + }, + }); + + for (let i = 0; i < eventNames.length; ++i) { + defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); + } + + return CustomEventTarget +} + +/** + * EventTarget. + * + * - This is constructor if no arguments. + * - This is a function which returns a CustomEventTarget constructor if there are arguments. + * + * For example: + * + * class A extends EventTarget {} + * class B extends EventTarget("message") {} + * class C extends EventTarget("message", "error") {} + * class D extends EventTarget(["message", "error"]) {} + */ +function EventTarget() { + /*eslint-disable consistent-return */ + if (this instanceof EventTarget) { + listenersMap.set(this, new Map()); + return + } + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return defineCustomEventTarget(arguments[0]) + } + if (arguments.length > 0) { + const types = new Array(arguments.length); + for (let i = 0; i < arguments.length; ++i) { + types[i] = arguments[i]; + } + return defineCustomEventTarget(types) + } + throw new TypeError("Cannot call a class as a function") + /*eslint-enable consistent-return */ +} + +// Should be enumerable, but class methods are not enumerable. +EventTarget.prototype = { + /** + * Add a given listener to this event target. + * @param {string} eventName The event name to add. + * @param {Function} listener The listener to add. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + addEventListener(eventName, listener, options) { + if (listener == null) { + return + } + if (typeof listener !== "function" && !isObject(listener)) { + throw new TypeError("'listener' should be a function or an object.") + } + + const listeners = getListeners(this); + const optionsIsObj = isObject(options); + const capture = optionsIsObj + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + const newNode = { + listener, + listenerType, + passive: optionsIsObj && Boolean(options.passive), + once: optionsIsObj && Boolean(options.once), + next: null, + }; + + // Set it as the first node if the first node is null. + let node = listeners.get(eventName); + if (node === undefined) { + listeners.set(eventName, newNode); + return + } + + // Traverse to the tail while checking duplication.. + let prev = null; + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + // Should ignore duplication. + return + } + prev = node; + node = node.next; + } + + // Add it. + prev.next = newNode; + }, + + /** + * Remove a given listener from this event target. + * @param {string} eventName The event name to remove. + * @param {Function} listener The listener to remove. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + removeEventListener(eventName, listener, options) { + if (listener == null) { + return + } + + const listeners = getListeners(this); + const capture = isObject(options) + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + return + } + + prev = node; + node = node.next; + } + }, + + /** + * Dispatch a given event. + * @param {Event|{type:string}} event The event to dispatch. + * @returns {boolean} `false` if canceled. + */ + dispatchEvent(event) { + if (event == null || typeof event.type !== "string") { + throw new TypeError('"event.type" should be a string.') + } + + // If listeners aren't registered, terminate. + const listeners = getListeners(this); + const eventName = event.type; + let node = listeners.get(eventName); + if (node == null) { + return true + } + + // Since we cannot rewrite several properties, so wrap object. + const wrappedEvent = wrapEvent(this, event); + + // This doesn't process capturing phase and bubbling phase. + // This isn't participating in a tree. + let prev = null; + while (node != null) { + // Remove this listener if it's once + if (node.once) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + // Call this listener + setPassiveListener( + wrappedEvent, + node.passive ? node.listener : null + ); + if (typeof node.listener === "function") { + try { + node.listener.call(this, wrappedEvent); + } catch (err) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error(err); + } + } + } else if ( + node.listenerType !== ATTRIBUTE && + typeof node.listener.handleEvent === "function" + ) { + node.listener.handleEvent(wrappedEvent); + } + + // Break if `event.stopImmediatePropagation` was called. + if (isStopped(wrappedEvent)) { + break + } + + node = node.next; + } + setPassiveListener(wrappedEvent, null); + setEventPhase(wrappedEvent, 0); + setCurrentTarget(wrappedEvent, null); + + return !wrappedEvent.defaultPrevented + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(EventTarget.prototype, "constructor", { + value: EventTarget, + configurable: true, + writable: true, +}); + +// Ensure `eventTarget instanceof window.EventTarget` is `true`. +if ( + typeof window !== "undefined" && + typeof window.EventTarget !== "undefined" +) { + Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); +} + +export default EventTarget; +export { defineEventAttribute, EventTarget }; +//# sourceMappingURL=event-target-shim.mjs.map diff --git a/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.mjs.map b/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.mjs.map new file mode 100644 index 0000000..57b3e8f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"event-target-shim.mjs","sources":["../src/event.mjs","../src/event-target.mjs"],"sourcesContent":["/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype)\n}\n\nexport { defineEventAttribute, EventTarget }\nexport default EventTarget\n"],"names":[],"mappings":";;;;;AAAA;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,WAAW,GAAG,IAAI,O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AAGF;IACI,OAAO,MAAM,KAAK,WAAW;IAC7B,OAAO,MAAM,CAAC,WAAW,KAAK,WAAW;EAC3C;IACE,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC,SAAS,EAAC;CAC7E;;;;;"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.umd.js b/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.umd.js new file mode 100644 index 0000000..e7cf5d4 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/event-target-shim/dist/event-target-shim.umd.js @@ -0,0 +1,6 @@ +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */(function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):(a=a||self,b(a.EventTargetShim={}))})(this,function(a){"use strict";function b(a){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},b(a)}function c(a){var b=u.get(a);return console.assert(null!=b,"'this' is expected an Event object, but got",a),b}function d(a){return null==a.passiveListener?void(!a.event.cancelable||(a.canceled=!0,"function"==typeof a.event.preventDefault&&a.event.preventDefault())):void("undefined"!=typeof console&&"function"==typeof console.error&&console.error("Unable to preventDefault inside passive event listener invocation.",a.passiveListener))}function e(a,b){u.set(this,{eventTarget:a,event:b,eventPhase:2,currentTarget:a,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:b.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});for(var c,d=Object.keys(b),e=0;e}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype)\n}\n\nexport { defineEventAttribute, EventTarget }\nexport default EventTarget\n"],"names":["pd","event","retv","privateData","get","console","assert","setCancelFlag","data","passiveListener","cancelable","canceled","preventDefault","error","Event","eventTarget","set","eventPhase","currentTarget","stopped","immediateStopped","timeStamp","Date","now","Object","defineProperty","value","enumerable","key","keys","i","length","defineRedirectDescriptor","configurable","defineCallDescriptor","apply","arguments","defineWrapper","BaseEvent","proto","CustomEvent","call","prototype","create","constructor","writable","descriptor","getOwnPropertyDescriptor","isFunc","getWrapper","wrapper","wrappers","getPrototypeOf","wrapEvent","Wrapper","isStopped","setEventPhase","setCurrentTarget","setPassiveListener","isObject","x","_typeof","getListeners","listeners","listenersMap","TypeError","defineEventAttributeDescriptor","eventName","node","listenerType","listener","next","prev","delete","newNode","passive","once","defineEventAttribute","eventTargetPrototype","defineCustomEventTarget","eventNames","CustomEventTarget","EventTarget","Map","Array","isArray","types","WeakMap","type","target","composedPath","NONE","CAPTURING_PHASE","AT_TARGET","BUBBLING_PHASE","stopPropagation","stopImmediatePropagation","bubbles","defaultPrevented","composed","srcElement","cancelBubble","returnValue","initEvent","window","setPrototypeOf","CAPTURE","BUBBLE","addEventListener","options","optionsIsObj","capture","removeEventListener","dispatchEvent","wrappedEvent","err","handleEvent"],"mappings":";;;;wbAkCA,QAASA,CAAAA,CAAT,CAAYC,CAAZ,CAAmB,IACTC,CAAAA,CAAI,CAAGC,CAAW,CAACC,GAAZD,CAAgBF,CAAhBE,QACbE,CAAAA,OAAO,CAACC,MAARD,CACY,IAARH,EAAAA,CADJG,CAEI,6CAFJA,CAGIJ,CAHJI,EAKOH,EAOX,QAASK,CAAAA,CAAT,CAAuBC,CAAvB,CAA6B,OACG,KAAxBA,EAAAA,CAAI,CAACC,eADgB,MAarB,CAACD,CAAI,CAACP,KAALO,CAAWE,UAbS,GAiBzBF,CAAI,CAACG,QAALH,GAjByB,CAkBgB,UAArC,QAAOA,CAAAA,CAAI,CAACP,KAALO,CAAWI,cAlBG,EAmB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AAI,CAACC,YAALD,GA/TE,CA+TFA,EACqC,UAArC,QAAOA,CAAAA,CAAI,CAACE,QAALF,CAAcgD,aAErBhD,CAAI,CAACE,QAALF,CAAcgD,WAAdhD,CAA0B8C,CAA1B9C,KAIAb,CAAS,CAAC2D,CAAD,QAIb9C,CAAI,CAAGA,CAAI,CAACG,WAEhBb,CAAAA,CAAkB,CAACwD,CAAD,CAAe,IAAf,EAClB1D,CAAa,CAAC0D,CAAD,CAAe,CAAf,EACbzD,CAAgB,CAACyD,CAAD,CAAe,IAAf,EAET,CAACA,CAAY,CAAChB,iBAvKL,EA4KxB1E,MAAM,CAACC,cAAPD,CAAsB0D,CAAW,CAACxC,SAAlClB,CAA6C,aAA7CA,CAA4D,CACxDE,KAAK,CAAEwD,CADiD,CAExDjD,YAAY,GAF4C,CAGxDY,QAAQ,GAHgD,CAA5DrB,EAQsB,WAAlB,QAAOgF,CAAAA,MAAP,EAC8B,WAA9B,QAAOA,CAAAA,MAAM,CAACtB,aAEd1D,MAAM,CAACiF,cAAPjF,CAAsB0D,CAAW,CAACxC,SAAlClB,CAA6CgF,MAAM,CAACtB,WAAPsB,CAAmB9D,SAAhElB"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.d.ts b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.d.ts new file mode 100644 index 0000000..3f043f7 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.d.ts @@ -0,0 +1,32 @@ +/// +import net from 'net'; +import { Agent, ClientRequest, RequestOptions } from 'agent-base'; +import { HttpProxyAgentOptions } from '.'; +interface HttpProxyAgentClientRequest extends ClientRequest { + path: string; + output?: string[]; + outputData?: { + data: string; + }[]; + _header?: string | null; + _implicitHeader(): void; +} +/** + * The `HttpProxyAgent` implements an HTTP Agent subclass that connects + * to the specified "HTTP proxy server" in order to proxy HTTP requests. + * + * @api public + */ +export default class HttpProxyAgent extends Agent { + private secureProxy; + private proxy; + constructor(_opts: string | HttpProxyAgentOptions); + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req: HttpProxyAgentClientRequest, opts: RequestOptions): Promise; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.js b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.js new file mode 100644 index 0000000..aca8280 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.js @@ -0,0 +1,145 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const net_1 = __importDefault(require("net")); +const tls_1 = __importDefault(require("tls")); +const url_1 = __importDefault(require("url")); +const debug_1 = __importDefault(require("debug")); +const once_1 = __importDefault(require("@tootallnate/once")); +const agent_base_1 = require("agent-base"); +const debug = (0, debug_1.default)('http-proxy-agent'); +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; +} +/** + * The `HttpProxyAgent` implements an HTTP Agent subclass that connects + * to the specified "HTTP proxy server" in order to proxy HTTP requests. + * + * @api public + */ +class HttpProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('Creating new HttpProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + const parsed = url_1.default.parse(req.path); + if (!parsed.protocol) { + parsed.protocol = 'http:'; + } + if (!parsed.hostname) { + parsed.hostname = opts.hostname || opts.host || null; + } + if (parsed.port == null && typeof opts.port) { + parsed.port = String(opts.port); + } + if (parsed.port === '80') { + // if port is 80, then we can remove the port so that the + // ":80" portion is not on the produced URL + parsed.port = ''; + } + // Change the `http.ClientRequest` instance's "path" field + // to the absolute path of the URL that will be requested. + req.path = url_1.default.format(parsed); + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + req.setHeader('Proxy-Authorization', `Basic ${Buffer.from(proxy.auth).toString('base64')}`); + } + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + // At this point, the http ClientRequest's internal `_header` field + // might have already been set. If this is the case then we'll need + // to re-generate the string since we just changed the `req.path`. + if (req._header) { + let first; + let endOfHeaders; + debug('Regenerating stored HTTP header string for request'); + req._header = null; + req._implicitHeader(); + if (req.output && req.output.length > 0) { + // Node < 12 + debug('Patching connection write() output buffer with updated header'); + first = req.output[0]; + endOfHeaders = first.indexOf('\r\n\r\n') + 4; + req.output[0] = req._header + first.substring(endOfHeaders); + debug('Output buffer: %o', req.output); + } + else if (req.outputData && req.outputData.length > 0) { + // Node >= 12 + debug('Patching connection write() output buffer with updated header'); + first = req.outputData[0].data; + endOfHeaders = first.indexOf('\r\n\r\n') + 4; + req.outputData[0].data = + req._header + first.substring(endOfHeaders); + debug('Output buffer: %o', req.outputData[0].data); + } + } + // Wait for the socket's `connect` event, so that this `callback()` + // function throws instead of the `http` request machinery. This is + // important for i.e. `PacProxyAgent` which determines a failed proxy + // connection via the `callback()` function throwing. + yield (0, once_1.default)(socket, 'connect'); + return socket; + }); + } +} +exports.default = HttpProxyAgent; +//# sourceMappingURL=agent.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.js.map b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.js.map new file mode 100644 index 0000000..bd3b56a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/agent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8CAAsB;AACtB,8CAAsB;AACtB,8CAAsB;AACtB,kDAAgC;AAChC,6DAAqC;AACrC,2CAAkE;AAGlE,MAAM,KAAK,GAAG,IAAA,eAAW,EAAC,kBAAkB,CAAC,CAAC;AAY9C,SAAS,OAAO,CAAC,QAAwB;IACxC,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AAC3E,CAAC;AAED;;;;;GAKG;AACH,MAAqB,cAAe,SAAQ,kBAAK;IAIhD,YAAY,KAAqC;QAChD,IAAI,IAA2B,CAAC;QAChC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAA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YAED,mEAAmE;YACnE,mEAAmE;YACnE,qEAAqE;YACrE,qDAAqD;YACrD,MAAM,IAAA,cAAI,EAAC,MAAM,EAAE,SAAS,CAAC,CAAC;YAE9B,OAAO,MAAM,CAAC;QACf,CAAC;KAAA;CACD;AA1ID,iCA0IC"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.d.ts b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.d.ts new file mode 100644 index 0000000..24bdb52 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.d.ts @@ -0,0 +1,21 @@ +/// +import net from 'net'; +import tls from 'tls'; +import { Url } from 'url'; +import { AgentOptions } from 'agent-base'; +import _HttpProxyAgent from './agent'; +declare function createHttpProxyAgent(opts: string | createHttpProxyAgent.HttpProxyAgentOptions): _HttpProxyAgent; +declare namespace createHttpProxyAgent { + interface BaseHttpProxyAgentOptions { + secureProxy?: boolean; + host?: string | null; + path?: string | null; + port?: string | number | null; + } + export interface HttpProxyAgentOptions extends AgentOptions, BaseHttpProxyAgentOptions, Partial> { + } + export type HttpProxyAgent = _HttpProxyAgent; + export const HttpProxyAgent: typeof _HttpProxyAgent; + export {}; +} +export = createHttpProxyAgent; diff --git a/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.js b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.js new file mode 100644 index 0000000..0a71180 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.js @@ -0,0 +1,14 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(require("./agent")); +function createHttpProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpProxyAgent) { + createHttpProxyAgent.HttpProxyAgent = agent_1.default; + createHttpProxyAgent.prototype = agent_1.default.prototype; +})(createHttpProxyAgent || (createHttpProxyAgent = {})); +module.exports = createHttpProxyAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.js.map b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.js.map new file mode 100644 index 0000000..e07dae5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/http-proxy-agent/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAIA,oDAAsC;AAEtC,SAAS,oBAAoB,CAC5B,IAAyD;IAEzD,OAAO,IAAI,eAAe,CAAC,IAAI,CAAC,CAAC;AAClC,CAAC;AAED,WAAU,oBAAoB;IAmBhB,mCAAc,GAAG,eAAe,CAAC;IAE9C,oBAAoB,CAAC,SAAS,GAAG,eAAe,CAAC,SAAS,CAAC;AAC5D,CAAC,EAtBS,oBAAoB,KAApB,oBAAoB,QAsB7B;AAED,iBAAS,oBAAoB,CAAC"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.d.ts b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.d.ts new file mode 100644 index 0000000..4f1c636 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.d.ts @@ -0,0 +1,30 @@ +/// +import net from 'net'; +import { Agent, ClientRequest, RequestOptions } from 'agent-base'; +import { HttpsProxyAgentOptions } from '.'; +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +export default class HttpsProxyAgent extends Agent { + private secureProxy; + private proxy; + constructor(_opts: string | HttpsProxyAgentOptions); + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req: ClientRequest, opts: RequestOptions): Promise; +} diff --git a/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.js b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.js new file mode 100644 index 0000000..75d1136 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.js @@ -0,0 +1,177 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const net_1 = __importDefault(require("net")); +const tls_1 = __importDefault(require("tls")); +const url_1 = __importDefault(require("url")); +const assert_1 = __importDefault(require("assert")); +const debug_1 = __importDefault(require("debug")); +const agent_base_1 = require("agent-base"); +const parse_proxy_response_1 = __importDefault(require("./parse-proxy-response")); +const debug = debug_1.default('https-proxy-agent:agent'); +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('creating new HttpsProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + // ALPN is supported by Node.js >= v5. + // attempt to negotiate http/1.1 for proxy servers that support http/2 + if (this.secureProxy && !('ALPNProtocols' in proxy)) { + proxy.ALPNProtocols = ['http 1.1']; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; + } + // The `Host` header should only include the port + // number when it is not the default port. + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; + } + headers.Host = host; + headers.Connection = 'close'; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r\n`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + const servername = opts.servername || opts.host; + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername })); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net_1.default.Socket({ writable: false }); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('replaying proxy buffer for failed request'); + assert_1.default(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); + } +} +exports.default = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); +} +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=agent.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.js.map b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.js.map new file mode 100644 index 0000000..0af6c17 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/agent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"agent.js","source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,CAAC,GAAG,CAAC,EAAE;YACxB,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;SACpB;KACD;IACD,OAAO,GAAG,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.d.ts b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.d.ts new file mode 100644 index 0000000..0d60062 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.d.ts @@ -0,0 +1,23 @@ +/// +import net from 'net'; +import tls from 'tls'; +import { Url } from 'url'; +import { AgentOptions } from 'agent-base'; +import { OutgoingHttpHeaders } from 'http'; +import _HttpsProxyAgent from './agent'; +declare function createHttpsProxyAgent(opts: string | createHttpsProxyAgent.HttpsProxyAgentOptions): _HttpsProxyAgent; +declare namespace createHttpsProxyAgent { + interface BaseHttpsProxyAgentOptions { + headers?: OutgoingHttpHeaders; + secureProxy?: boolean; + host?: string | null; + path?: string | null; + port?: string | number | null; + } + export interface HttpsProxyAgentOptions extends AgentOptions, BaseHttpsProxyAgentOptions, Partial> { + } + export type HttpsProxyAgent = _HttpsProxyAgent; + export const HttpsProxyAgent: typeof _HttpsProxyAgent; + export {}; +} +export = createHttpsProxyAgent; diff --git a/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.js b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.js new file mode 100644 index 0000000..b03e763 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.js @@ -0,0 +1,14 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(require("./agent")); +function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpsProxyAgent) { + createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent.prototype = agent_1.default.prototype; +})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); +module.exports = createHttpsProxyAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.js.map b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.js.map new file mode 100644 index 0000000..f3ce559 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAKA,oDAAuC;AAEvC,SAAS,qBAAqB,CAC7B,IAA2D;IAE3D,OAAO,IAAI,eAAgB,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC;AAED,WAAU,qBAAqB;IAoBjB,qCAAe,GAAG,eAAgB,CAAC;IAEhD,qBAAqB,CAAC,SAAS,GAAG,eAAgB,CAAC,SAAS,CAAC;AAC9D,CAAC,EAvBS,qBAAqB,KAArB,qBAAqB,QAuB9B;AAED,iBAAS,qBAAqB,CAAC"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts new file mode 100644 index 0000000..7565674 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts @@ -0,0 +1,7 @@ +/// +import { Readable } from 'stream'; +export interface ProxyResponse { + statusCode: number; + buffered: Buffer; +} +export default function parseProxyResponse(socket: Readable): Promise; diff --git a/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.js b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.js new file mode 100644 index 0000000..aa5ce3c --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.js @@ -0,0 +1,66 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const debug_1 = __importDefault(require("debug")); +const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('close', onclose); + socket.removeListener('readable', read); + } + function onclose(err) { + debug('onclose had error %o', err); + } + function onend() { + debug('onend'); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); + const statusCode = +firstLine.split(' ')[1]; + debug('got proxy server response: %o', firstLine); + resolve({ + statusCode, + buffered + }); + } + socket.on('error', onerror); + socket.on('close', onclose); + socket.on('end', onend); + read(); + }); +} +exports.default = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map new file mode 100644 index 0000000..bacdb84 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-proxy-response.js","sourceRoot":"","sources":["../src/parse-proxy-response.ts"],"names":[],"mappings":";;;;;AAAA,kDAAgC;AAGhC,MAAM,KAAK,GAAG,eAAW,CAAC,wCAAw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,MAAM,YAAY,GAAG,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;YAElD,IAAI,YAAY,KAAK,CAAC,CAAC,EAAE;gBACxB,iBAAiB;gBACjB,KAAK,CAAC,8CAA8C,CAAC,CAAC;gBACtD,IAAI,EAAE,CAAC;gBACP,OAAO;aACP;YAED,MAAM,SAAS,GAAG,QAAQ,CAAC,QAAQ,CAClC,OAAO,EACP,CAAC,EACD,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CACxB,CAAC;YACF,MAAM,UAAU,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5C,KAAK,CAAC,+BAA+B,EAAE,SAAS,CAAC,CAAC;YAClD,OAAO,CAAC;gBACP,UAAU;gBACV,QAAQ;aACR,CAAC,CAAC;QACJ,CAAC;QAED,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAExB,IAAI,EAAE,CAAC;IACR,CAAC,CAAC,CAAC;AACJ,CAAC;AAvED,qCAuEC"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.d.ts b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.d.ts new file mode 100644 index 0000000..29fdd1d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.d.ts @@ -0,0 +1,35 @@ +declare const _default: { + (p: string, pattern: string, options?: import("./index.js").MinimatchOptions): boolean; + sep: string; + GLOBSTAR: typeof import("./index.js").GLOBSTAR; + filter: (pattern: string, options?: import("./index.js").MinimatchOptions) => (p: string) => boolean; + defaults: (def: import("./index.js").MinimatchOptions) => any; + braceExpand: (pattern: string, options?: import("./index.js").MinimatchOptions) => string[]; + makeRe: (pattern: string, options?: import("./index.js").MinimatchOptions) => false | import("./index.js").MMRegExp; + match: (list: string[], pattern: string, options?: import("./index.js").MinimatchOptions) => string[]; + Minimatch: typeof import("./index.js").Minimatch; +} & { + default: { + (p: string, pattern: string, options?: import("./index.js").MinimatchOptions): boolean; + sep: string; + GLOBSTAR: typeof import("./index.js").GLOBSTAR; + filter: (pattern: string, options?: import("./index.js").MinimatchOptions) => (p: string) => boolean; + defaults: (def: import("./index.js").MinimatchOptions) => any; + braceExpand: (pattern: string, options?: import("./index.js").MinimatchOptions) => string[]; + makeRe: (pattern: string, options?: import("./index.js").MinimatchOptions) => false | import("./index.js").MMRegExp; + match: (list: string[], pattern: string, options?: import("./index.js").MinimatchOptions) => string[]; + Minimatch: typeof import("./index.js").Minimatch; + }; + minimatch: { + (p: string, pattern: string, options?: import("./index.js").MinimatchOptions): boolean; + sep: string; + GLOBSTAR: typeof import("./index.js").GLOBSTAR; + filter: (pattern: string, options?: import("./index.js").MinimatchOptions) => (p: string) => boolean; + defaults: (def: import("./index.js").MinimatchOptions) => any; + braceExpand: (pattern: string, options?: import("./index.js").MinimatchOptions) => string[]; + makeRe: (pattern: string, options?: import("./index.js").MinimatchOptions) => false | import("./index.js").MMRegExp; + match: (list: string[], pattern: string, options?: import("./index.js").MinimatchOptions) => string[]; + Minimatch: typeof import("./index.js").Minimatch; + }; +}; +export = _default; diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.js b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.js new file mode 100644 index 0000000..db73b6b --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.js @@ -0,0 +1,7 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const index_js_1 = __importDefault(require("./index.js")); +module.exports = Object.assign(index_js_1.default, { default: index_js_1.default, minimatch: index_js_1.default }); +//# sourceMappingURL=index-cjs.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.js.map b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.js.map new file mode 100644 index 0000000..1a05485 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index-cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index-cjs.js","sourceRoot":"","sources":["../../src/index-cjs.ts"],"names":[],"mappings":";;;;AAAA,0DAAkC;AAElC,iBAAS,MAAM,CAAC,MAAM,CAAC,kBAAS,EAAE,EAAE,OAAO,EAAE,kBAAS,EAAE,SAAS,EAAT,kBAAS,EAAE,CAAC,CAAA"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.d.ts b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.d.ts new file mode 100644 index 0000000..cca07a8 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.d.ts @@ -0,0 +1,71 @@ +export interface MinimatchOptions { + nobrace?: boolean; + nocomment?: boolean; + nonegate?: boolean; + debug?: boolean; + noglobstar?: boolean; + noext?: boolean; + nonull?: boolean; + windowsPathsNoEscape?: boolean; + allowWindowsEscape?: boolean; + partial?: boolean; + dot?: boolean; + nocase?: boolean; + nocaseMagicOnly?: boolean; + matchBase?: boolean; + flipNegate?: boolean; + preserveMultipleSlashes?: boolean; +} +export declare const minimatch: { + (p: string, pattern: string, options?: MinimatchOptions): boolean; + sep: string; + GLOBSTAR: typeof GLOBSTAR; + filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean; + defaults: (def: MinimatchOptions) => typeof minimatch; + braceExpand: (pattern: string, options?: MinimatchOptions) => string[]; + makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp; + match: (list: string[], pattern: string, options?: MinimatchOptions) => string[]; + Minimatch: typeof Minimatch; +}; +export default minimatch; +export declare const sep: string; +export declare const GLOBSTAR: unique symbol; +export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean; +export declare const defaults: (def: MinimatchOptions) => typeof minimatch; +export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[]; +declare const SUBPARSE: unique symbol; +export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp; +export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[]; +export type MMRegExp = RegExp & { + _src?: string; + _glob?: string; +}; +type SubparseReturn = [string, boolean]; +type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR; +type ParseReturn = ParseReturnFiltered | false; +export declare class Minimatch { + options: MinimatchOptions; + set: ParseReturnFiltered[][]; + pattern: string; + windowsPathsNoEscape: boolean; + nonegate: boolean; + negate: boolean; + comment: boolean; + empty: boolean; + preserveMultipleSlashes: boolean; + partial: boolean; + globSet: string[]; + globParts: string[][]; + regexp: false | null | MMRegExp; + constructor(pattern: string, options?: MinimatchOptions); + debug(..._: any[]): void; + make(): void; + parseNegate(): void; + matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean; + braceExpand(): string[]; + parse(pattern: string, isSub?: typeof SUBPARSE): ParseReturn | SubparseReturn; + makeRe(): false | MMRegExp; + slashSplit(p: string): string[]; + match(f: string, partial?: boolean): boolean; + static defaults(def: MinimatchOptions): typeof Minimatch; +} diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.js b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.js new file mode 100644 index 0000000..63fc3bd --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.js @@ -0,0 +1,1090 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Minimatch = exports.match = exports.makeRe = exports.braceExpand = exports.defaults = exports.filter = exports.GLOBSTAR = exports.sep = exports.minimatch = void 0; +const minimatch = (p, pattern, options = {}) => { + assertValidPattern(pattern); + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false; + } + return new Minimatch(pattern, options).match(p); +}; +exports.minimatch = minimatch; +exports.default = exports.minimatch; +// Optimized checking for the most common glob patterns. +const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; +const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); +const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); +const starDotExtTestNocase = (ext) => { + ext = ext.toLowerCase(); + return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext); +}; +const starDotExtTestNocaseDot = (ext) => { + ext = ext.toLowerCase(); + return (f) => f.toLowerCase().endsWith(ext); +}; +const starDotStarRE = /^\*+\.\*+$/; +const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.'); +const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.'); +const dotStarRE = /^\.\*+$/; +const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.'); +const starRE = /^\*+$/; +const starTest = (f) => f.length !== 0 && !f.startsWith('.'); +const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..'; +const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; +const qmarksTestNocase = ([$0, ext = '']) => { + const noext = qmarksTestNoExt([$0]); + if (!ext) + return noext; + ext = ext.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext); +}; +const qmarksTestNocaseDot = ([$0, ext = '']) => { + const noext = qmarksTestNoExtDot([$0]); + if (!ext) + return noext; + ext = ext.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext); +}; +const qmarksTestDot = ([$0, ext = '']) => { + const noext = qmarksTestNoExtDot([$0]); + return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +}; +const qmarksTest = ([$0, ext = '']) => { + const noext = qmarksTestNoExt([$0]); + return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +}; +const qmarksTestNoExt = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && !f.startsWith('.'); +}; +const qmarksTestNoExtDot = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && f !== '.' && f !== '..'; +}; +/* c8 ignore start */ +const platform = typeof process === 'object' && process + ? (typeof process.env === 'object' && + process.env && + process.env.__MINIMATCH_TESTING_PLATFORM__) || + process.platform + : 'posix'; +const isWindows = platform === 'win32'; +const path = isWindows ? { sep: '\\' } : { sep: '/' }; +/* c8 ignore stop */ +exports.sep = path.sep; +exports.minimatch.sep = exports.sep; +exports.GLOBSTAR = Symbol('globstar **'); +exports.minimatch.GLOBSTAR = exports.GLOBSTAR; +const brace_expansion_1 = __importDefault(require("brace-expansion")); +const plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)' }, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' }, +}; +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]'; +// * => any number of characters +const star = qmark + '*?'; +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?'; +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?'; +// "abc" -> { a:true, b:true, c:true } +const charSet = (s) => s.split('').reduce((set, c) => { + set[c] = true; + return set; +}, {}); +// characters that need to be escaped in RegExp. +const reSpecials = charSet('().*{}+?[]^$\\!'); +// characters that indicate we have to add the pattern start +const addPatternStartSet = charSet('[.('); +const filter = (pattern, options = {}) => (p) => (0, exports.minimatch)(p, pattern, options); +exports.filter = filter; +exports.minimatch.filter = exports.filter; +const ext = (a, b = {}) => Object.assign({}, a, b); +const defaults = (def) => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return exports.minimatch; + } + const orig = exports.minimatch; + const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); + return Object.assign(m, { + Minimatch: class Minimatch extends orig.Minimatch { + constructor(pattern, options = {}) { + super(pattern, ext(def, options)); + } + static defaults(options) { + return orig.defaults(ext(def, options)).Minimatch; + } + }, + filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), + defaults: (options) => orig.defaults(ext(def, options)), + makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), + braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), + match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), + sep: orig.sep, + GLOBSTAR: exports.GLOBSTAR, + }); +}; +exports.defaults = defaults; +exports.minimatch.defaults = exports.defaults; +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +const braceExpand = (pattern, options = {}) => { + assertValidPattern(pattern); + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern]; + } + return (0, brace_expansion_1.default)(pattern); +}; +exports.braceExpand = braceExpand; +exports.minimatch.braceExpand = exports.braceExpand; +const MAX_PATTERN_LENGTH = 1024 * 64; +const assertValidPattern = (pattern) => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern'); + } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long'); + } +}; +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const SUBPARSE = Symbol('subparse'); +const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); +exports.makeRe = makeRe; +exports.minimatch.makeRe = exports.makeRe; +const match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options); + list = list.filter(f => mm.match(f)); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list; +}; +exports.match = match; +exports.minimatch.match = exports.match; +// replace stuff like \* with * +const globUnescape = (s) => s.replace(/\\(.)/g, '$1'); +const charUnescape = (s) => s.replace(/\\([^-\]])/g, '$1'); +const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +const braExpEscape = (s) => s.replace(/[[\]\\]/g, '\\$&'); +class Minimatch { + options; + set; + pattern; + windowsPathsNoEscape; + nonegate; + negate; + comment; + empty; + preserveMultipleSlashes; + partial; + globSet; + globParts; + regexp; + constructor(pattern, options = {}) { + assertValidPattern(pattern); + options = options || {}; + this.options = options; + this.pattern = pattern; + this.windowsPathsNoEscape = + !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/'); + } + this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; + this.regexp = null; + this.negate = false; + this.nonegate = !!options.nonegate; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + this.globSet = []; + this.globParts = []; + this.set = []; + // make the set of regexps etc. + this.make(); + } + debug(..._) { } + make() { + const pattern = this.pattern; + const options = this.options; + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true; + return; + } + if (!pattern) { + this.empty = true; + return; + } + // step 1: figure out negation, etc. + this.parseNegate(); + // step 2: expand braces + this.globSet = this.braceExpand(); + if (options.debug) { + this.debug = (...args) => console.error(...args); + } + this.debug(this.pattern, this.globSet); + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + const rawGlobParts = this.globSet.map(s => this.slashSplit(s)); + // consecutive globstars are an unncessary perf killer + // also, **/*/... is equivalent to */**/..., so swap all of those + // this turns a pattern like **/*/**/*/x into */*/**/x + // and a pattern like **/x/**/*/y becomes **/x/*/**/y + // the *later* we can push the **, the more efficient it is, + // because we can avoid having to do a recursive walk until + // the walked tree is as shallow as possible. + // Note that this is only true up to the last pattern, though, because + // a/*/** will only match a/b if b is a dir, but a/**/* will match a/b + // regardless, since it's "0 or more path segments" if it's not final. + if (this.options.noglobstar) { + // ** is * anyway + this.globParts = rawGlobParts; + } + else { + // do this swap BEFORE the reduce, so that we can turn a string + // of **/*/**/* into */*/**/** and then reduce the **'s into one + for (const parts of rawGlobParts) { + let swapped; + do { + swapped = false; + for (let i = 0; i < parts.length - 1; i++) { + if (parts[i] === '*' && parts[i - 1] === '**') { + parts[i] = '**'; + parts[i - 1] = '*'; + swapped = true; + } + } + } while (swapped); + } + this.globParts = rawGlobParts.map(parts => { + parts = parts.reduce((set, part) => { + const prev = set[set.length - 1]; + if (part === '**' && prev === '**') { + return set; + } + if (part === '..') { + if (prev && prev !== '..' && prev !== '.' && prev !== '**') { + set.pop(); + return set; + } + } + set.push(part); + return set; + }, []); + return parts.length === 0 ? [''] : parts; + }); + } + this.debug(this.pattern, this.globParts); + // glob --> regexps + let set = this.globParts.map((s, _, __) => s.map(ss => this.parse(ss))); + this.debug(this.pattern, set); + // filter out everything that didn't compile properly. + this.set = set.filter(s => s.indexOf(false) === -1); + // do not treat the ? in UNC paths as magic + if (isWindows) { + for (let i = 0; i < this.set.length; i++) { + const p = this.set[i]; + if (p[0] === '' && + p[1] === '' && + this.globParts[i][2] === '?' && + typeof p[3] === 'string' && + /^[a-z]:$/i.test(p[3])) { + p[2] = '?'; + } + } + } + this.debug(this.pattern, this.set); + } + parseNegate() { + if (this.nonegate) + return; + const pattern = this.pattern; + let negate = false; + let negateOffset = 0; + for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { + negate = !negate; + negateOffset++; + } + if (negateOffset) + this.pattern = pattern.slice(negateOffset); + this.negate = negate; + } + // set partial to true to test if, for example, + // "/a/b" matches the start of "/*/b/*/d" + // Partial means, if you run out of file before you run + // out of pattern, then that's fine, as long as all + // the parts match. + matchOne(file, pattern, partial = false) { + const options = this.options; + // a UNC pattern like //?/c:/* can match a path like c:/x + // and vice versa + if (isWindows) { + const fileUNC = file[0] === '' && + file[1] === '' && + file[2] === '?' && + typeof file[3] === 'string' && + /^[a-z]:$/i.test(file[3]); + const patternUNC = pattern[0] === '' && + pattern[1] === '' && + pattern[2] === '?' && + typeof pattern[3] === 'string' && + /^[a-z]:$/i.test(pattern[3]); + if (fileUNC && patternUNC) { + const fd = file[3]; + const pd = pattern[3]; + if (fd.toLowerCase() === pd.toLowerCase()) { + file[3] = pd; + } + } + else if (patternUNC && typeof file[0] === 'string') { + const pd = pattern[3]; + const fd = file[0]; + if (pd.toLowerCase() === fd.toLowerCase()) { + pattern[3] = fd; + pattern = pattern.slice(3); + } + } + else if (fileUNC && typeof pattern[0] === 'string') { + const fd = file[3]; + if (fd.toLowerCase() === pattern[0].toLowerCase()) { + pattern[0] = fd; + file = file.slice(3); + } + } + } + this.debug('matchOne', this, { file, pattern }); + this.debug('matchOne', file.length, pattern.length); + for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { + this.debug('matchOne loop'); + var p = pattern[pi]; + var f = file[fi]; + this.debug(pattern, p, f); + // should be impossible. + // some invalid regexp stuff in the set. + /* c8 ignore start */ + if (p === false) { + return false; + } + /* c8 ignore stop */ + if (p === exports.GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]); + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi; + var pr = pi + 1; + if (pr === pl) { + this.debug('** at the end'); + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || + file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) + return false; + } + return true; + } + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr]; + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee); + // found a match. + return true; + } + else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || + swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr); + break; + } + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue'); + fr++; + } + } + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + /* c8 ignore start */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr); + if (fr === fl) { + return true; + } + } + /* c8 ignore stop */ + return false; + } + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + let hit; + if (typeof p === 'string') { + hit = f === p; + this.debug('string match', p, f, hit); + } + else { + hit = p.test(f); + this.debug('pattern match', p, f, hit); + } + if (!hit) + return false; + } + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true; + } + else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial; + } + else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return fi === fl - 1 && file[fi] === ''; + /* c8 ignore start */ + } + else { + // should be unreachable. + throw new Error('wtf?'); + } + /* c8 ignore stop */ + } + braceExpand() { + return (0, exports.braceExpand)(this.pattern, this.options); + } + parse(pattern, isSub) { + assertValidPattern(pattern); + const options = this.options; + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return exports.GLOBSTAR; + else + pattern = '*'; + } + if (pattern === '') + return ''; + // far and away, the most common glob pattern parts are + // *, *.*, and *. Add a fast check method for those. + let m; + let fastTest = null; + if (isSub !== SUBPARSE) { + if ((m = pattern.match(starRE))) { + fastTest = options.dot ? starTestDot : starTest; + } + else if ((m = pattern.match(starDotExtRE))) { + fastTest = (options.nocase + ? options.dot + ? starDotExtTestNocaseDot + : starDotExtTestNocase + : options.dot + ? starDotExtTestDot + : starDotExtTest)(m[1]); + } + else if ((m = pattern.match(qmarksRE))) { + fastTest = (options.nocase + ? options.dot + ? qmarksTestNocaseDot + : qmarksTestNocase + : options.dot + ? qmarksTestDot + : qmarksTest)(m); + } + else if ((m = pattern.match(starDotStarRE))) { + fastTest = options.dot ? starDotStarTestDot : starDotStarTest; + } + else if ((m = pattern.match(dotStarRE))) { + fastTest = dotStarTest; + } + } + let re = ''; + let hasMagic = false; + let escaping = false; + // ? => one single character + const patternListStack = []; + const negativeLists = []; + let stateChar = false; + let inClass = false; + let reClassStart = -1; + let classStart = -1; + let cs; + let pl; + let sp; + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. However, if the pattern + // starts with ., then traversal patterns can match. + let dotTravAllowed = pattern.charAt(0) === '.'; + let dotFileAllowed = options.dot || dotTravAllowed; + const patternStart = () => dotTravAllowed + ? '' + : dotFileAllowed + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)'; + const subPatternStart = (p) => p.charAt(0) === '.' + ? '' + : options.dot + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)'; + const clearStateChar = () => { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star; + hasMagic = true; + break; + case '?': + re += qmark; + hasMagic = true; + break; + default: + re += '\\' + stateChar; + break; + } + this.debug('clearStateChar %j %j', stateChar, re); + stateChar = false; + } + }; + for (let i = 0, c; i < pattern.length && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c); + // skip over any that are escaped. + if (escaping) { + // completely not allowed, even escaped. + // should be impossible. + /* c8 ignore start */ + if (c === '/') { + return false; + } + /* c8 ignore stop */ + if (reSpecials[c]) { + re += '\\'; + } + re += c; + escaping = false; + continue; + } + switch (c) { + // Should already be path-split by now. + /* c8 ignore start */ + case '/': { + return false; + } + /* c8 ignore stop */ + case '\\': + if (inClass && pattern.charAt(i + 1) === '-') { + re += c; + continue; + } + clearStateChar(); + escaping = true; + continue; + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class'); + if (c === '!' && i === classStart + 1) + c = '^'; + re += c; + continue; + } + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + this.debug('call clearStateChar %j', stateChar); + clearStateChar(); + stateChar = c; + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) + clearStateChar(); + continue; + case '(': { + if (inClass) { + re += '('; + continue; + } + if (!stateChar) { + re += '\\('; + continue; + } + const plEntry = { + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close, + }; + this.debug(this.pattern, '\t', plEntry); + patternListStack.push(plEntry); + // negation is (?:(?!(?:js)(?:))[^/]*) + re += plEntry.open; + // next entry starts with a dot maybe? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true; + re += subPatternStart(pattern.slice(i + 1)); + } + this.debug('plType %j %j', stateChar, re); + stateChar = false; + continue; + } + case ')': { + const plEntry = patternListStack[patternListStack.length - 1]; + if (inClass || !plEntry) { + re += '\\)'; + continue; + } + patternListStack.pop(); + // closing an extglob + clearStateChar(); + hasMagic = true; + pl = plEntry; + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close; + if (pl.type === '!') { + negativeLists.push(Object.assign(pl, { reEnd: re.length })); + } + continue; + } + case '|': { + const plEntry = patternListStack[patternListStack.length - 1]; + if (inClass || !plEntry) { + re += '\\|'; + continue; + } + clearStateChar(); + re += '|'; + // next subpattern can start with a dot? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true; + re += subPatternStart(pattern.slice(i + 1)); + } + continue; + } + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar(); + if (inClass) { + re += '\\' + c; + continue; + } + inClass = true; + classStart = i; + reClassStart = re.length; + re += c; + continue; + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c; + continue; + } + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + cs = pattern.substring(classStart + 1, i); + try { + RegExp('[' + braExpEscape(charUnescape(cs)) + ']'); + // looks good, finish up the class. + re += c; + } + catch (er) { + // out of order ranges in JS are errors, but in glob syntax, + // they're just a range that matches nothing. + re = re.substring(0, reClassStart) + '(?:$.)'; // match nothing ever + } + hasMagic = true; + inClass = false; + continue; + default: + // swallow any state char that wasn't consumed + clearStateChar(); + if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\'; + } + re += c; + break; + } // switch + } // for + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.slice(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re = re.substring(0, reClassStart) + '\\[' + sp[0]; + hasMagic = hasMagic || sp[1]; + } + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + let tail; + tail = re.slice(pl.reStart + pl.open.length); + this.debug(this.pattern, 'setting tail', re, pl); + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\'; + // should already be done + /* c8 ignore start */ + } + /* c8 ignore stop */ + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|'; + }); + this.debug('tail=%j\n %s', tail, tail, pl, re); + const t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type; + hasMagic = true; + re = re.slice(0, pl.reStart) + t + '\\(' + tail; + } + // handle trailing things that only matter at the very end. + clearStateChar(); + if (escaping) { + // trailing \\ + re += '\\\\'; + } + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + const addPatternStart = addPatternStartSet[re.charAt(0)]; + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (let n = negativeLists.length - 1; n > -1; n--) { + const nl = negativeLists[n]; + const nlBefore = re.slice(0, nl.reStart); + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8); + let nlAfter = re.slice(nl.reEnd); + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter; + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + const closeParensBefore = nlBefore.split(')').length; + const openParensBefore = nlBefore.split('(').length - closeParensBefore; + let cleanAfter = nlAfter; + for (let i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); + } + nlAfter = cleanAfter; + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : ''; + re = nlBefore + nlFirst + nlAfter + dollar + nlLast; + } + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re; + } + if (addPatternStart) { + re = patternStart() + re; + } + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic]; + } + // if it's nocase, and the lcase/uppercase don't match, it's magic + if (options.nocase && !hasMagic && !options.nocaseMagicOnly) { + hasMagic = pattern.toUpperCase() !== pattern.toLowerCase(); + } + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern); + } + const flags = options.nocase ? 'i' : ''; + try { + const ext = fastTest + ? { + _glob: pattern, + _src: re, + test: fastTest, + } + : { + _glob: pattern, + _src: re, + }; + return Object.assign(new RegExp('^' + re + '$', flags), ext); + /* c8 ignore start */ + } + catch (er) { + // should be impossible + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + this.debug('invalid regexp', er); + return new RegExp('$.'); + } + /* c8 ignore stop */ + } + makeRe() { + if (this.regexp || this.regexp === false) + return this.regexp; + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + const set = this.set; + if (!set.length) { + this.regexp = false; + return this.regexp; + } + const options = this.options; + const twoStar = options.noglobstar + ? star + : options.dot + ? twoStarDot + : twoStarNoDot; + const flags = options.nocase ? 'i' : ''; + // regexpify non-globstar patterns + // if ** is only item, then we just do one twoStar + // if ** is first, and there are more, prepend (\/|twoStar\/)? to next + // if ** is last, append (\/twoStar|) to previous + // if ** is in the middle, append (\/|\/twoStar\/) to previous + // then filter out GLOBSTAR symbols + let re = set + .map(pattern => { + const pp = pattern.map(p => typeof p === 'string' + ? regExpEscape(p) + : p === exports.GLOBSTAR + ? exports.GLOBSTAR + : p._src); + pp.forEach((p, i) => { + const next = pp[i + 1]; + const prev = pp[i - 1]; + if (p !== exports.GLOBSTAR || prev === exports.GLOBSTAR) { + return; + } + if (prev === undefined) { + if (next !== undefined && next !== exports.GLOBSTAR) { + pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next; + } + else { + pp[i] = twoStar; + } + } + else if (next === undefined) { + pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?'; + } + else if (next !== exports.GLOBSTAR) { + pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next; + pp[i + 1] = exports.GLOBSTAR; + } + }); + return pp.filter(p => p !== exports.GLOBSTAR).join('/'); + }) + .join('|'); + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$'; + // can match anything, as long as it's not this. + if (this.negate) + re = '^(?!' + re + ').*$'; + try { + this.regexp = new RegExp(re, flags); + /* c8 ignore start */ + } + catch (ex) { + // should be impossible + this.regexp = false; + } + /* c8 ignore stop */ + return this.regexp; + } + slashSplit(p) { + // if p starts with // on windows, we preserve that + // so that UNC paths aren't broken. Otherwise, any number of + // / characters are coalesced into one, unless + // preserveMultipleSlashes is set to true. + if (this.preserveMultipleSlashes) { + return p.split('/'); + } + else if (isWindows && /^\/\/[^\/]+/.test(p)) { + // add an extra '' for the one we lose + return ['', ...p.split(/\/+/)]; + } + else { + return p.split(/\/+/); + } + } + match(f, partial = this.partial) { + this.debug('match', f, this.pattern); + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) { + return false; + } + if (this.empty) { + return f === ''; + } + if (f === '/' && partial) { + return true; + } + const options = this.options; + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/'); + } + // treat the test path as a set of pathparts. + const ff = this.slashSplit(f); + this.debug(this.pattern, 'split', ff); + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + const set = this.set; + this.debug(this.pattern, 'set', set); + // Find the basename of the path by looking for the last non-empty segment + let filename = ff[ff.length - 1]; + if (!filename) { + for (let i = ff.length - 2; !filename && i >= 0; i--) { + filename = ff[i]; + } + } + for (let i = 0; i < set.length; i++) { + const pattern = set[i]; + let file = ff; + if (options.matchBase && pattern.length === 1) { + file = [filename]; + } + const hit = this.matchOne(file, pattern, partial); + if (hit) { + if (options.flipNegate) { + return true; + } + return !this.negate; + } + } + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) { + return false; + } + return this.negate; + } + static defaults(def) { + return exports.minimatch.defaults(def).Minimatch; + } +} +exports.Minimatch = Minimatch; +exports.minimatch.Minimatch = Minimatch; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.js.map b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.js.map new file mode 100644 index 0000000..0f561db --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAmBO,MAAM,SAAS,GAAG,CACvB,CAAS,EACT,OAAe,EACf,UAA4B,EAAE,EAC9B,EAAE;IACF,kBAAkB,CAAC,OAAO,CAAC,CAAA;IAE3B,oCAAoC;IACpC,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;QACnD,OAAO,KAAK,CAAA;KACb;IAED,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC,CAAA;AAbY,QAAA,SAAS,aAarB;AAED,kBAAe,iBAAS,CAAA;AAExB,wDAAwD;AACxD,MAAM,YAAY,GAAG,uBAAuB,CAAA;AAC5C,MAAM,cAAc,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,CAAS,EAAE,EAAE,CACpD,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;AACvC,MAAM,iBAAiB,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;AACzE,MAAM,oBAAoB,GAAG,CAAC,GAAW,EAAE,EAAE;IAC3C,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,CAAA;IACvB,OAAO,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;AAC3E,CAAC,CAAA;AACD,MAAM,uBAAuB,GAAG,CAAC,GAAW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QAAQ,GAAG,EAAE,CAAC,CAAC,CAAC,CAAA;aACjB;SACF;QAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACnC,MAAM,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,CAAA;YACtB,IAAI,IAAI,GAAG,EAAE,CAAA;YACb,IAAI,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC7C,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAA;aAClB;YACD,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;YACjD,IAAI,GAAG,EAAE;gBACP,IAAI,OAAO,CAAC,UAAU,EAAE;oBACtB,OAAO,IAAI,CAAA;iBACZ;gBACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAA;aACpB;SACF;QAED,2DAA2D;QAC3D,8BAA8B;QAC9B,IAAI,OAAO,CAAC,UAAU,EAAE;YACtB,OAAO,KAAK,CAAA;SACb;QACD,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,GAAqB;QACnC,OAAO,iBAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,SAAS,CAAA;IAC1C,CAAC;CACF;AAt+BD,8BAs+BC;AAED,iBAAS,CAAC,SAAS,GAAG,SAAS,CAAA"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/package.json b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/cjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.d.ts b/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.d.ts new file mode 100644 index 0000000..cca07a8 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.d.ts @@ -0,0 +1,71 @@ +export interface MinimatchOptions { + nobrace?: boolean; + nocomment?: boolean; + nonegate?: boolean; + debug?: boolean; + noglobstar?: boolean; + noext?: boolean; + nonull?: boolean; + windowsPathsNoEscape?: boolean; + allowWindowsEscape?: boolean; + partial?: boolean; + dot?: boolean; + nocase?: boolean; + nocaseMagicOnly?: boolean; + matchBase?: boolean; + flipNegate?: boolean; + preserveMultipleSlashes?: boolean; +} +export declare const minimatch: { + (p: string, pattern: string, options?: MinimatchOptions): boolean; + sep: string; + GLOBSTAR: typeof GLOBSTAR; + filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean; + defaults: (def: MinimatchOptions) => typeof minimatch; + braceExpand: (pattern: string, options?: MinimatchOptions) => string[]; + makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp; + match: (list: string[], pattern: string, options?: MinimatchOptions) => string[]; + Minimatch: typeof Minimatch; +}; +export default minimatch; +export declare const sep: string; +export declare const GLOBSTAR: unique symbol; +export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean; +export declare const defaults: (def: MinimatchOptions) => typeof minimatch; +export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[]; +declare const SUBPARSE: unique symbol; +export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp; +export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[]; +export type MMRegExp = RegExp & { + _src?: string; + _glob?: string; +}; +type SubparseReturn = [string, boolean]; +type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR; +type ParseReturn = ParseReturnFiltered | false; +export declare class Minimatch { + options: MinimatchOptions; + set: ParseReturnFiltered[][]; + pattern: string; + windowsPathsNoEscape: boolean; + nonegate: boolean; + negate: boolean; + comment: boolean; + empty: boolean; + preserveMultipleSlashes: boolean; + partial: boolean; + globSet: string[]; + globParts: string[][]; + regexp: false | null | MMRegExp; + constructor(pattern: string, options?: MinimatchOptions); + debug(..._: any[]): void; + make(): void; + parseNegate(): void; + matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean; + braceExpand(): string[]; + parse(pattern: string, isSub?: typeof SUBPARSE): ParseReturn | SubparseReturn; + makeRe(): false | MMRegExp; + slashSplit(p: string): string[]; + match(f: string, partial?: boolean): boolean; + static defaults(def: MinimatchOptions): typeof Minimatch; +} diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.js b/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.js new file mode 100644 index 0000000..59ac196 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.js @@ -0,0 +1,1077 @@ +export const minimatch = (p, pattern, options = {}) => { + assertValidPattern(pattern); + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false; + } + return new Minimatch(pattern, options).match(p); +}; +export default minimatch; +// Optimized checking for the most common glob patterns. +const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; +const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext); +const starDotExtTestDot = (ext) => (f) => f.endsWith(ext); +const starDotExtTestNocase = (ext) => { + ext = ext.toLowerCase(); + return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext); +}; +const starDotExtTestNocaseDot = (ext) => { + ext = ext.toLowerCase(); + return (f) => f.toLowerCase().endsWith(ext); +}; +const starDotStarRE = /^\*+\.\*+$/; +const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.'); +const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.'); +const dotStarRE = /^\.\*+$/; +const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.'); +const starRE = /^\*+$/; +const starTest = (f) => f.length !== 0 && !f.startsWith('.'); +const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..'; +const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; +const qmarksTestNocase = ([$0, ext = '']) => { + const noext = qmarksTestNoExt([$0]); + if (!ext) + return noext; + ext = ext.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext); +}; +const qmarksTestNocaseDot = ([$0, ext = '']) => { + const noext = qmarksTestNoExtDot([$0]); + if (!ext) + return noext; + ext = ext.toLowerCase(); + return (f) => noext(f) && f.toLowerCase().endsWith(ext); +}; +const qmarksTestDot = ([$0, ext = '']) => { + const noext = qmarksTestNoExtDot([$0]); + return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +}; +const qmarksTest = ([$0, ext = '']) => { + const noext = qmarksTestNoExt([$0]); + return !ext ? noext : (f) => noext(f) && f.endsWith(ext); +}; +const qmarksTestNoExt = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && !f.startsWith('.'); +}; +const qmarksTestNoExtDot = ([$0]) => { + const len = $0.length; + return (f) => f.length === len && f !== '.' && f !== '..'; +}; +/* c8 ignore start */ +const platform = typeof process === 'object' && process + ? (typeof process.env === 'object' && + process.env && + process.env.__MINIMATCH_TESTING_PLATFORM__) || + process.platform + : 'posix'; +const isWindows = platform === 'win32'; +const path = isWindows ? { sep: '\\' } : { sep: '/' }; +/* c8 ignore stop */ +export const sep = path.sep; +minimatch.sep = sep; +export const GLOBSTAR = Symbol('globstar **'); +minimatch.GLOBSTAR = GLOBSTAR; +import expand from 'brace-expansion'; +const plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)' }, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' }, +}; +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]'; +// * => any number of characters +const star = qmark + '*?'; +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?'; +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?'; +// "abc" -> { a:true, b:true, c:true } +const charSet = (s) => s.split('').reduce((set, c) => { + set[c] = true; + return set; +}, {}); +// characters that need to be escaped in RegExp. +const reSpecials = charSet('().*{}+?[]^$\\!'); +// characters that indicate we have to add the pattern start +const addPatternStartSet = charSet('[.('); +export const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options); +minimatch.filter = filter; +const ext = (a, b = {}) => Object.assign({}, a, b); +export const defaults = (def) => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch; + } + const orig = minimatch; + const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options)); + return Object.assign(m, { + Minimatch: class Minimatch extends orig.Minimatch { + constructor(pattern, options = {}) { + super(pattern, ext(def, options)); + } + static defaults(options) { + return orig.defaults(ext(def, options)).Minimatch; + } + }, + filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)), + defaults: (options) => orig.defaults(ext(def, options)), + makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)), + braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)), + match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)), + sep: orig.sep, + GLOBSTAR: GLOBSTAR, + }); +}; +minimatch.defaults = defaults; +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +export const braceExpand = (pattern, options = {}) => { + assertValidPattern(pattern); + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern]; + } + return expand(pattern); +}; +minimatch.braceExpand = braceExpand; +const MAX_PATTERN_LENGTH = 1024 * 64; +const assertValidPattern = (pattern) => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern'); + } + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long'); + } +}; +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const SUBPARSE = Symbol('subparse'); +export const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe(); +minimatch.makeRe = makeRe; +export const match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options); + list = list.filter(f => mm.match(f)); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list; +}; +minimatch.match = match; +// replace stuff like \* with * +const globUnescape = (s) => s.replace(/\\(.)/g, '$1'); +const charUnescape = (s) => s.replace(/\\([^-\]])/g, '$1'); +const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +const braExpEscape = (s) => s.replace(/[[\]\\]/g, '\\$&'); +export class Minimatch { + options; + set; + pattern; + windowsPathsNoEscape; + nonegate; + negate; + comment; + empty; + preserveMultipleSlashes; + partial; + globSet; + globParts; + regexp; + constructor(pattern, options = {}) { + assertValidPattern(pattern); + options = options || {}; + this.options = options; + this.pattern = pattern; + this.windowsPathsNoEscape = + !!options.windowsPathsNoEscape || options.allowWindowsEscape === false; + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/'); + } + this.preserveMultipleSlashes = !!options.preserveMultipleSlashes; + this.regexp = null; + this.negate = false; + this.nonegate = !!options.nonegate; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + this.globSet = []; + this.globParts = []; + this.set = []; + // make the set of regexps etc. + this.make(); + } + debug(..._) { } + make() { + const pattern = this.pattern; + const options = this.options; + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true; + return; + } + if (!pattern) { + this.empty = true; + return; + } + // step 1: figure out negation, etc. + this.parseNegate(); + // step 2: expand braces + this.globSet = this.braceExpand(); + if (options.debug) { + this.debug = (...args) => console.error(...args); + } + this.debug(this.pattern, this.globSet); + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + const rawGlobParts = this.globSet.map(s => this.slashSplit(s)); + // consecutive globstars are an unncessary perf killer + // also, **/*/... is equivalent to */**/..., so swap all of those + // this turns a pattern like **/*/**/*/x into */*/**/x + // and a pattern like **/x/**/*/y becomes **/x/*/**/y + // the *later* we can push the **, the more efficient it is, + // because we can avoid having to do a recursive walk until + // the walked tree is as shallow as possible. + // Note that this is only true up to the last pattern, though, because + // a/*/** will only match a/b if b is a dir, but a/**/* will match a/b + // regardless, since it's "0 or more path segments" if it's not final. + if (this.options.noglobstar) { + // ** is * anyway + this.globParts = rawGlobParts; + } + else { + // do this swap BEFORE the reduce, so that we can turn a string + // of **/*/**/* into */*/**/** and then reduce the **'s into one + for (const parts of rawGlobParts) { + let swapped; + do { + swapped = false; + for (let i = 0; i < parts.length - 1; i++) { + if (parts[i] === '*' && parts[i - 1] === '**') { + parts[i] = '**'; + parts[i - 1] = '*'; + swapped = true; + } + } + } while (swapped); + } + this.globParts = rawGlobParts.map(parts => { + parts = parts.reduce((set, part) => { + const prev = set[set.length - 1]; + if (part === '**' && prev === '**') { + return set; + } + if (part === '..') { + if (prev && prev !== '..' && prev !== '.' && prev !== '**') { + set.pop(); + return set; + } + } + set.push(part); + return set; + }, []); + return parts.length === 0 ? [''] : parts; + }); + } + this.debug(this.pattern, this.globParts); + // glob --> regexps + let set = this.globParts.map((s, _, __) => s.map(ss => this.parse(ss))); + this.debug(this.pattern, set); + // filter out everything that didn't compile properly. + this.set = set.filter(s => s.indexOf(false) === -1); + // do not treat the ? in UNC paths as magic + if (isWindows) { + for (let i = 0; i < this.set.length; i++) { + const p = this.set[i]; + if (p[0] === '' && + p[1] === '' && + this.globParts[i][2] === '?' && + typeof p[3] === 'string' && + /^[a-z]:$/i.test(p[3])) { + p[2] = '?'; + } + } + } + this.debug(this.pattern, this.set); + } + parseNegate() { + if (this.nonegate) + return; + const pattern = this.pattern; + let negate = false; + let negateOffset = 0; + for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { + negate = !negate; + negateOffset++; + } + if (negateOffset) + this.pattern = pattern.slice(negateOffset); + this.negate = negate; + } + // set partial to true to test if, for example, + // "/a/b" matches the start of "/*/b/*/d" + // Partial means, if you run out of file before you run + // out of pattern, then that's fine, as long as all + // the parts match. + matchOne(file, pattern, partial = false) { + const options = this.options; + // a UNC pattern like //?/c:/* can match a path like c:/x + // and vice versa + if (isWindows) { + const fileUNC = file[0] === '' && + file[1] === '' && + file[2] === '?' && + typeof file[3] === 'string' && + /^[a-z]:$/i.test(file[3]); + const patternUNC = pattern[0] === '' && + pattern[1] === '' && + pattern[2] === '?' && + typeof pattern[3] === 'string' && + /^[a-z]:$/i.test(pattern[3]); + if (fileUNC && patternUNC) { + const fd = file[3]; + const pd = pattern[3]; + if (fd.toLowerCase() === pd.toLowerCase()) { + file[3] = pd; + } + } + else if (patternUNC && typeof file[0] === 'string') { + const pd = pattern[3]; + const fd = file[0]; + if (pd.toLowerCase() === fd.toLowerCase()) { + pattern[3] = fd; + pattern = pattern.slice(3); + } + } + else if (fileUNC && typeof pattern[0] === 'string') { + const fd = file[3]; + if (fd.toLowerCase() === pattern[0].toLowerCase()) { + pattern[0] = fd; + file = file.slice(3); + } + } + } + this.debug('matchOne', this, { file, pattern }); + this.debug('matchOne', file.length, pattern.length); + for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { + this.debug('matchOne loop'); + var p = pattern[pi]; + var f = file[fi]; + this.debug(pattern, p, f); + // should be impossible. + // some invalid regexp stuff in the set. + /* c8 ignore start */ + if (p === false) { + return false; + } + /* c8 ignore stop */ + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]); + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi; + var pr = pi + 1; + if (pr === pl) { + this.debug('** at the end'); + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || + file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) + return false; + } + return true; + } + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr]; + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee); + // found a match. + return true; + } + else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || + swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr); + break; + } + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue'); + fr++; + } + } + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + /* c8 ignore start */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr); + if (fr === fl) { + return true; + } + } + /* c8 ignore stop */ + return false; + } + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + let hit; + if (typeof p === 'string') { + hit = f === p; + this.debug('string match', p, f, hit); + } + else { + hit = p.test(f); + this.debug('pattern match', p, f, hit); + } + if (!hit) + return false; + } + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true; + } + else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial; + } + else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return fi === fl - 1 && file[fi] === ''; + /* c8 ignore start */ + } + else { + // should be unreachable. + throw new Error('wtf?'); + } + /* c8 ignore stop */ + } + braceExpand() { + return braceExpand(this.pattern, this.options); + } + parse(pattern, isSub) { + assertValidPattern(pattern); + const options = this.options; + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR; + else + pattern = '*'; + } + if (pattern === '') + return ''; + // far and away, the most common glob pattern parts are + // *, *.*, and *. Add a fast check method for those. + let m; + let fastTest = null; + if (isSub !== SUBPARSE) { + if ((m = pattern.match(starRE))) { + fastTest = options.dot ? starTestDot : starTest; + } + else if ((m = pattern.match(starDotExtRE))) { + fastTest = (options.nocase + ? options.dot + ? starDotExtTestNocaseDot + : starDotExtTestNocase + : options.dot + ? starDotExtTestDot + : starDotExtTest)(m[1]); + } + else if ((m = pattern.match(qmarksRE))) { + fastTest = (options.nocase + ? options.dot + ? qmarksTestNocaseDot + : qmarksTestNocase + : options.dot + ? qmarksTestDot + : qmarksTest)(m); + } + else if ((m = pattern.match(starDotStarRE))) { + fastTest = options.dot ? starDotStarTestDot : starDotStarTest; + } + else if ((m = pattern.match(dotStarRE))) { + fastTest = dotStarTest; + } + } + let re = ''; + let hasMagic = false; + let escaping = false; + // ? => one single character + const patternListStack = []; + const negativeLists = []; + let stateChar = false; + let inClass = false; + let reClassStart = -1; + let classStart = -1; + let cs; + let pl; + let sp; + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. However, if the pattern + // starts with ., then traversal patterns can match. + let dotTravAllowed = pattern.charAt(0) === '.'; + let dotFileAllowed = options.dot || dotTravAllowed; + const patternStart = () => dotTravAllowed + ? '' + : dotFileAllowed + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)'; + const subPatternStart = (p) => p.charAt(0) === '.' + ? '' + : options.dot + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)'; + const clearStateChar = () => { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star; + hasMagic = true; + break; + case '?': + re += qmark; + hasMagic = true; + break; + default: + re += '\\' + stateChar; + break; + } + this.debug('clearStateChar %j %j', stateChar, re); + stateChar = false; + } + }; + for (let i = 0, c; i < pattern.length && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c); + // skip over any that are escaped. + if (escaping) { + // completely not allowed, even escaped. + // should be impossible. + /* c8 ignore start */ + if (c === '/') { + return false; + } + /* c8 ignore stop */ + if (reSpecials[c]) { + re += '\\'; + } + re += c; + escaping = false; + continue; + } + switch (c) { + // Should already be path-split by now. + /* c8 ignore start */ + case '/': { + return false; + } + /* c8 ignore stop */ + case '\\': + if (inClass && pattern.charAt(i + 1) === '-') { + re += c; + continue; + } + clearStateChar(); + escaping = true; + continue; + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class'); + if (c === '!' && i === classStart + 1) + c = '^'; + re += c; + continue; + } + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + this.debug('call clearStateChar %j', stateChar); + clearStateChar(); + stateChar = c; + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) + clearStateChar(); + continue; + case '(': { + if (inClass) { + re += '('; + continue; + } + if (!stateChar) { + re += '\\('; + continue; + } + const plEntry = { + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close, + }; + this.debug(this.pattern, '\t', plEntry); + patternListStack.push(plEntry); + // negation is (?:(?!(?:js)(?:))[^/]*) + re += plEntry.open; + // next entry starts with a dot maybe? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true; + re += subPatternStart(pattern.slice(i + 1)); + } + this.debug('plType %j %j', stateChar, re); + stateChar = false; + continue; + } + case ')': { + const plEntry = patternListStack[patternListStack.length - 1]; + if (inClass || !plEntry) { + re += '\\)'; + continue; + } + patternListStack.pop(); + // closing an extglob + clearStateChar(); + hasMagic = true; + pl = plEntry; + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close; + if (pl.type === '!') { + negativeLists.push(Object.assign(pl, { reEnd: re.length })); + } + continue; + } + case '|': { + const plEntry = patternListStack[patternListStack.length - 1]; + if (inClass || !plEntry) { + re += '\\|'; + continue; + } + clearStateChar(); + re += '|'; + // next subpattern can start with a dot? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true; + re += subPatternStart(pattern.slice(i + 1)); + } + continue; + } + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar(); + if (inClass) { + re += '\\' + c; + continue; + } + inClass = true; + classStart = i; + reClassStart = re.length; + re += c; + continue; + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c; + continue; + } + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + cs = pattern.substring(classStart + 1, i); + try { + RegExp('[' + braExpEscape(charUnescape(cs)) + ']'); + // looks good, finish up the class. + re += c; + } + catch (er) { + // out of order ranges in JS are errors, but in glob syntax, + // they're just a range that matches nothing. + re = re.substring(0, reClassStart) + '(?:$.)'; // match nothing ever + } + hasMagic = true; + inClass = false; + continue; + default: + // swallow any state char that wasn't consumed + clearStateChar(); + if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\'; + } + re += c; + break; + } // switch + } // for + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.slice(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re = re.substring(0, reClassStart) + '\\[' + sp[0]; + hasMagic = hasMagic || sp[1]; + } + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + let tail; + tail = re.slice(pl.reStart + pl.open.length); + this.debug(this.pattern, 'setting tail', re, pl); + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\'; + // should already be done + /* c8 ignore start */ + } + /* c8 ignore stop */ + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|'; + }); + this.debug('tail=%j\n %s', tail, tail, pl, re); + const t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type; + hasMagic = true; + re = re.slice(0, pl.reStart) + t + '\\(' + tail; + } + // handle trailing things that only matter at the very end. + clearStateChar(); + if (escaping) { + // trailing \\ + re += '\\\\'; + } + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + const addPatternStart = addPatternStartSet[re.charAt(0)]; + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (let n = negativeLists.length - 1; n > -1; n--) { + const nl = negativeLists[n]; + const nlBefore = re.slice(0, nl.reStart); + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8); + let nlAfter = re.slice(nl.reEnd); + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter; + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + const closeParensBefore = nlBefore.split(')').length; + const openParensBefore = nlBefore.split('(').length - closeParensBefore; + let cleanAfter = nlAfter; + for (let i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); + } + nlAfter = cleanAfter; + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : ''; + re = nlBefore + nlFirst + nlAfter + dollar + nlLast; + } + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re; + } + if (addPatternStart) { + re = patternStart() + re; + } + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic]; + } + // if it's nocase, and the lcase/uppercase don't match, it's magic + if (options.nocase && !hasMagic && !options.nocaseMagicOnly) { + hasMagic = pattern.toUpperCase() !== pattern.toLowerCase(); + } + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern); + } + const flags = options.nocase ? 'i' : ''; + try { + const ext = fastTest + ? { + _glob: pattern, + _src: re, + test: fastTest, + } + : { + _glob: pattern, + _src: re, + }; + return Object.assign(new RegExp('^' + re + '$', flags), ext); + /* c8 ignore start */ + } + catch (er) { + // should be impossible + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + this.debug('invalid regexp', er); + return new RegExp('$.'); + } + /* c8 ignore stop */ + } + makeRe() { + if (this.regexp || this.regexp === false) + return this.regexp; + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + const set = this.set; + if (!set.length) { + this.regexp = false; + return this.regexp; + } + const options = this.options; + const twoStar = options.noglobstar + ? star + : options.dot + ? twoStarDot + : twoStarNoDot; + const flags = options.nocase ? 'i' : ''; + // regexpify non-globstar patterns + // if ** is only item, then we just do one twoStar + // if ** is first, and there are more, prepend (\/|twoStar\/)? to next + // if ** is last, append (\/twoStar|) to previous + // if ** is in the middle, append (\/|\/twoStar\/) to previous + // then filter out GLOBSTAR symbols + let re = set + .map(pattern => { + const pp = pattern.map(p => typeof p === 'string' + ? regExpEscape(p) + : p === GLOBSTAR + ? GLOBSTAR + : p._src); + pp.forEach((p, i) => { + const next = pp[i + 1]; + const prev = pp[i - 1]; + if (p !== GLOBSTAR || prev === GLOBSTAR) { + return; + } + if (prev === undefined) { + if (next !== undefined && next !== GLOBSTAR) { + pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next; + } + else { + pp[i] = twoStar; + } + } + else if (next === undefined) { + pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?'; + } + else if (next !== GLOBSTAR) { + pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next; + pp[i + 1] = GLOBSTAR; + } + }); + return pp.filter(p => p !== GLOBSTAR).join('/'); + }) + .join('|'); + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$'; + // can match anything, as long as it's not this. + if (this.negate) + re = '^(?!' + re + ').*$'; + try { + this.regexp = new RegExp(re, flags); + /* c8 ignore start */ + } + catch (ex) { + // should be impossible + this.regexp = false; + } + /* c8 ignore stop */ + return this.regexp; + } + slashSplit(p) { + // if p starts with // on windows, we preserve that + // so that UNC paths aren't broken. Otherwise, any number of + // / characters are coalesced into one, unless + // preserveMultipleSlashes is set to true. + if (this.preserveMultipleSlashes) { + return p.split('/'); + } + else if (isWindows && /^\/\/[^\/]+/.test(p)) { + // add an extra '' for the one we lose + return ['', ...p.split(/\/+/)]; + } + else { + return p.split(/\/+/); + } + } + match(f, partial = this.partial) { + this.debug('match', f, this.pattern); + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) { + return false; + } + if (this.empty) { + return f === ''; + } + if (f === '/' && partial) { + return true; + } + const options = this.options; + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/'); + } + // treat the test path as a set of pathparts. + const ff = this.slashSplit(f); + this.debug(this.pattern, 'split', ff); + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + const set = this.set; + this.debug(this.pattern, 'set', set); + // Find the basename of the path by looking for the last non-empty segment + let filename = ff[ff.length - 1]; + if (!filename) { + for (let i = ff.length - 2; !filename && i >= 0; i--) { + filename = ff[i]; + } + } + for (let i = 0; i < set.length; i++) { + const pattern = set[i]; + let file = ff; + if (options.matchBase && pattern.length === 1) { + file = [filename]; + } + const hit = this.matchOne(file, pattern, partial); + if (hit) { + if (options.flipNegate) { + return true; + } + return !this.negate; + } + } + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) { + return false; + } + return this.negate; + } + static defaults(def) { + return minimatch.defaults(def).Minimatch; + } +} +minimatch.Minimatch = Minimatch; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.js.map b/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.js.map new file mode 100644 index 0000000..854172c --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAmBA,MAAM,CAAC,MAAM,SAAS,GAAG,CACvB,CAAS,EACT,OAAe,EACf,UAA4B,EAAE,EAC9B,EAAE;IACF,kBAAkB,CAAC,OAAO,CAAC,CAAA;IAE3B,oCAAoC;IACpC,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;QACnD,OAAO,KAAK,CAAA;KACb;IAED,OAAO,IAAI,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;AACjD,CAAC,CAAA;AAED,eAAe,SAAS,CAAA;AAExB,wDAAwD;AACxD,MAAM,YAAY,GAAG,uBAAuB,CAAA;AAC5C,MAAM,cAAc,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,CAAS,EAAE,EAAE,CACpD,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;AACvC,MAAM,iBAAiB,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,CAAC,CAAS,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;AACzE,MAAM,oBAAoB,GAAG,CAAC,GAAW,EAAE,EAAE;IAC3C,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,C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I,CAAC,QAAQ,EAAE;YACb,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;gBACpD,QAAQ,GAAG,EAAE,CAAC,CAAC,CAAC,CAAA;aACjB;SACF;QAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACnC,MAAM,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,CAAA;YACtB,IAAI,IAAI,GAAG,EAAE,CAAA;YACb,IAAI,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC7C,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAA;aAClB;YACD,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;YACjD,IAAI,GAAG,EAAE;gBACP,IAAI,OAAO,CAAC,UAAU,EAAE;oBACtB,OAAO,IAAI,CAAA;iBACZ;gBACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAA;aACpB;SACF;QAED,2DAA2D;QAC3D,8BAA8B;QAC9B,IAAI,OAAO,CAAC,UAAU,EAAE;YACtB,OAAO,KAAK,CAAA;SACb;QACD,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,MAAM,CAAC,QAAQ,CAAC,GAAqB;QACnC,OAAO,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,SAAS,CAAA;IAC1C,CAAC;CACF;AAED,SAAS,CAAC,SAAS,GAAG,SAAS,CAAA"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/package.json b/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/minimatch/dist/mjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/index.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/index.js new file mode 100644 index 0000000..6e76a32 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/index.js @@ -0,0 +1,24 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _processor = _interopRequireDefault(require("./processor")); + +var selectors = _interopRequireWildcard(require("./selectors")); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +var parser = function parser(processor) { + return new _processor["default"](processor); +}; + +Object.assign(parser, selectors); +delete parser.__esModule; +var _default = parser; +exports["default"] = _default; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/parser.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/parser.js new file mode 100644 index 0000000..b97a0fa --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/parser.js @@ -0,0 +1,1243 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _root = _interopRequireDefault(require("./selectors/root")); + +var _selector = _interopRequireDefault(require("./selectors/selector")); + +var _className = _interopRequireDefault(require("./selectors/className")); + +var _comment = _interopRequireDefault(require("./selectors/comment")); + +var _id = _interopRequireDefault(require("./selectors/id")); + +var _tag = _interopRequireDefault(require("./selectors/tag")); + +var _string = _interopRequireDefault(require("./selectors/string")); + +var _pseudo = _interopRequireDefault(require("./selectors/pseudo")); + +var _attribute = _interopRequireWildcard(require("./selectors/attribute")); + +var _universal = _interopRequireDefault(require("./selectors/universal")); + +var _combinator = _interopRequireDefault(require("./selectors/combinator")); + +var _nesting = _interopRequireDefault(require("./selectors/nesting")); + +var _sortAscending = _interopRequireDefault(require("./sortAscending")); + +var _tokenize = _interopRequireWildcard(require("./tokenize")); + +var tokens = _interopRequireWildcard(require("./tokenTypes")); + +var types = _interopRequireWildcard(require("./selectors/types")); + +var _util = require("./util"); + +var _WHITESPACE_TOKENS, _Object$assign; + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS); +var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign)); + +function tokenStart(token) { + return { + line: token[_tokenize.FIELDS.START_LINE], + column: token[_tokenize.FIELDS.START_COL] + }; +} + +function tokenEnd(token) { + return { + line: token[_tokenize.FIELDS.END_LINE], + column: token[_tokenize.FIELDS.END_COL] + }; +} + +function getSource(startLine, startColumn, endLine, endColumn) { + return { + start: { + line: startLine, + column: startColumn + }, + end: { + line: endLine, + column: endColumn + } + }; +} + +function getTokenSource(token) { + return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]); +} + +function getTokenSourceSpan(startToken, endToken) { + if (!startToken) { + return undefined; + } + + return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]); +} + +function unescapeProp(node, prop) { + var value = node[prop]; + + if (typeof value !== "string") { + return; + } + + if (value.indexOf("\\") !== -1) { + (0, _util.ensureObject)(node, 'raws'); + node[prop] = (0, _util.unesc)(value); + + if (node.raws[prop] === undefined) { + node.raws[prop] = value; + } + } + + return node; +} + +function indexesOf(array, item) { + var i = -1; + var indexes = []; + + while ((i = array.indexOf(item, i + 1)) !== -1) { + indexes.push(i); + } + + return indexes; +} + +function uniqs() { + var list = Array.prototype.concat.apply([], arguments); + return list.filter(function (item, i) { + return i === list.indexOf(item); + }); +} + +var Parser = /*#__PURE__*/function () { + function Parser(rule, options) { + if (options === void 0) { + options = {}; + } + + this.rule = rule; + this.options = Object.assign({ + lossy: false, + safe: false + }, options); + this.position = 0; + this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector; + this.tokens = (0, _tokenize["default"])({ + css: this.css, + error: this._errorGenerator(), + safe: this.options.safe + }); + var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]); + this.root = new _root["default"]({ + source: rootSource + }); + this.root.errorGenerator = this._errorGenerator(); + var selector = new _selector["default"]({ + source: { + start: { + line: 1, + column: 1 + } + } + }); + this.root.append(selector); + this.current = selector; + this.loop(); + } + + var _proto = Parser.prototype; + + _proto._errorGenerator = function _errorGenerator() { + var _this = this; + + return function (message, errorOptions) { + if (typeof _this.rule === 'string') { + return new Error(message); + } + + return _this.rule.error(message, errorOptions); + }; + }; + + _proto.attribute = function attribute() { + var attr = []; + var startingToken = this.currToken; + this.position++; + + while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) { + attr.push(this.currToken); + this.position++; + } + + if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) { + return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]); + } + + var len = attr.length; + var node = { + source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]), + sourceIndex: startingToken[_tokenize.FIELDS.START_POS] + }; + + if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) { + return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]); + } + + var pos = 0; + var spaceBefore = ''; + var commentBefore = ''; + var lastAdded = null; + var spaceAfterMeaningfulToken = false; + + while (pos < len) { + var token = attr[pos]; + var content = this.content(token); + var next = attr[pos + 1]; + + switch (token[_tokenize.FIELDS.TYPE]) { + case tokens.space: + // if ( + // len === 1 || + // pos === 0 && this.content(next) === '|' + // ) { + // return this.expected('attribute', token[TOKEN.START_POS], content); + // } + spaceAfterMeaningfulToken = true; + + if (this.options.lossy) { + break; + } + + if (lastAdded) { + (0, _util.ensureObject)(node, 'spaces', lastAdded); + var prevContent = node.spaces[lastAdded].after || ''; + node.spaces[lastAdded].after = prevContent + content; + var existingComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null; + + if (existingComment) { + node.raws.spaces[lastAdded].after = existingComment + content; + } + } else { + spaceBefore = spaceBefore + content; + commentBefore = commentBefore + content; + } + + break; + + case tokens.asterisk: + if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) { + if (spaceBefore) { + (0, _util.ensureObject)(node, 'spaces', 'attribute'); + node.spaces.attribute.before = spaceBefore; + spaceBefore = ''; + } + + if (commentBefore) { + (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute'); + node.raws.spaces.attribute.before = spaceBefore; + commentBefore = ''; + } + + node.namespace = (node.namespace || "") + content; + var rawValue = (0, _util.getProp)(node, 'raws', 'namespace') || null; + + if (rawValue) { + node.raws.namespace += content; + } + + lastAdded = 'namespace'; + } + + spaceAfterMeaningfulToken = false; + break; + + case tokens.dollar: + if (lastAdded === "value") { + var oldRawValue = (0, _util.getProp)(node, 'raws', 'value'); + node.value += "$"; + + if (oldRawValue) { + node.raws.value = oldRawValue + "$"; + } + + break; + } + + // Falls through + + case tokens.caret: + if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } + + spaceAfterMeaningfulToken = false; + break; + + case tokens.combinator: + if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } + + if (content !== '|') { + spaceAfterMeaningfulToken = false; + break; + } + + if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { + node.operator = content; + lastAdded = 'operator'; + } else if (!node.namespace && !node.attribute) { + node.namespace = true; + } + + spaceAfterMeaningfulToken = false; + break; + + case tokens.word: + if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && // this look-ahead probably fails with comment nodes involved. + !node.operator && !node.namespace) { + node.namespace = content; + lastAdded = 'namespace'; + } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) { + if (spaceBefore) { + (0, _util.ensureObject)(node, 'spaces', 'attribute'); + node.spaces.attribute.before = spaceBefore; + spaceBefore = ''; + } + + if (commentBefore) { + (0, _util.ensureObject)(node, 'raws', 'spaces', 'attribute'); + node.raws.spaces.attribute.before = commentBefore; + commentBefore = ''; + } + + node.attribute = (node.attribute || "") + content; + + var _rawValue = (0, _util.getProp)(node, 'raws', 'attribute') || null; + + if (_rawValue) { + node.raws.attribute += content; + } + + lastAdded = 'attribute'; + } else if (!node.value && node.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node.quoteMark)) { + var _unescaped = (0, _util.unesc)(content); + + var _oldRawValue = (0, _util.getProp)(node, 'raws', 'value') || ''; + + var oldValue = node.value || ''; + node.value = oldValue + _unescaped; + node.quoteMark = null; + + if (_unescaped !== content || _oldRawValue) { + (0, _util.ensureObject)(node, 'raws'); + node.raws.value = (_oldRawValue || oldValue) + content; + } + + lastAdded = 'value'; + } else { + var insensitive = content === 'i' || content === "I"; + + if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) { + node.insensitive = insensitive; + + if (!insensitive || content === "I") { + (0, _util.ensureObject)(node, 'raws'); + node.raws.insensitiveFlag = content; + } + + lastAdded = 'insensitive'; + + if (spaceBefore) { + (0, _util.ensureObject)(node, 'spaces', 'insensitive'); + node.spaces.insensitive.before = spaceBefore; + spaceBefore = ''; + } + + if (commentBefore) { + (0, _util.ensureObject)(node, 'raws', 'spaces', 'insensitive'); + node.raws.spaces.insensitive.before = commentBefore; + commentBefore = ''; + } + } else if (node.value || node.value === '') { + lastAdded = 'value'; + node.value += content; + + if (node.raws.value) { + node.raws.value += content; + } + } + } + + spaceAfterMeaningfulToken = false; + break; + + case tokens.str: + if (!node.attribute || !node.operator) { + return this.error("Expected an attribute followed by an operator preceding the string.", { + index: token[_tokenize.FIELDS.START_POS] + }); + } + + var _unescapeValue = (0, _attribute.unescapeValue)(content), + unescaped = _unescapeValue.unescaped, + quoteMark = _unescapeValue.quoteMark; + + node.value = unescaped; + node.quoteMark = quoteMark; + lastAdded = 'value'; + (0, _util.ensureObject)(node, 'raws'); + node.raws.value = content; + spaceAfterMeaningfulToken = false; + break; + + case tokens.equals: + if (!node.attribute) { + return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content); + } + + if (node.value) { + return this.error('Unexpected "=" found; an operator was already defined.', { + index: token[_tokenize.FIELDS.START_POS] + }); + } + + node.operator = node.operator ? node.operator + content : content; + lastAdded = 'operator'; + spaceAfterMeaningfulToken = false; + break; + + case tokens.comment: + if (lastAdded) { + if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') { + var lastComment = (0, _util.getProp)(node, 'spaces', lastAdded, 'after') || ''; + var rawLastComment = (0, _util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment; + (0, _util.ensureObject)(node, 'raws', 'spaces', lastAdded); + node.raws.spaces[lastAdded].after = rawLastComment + content; + } else { + var lastValue = node[lastAdded] || ''; + var rawLastValue = (0, _util.getProp)(node, 'raws', lastAdded) || lastValue; + (0, _util.ensureObject)(node, 'raws'); + node.raws[lastAdded] = rawLastValue + content; + } + } else { + commentBefore = commentBefore + content; + } + + break; + + default: + return this.error("Unexpected \"" + content + "\" found.", { + index: token[_tokenize.FIELDS.START_POS] + }); + } + + pos++; + } + + unescapeProp(node, "attribute"); + unescapeProp(node, "namespace"); + this.newNode(new _attribute["default"](node)); + this.position++; + } + /** + * return a node containing meaningless garbage up to (but not including) the specified token position. + * if the token position is negative, all remaining tokens are consumed. + * + * This returns an array containing a single string node if all whitespace, + * otherwise an array of comment nodes with space before and after. + * + * These tokens are not added to the current selector, the caller can add them or use them to amend + * a previous node's space metadata. + * + * In lossy mode, this returns only comments. + */ + ; + + _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) { + if (stopPosition < 0) { + stopPosition = this.tokens.length; + } + + var startPosition = this.position; + var nodes = []; + var space = ""; + var lastComment = undefined; + + do { + if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) { + if (!this.options.lossy) { + space += this.content(); + } + } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) { + var spaces = {}; + + if (space) { + spaces.before = space; + space = ""; + } + + lastComment = new _comment["default"]({ + value: this.content(), + source: getTokenSource(this.currToken), + sourceIndex: this.currToken[_tokenize.FIELDS.START_POS], + spaces: spaces + }); + nodes.push(lastComment); + } + } while (++this.position < stopPosition); + + if (space) { + if (lastComment) { + lastComment.spaces.after = space; + } else if (!this.options.lossy) { + var firstToken = this.tokens[startPosition]; + var lastToken = this.tokens[this.position - 1]; + nodes.push(new _string["default"]({ + value: '', + source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]), + sourceIndex: firstToken[_tokenize.FIELDS.START_POS], + spaces: { + before: space, + after: '' + } + })); + } + } + + return nodes; + } + /** + * + * @param {*} nodes + */ + ; + + _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) { + var _this2 = this; + + if (requiredSpace === void 0) { + requiredSpace = false; + } + + var space = ""; + var rawSpace = ""; + nodes.forEach(function (n) { + var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace); + + var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace); + + space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0); + rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0); + }); + + if (rawSpace === space) { + rawSpace = undefined; + } + + var result = { + space: space, + rawSpace: rawSpace + }; + return result; + }; + + _proto.isNamedCombinator = function isNamedCombinator(position) { + if (position === void 0) { + position = this.position; + } + + return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash; + }; + + _proto.namedCombinator = function namedCombinator() { + if (this.isNamedCombinator()) { + var nameRaw = this.content(this.tokens[this.position + 1]); + var name = (0, _util.unesc)(nameRaw).toLowerCase(); + var raws = {}; + + if (name !== nameRaw) { + raws.value = "/" + nameRaw + "/"; + } + + var node = new _combinator["default"]({ + value: "/" + name + "/", + source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]), + sourceIndex: this.currToken[_tokenize.FIELDS.START_POS], + raws: raws + }); + this.position = this.position + 3; + return node; + } else { + this.unexpected(); + } + }; + + _proto.combinator = function combinator() { + var _this3 = this; + + if (this.content() === '|') { + return this.namespace(); + } // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector. + + + var nextSigTokenPos = this.locateNextMeaningfulToken(this.position); + + if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) { + var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos); + + if (nodes.length > 0) { + var last = this.current.last; + + if (last) { + var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes), + space = _this$convertWhitespa.space, + rawSpace = _this$convertWhitespa.rawSpace; + + if (rawSpace !== undefined) { + last.rawSpaceAfter += rawSpace; + } + + last.spaces.after += space; + } else { + nodes.forEach(function (n) { + return _this3.newNode(n); + }); + } + } + + return; + } + + var firstToken = this.currToken; + var spaceOrDescendantSelectorNodes = undefined; + + if (nextSigTokenPos > this.position) { + spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos); + } + + var node; + + if (this.isNamedCombinator()) { + node = this.namedCombinator(); + } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) { + node = new _combinator["default"]({ + value: this.content(), + source: getTokenSource(this.currToken), + sourceIndex: this.currToken[_tokenize.FIELDS.START_POS] + }); + this.position++; + } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {// pass + } else if (!spaceOrDescendantSelectorNodes) { + this.unexpected(); + } + + if (node) { + if (spaceOrDescendantSelectorNodes) { + var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes), + _space = _this$convertWhitespa2.space, + _rawSpace = _this$convertWhitespa2.rawSpace; + + node.spaces.before = _space; + node.rawSpaceBefore = _rawSpace; + } + } else { + // descendant combinator + var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true), + _space2 = _this$convertWhitespa3.space, + _rawSpace2 = _this$convertWhitespa3.rawSpace; + + if (!_rawSpace2) { + _rawSpace2 = _space2; + } + + var spaces = {}; + var raws = { + spaces: {} + }; + + if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) { + spaces.before = _space2.slice(0, _space2.length - 1); + raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1); + } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) { + spaces.after = _space2.slice(1); + raws.spaces.after = _rawSpace2.slice(1); + } else { + raws.value = _rawSpace2; + } + + node = new _combinator["default"]({ + value: ' ', + source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]), + sourceIndex: firstToken[_tokenize.FIELDS.START_POS], + spaces: spaces, + raws: raws + }); + } + + if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) { + node.spaces.after = this.optionalSpace(this.content()); + this.position++; + } + + return this.newNode(node); + }; + + _proto.comma = function comma() { + if (this.position === this.tokens.length - 1) { + this.root.trailingComma = true; + this.position++; + return; + } + + this.current._inferEndPosition(); + + var selector = new _selector["default"]({ + source: { + start: tokenStart(this.tokens[this.position + 1]) + } + }); + this.current.parent.append(selector); + this.current = selector; + this.position++; + }; + + _proto.comment = function comment() { + var current = this.currToken; + this.newNode(new _comment["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + })); + this.position++; + }; + + _proto.error = function error(message, opts) { + throw this.root.error(message, opts); + }; + + _proto.missingBackslash = function missingBackslash() { + return this.error('Expected a backslash preceding the semicolon.', { + index: this.currToken[_tokenize.FIELDS.START_POS] + }); + }; + + _proto.missingParenthesis = function missingParenthesis() { + return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]); + }; + + _proto.missingSquareBracket = function missingSquareBracket() { + return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]); + }; + + _proto.unexpected = function unexpected() { + return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]); + }; + + _proto.namespace = function namespace() { + var before = this.prevToken && this.content(this.prevToken) || true; + + if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) { + this.position++; + return this.word(before); + } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) { + this.position++; + return this.universal(before); + } + }; + + _proto.nesting = function nesting() { + if (this.nextToken) { + var nextContent = this.content(this.nextToken); + + if (nextContent === "|") { + this.position++; + return; + } + } + + var current = this.currToken; + this.newNode(new _nesting["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + })); + this.position++; + }; + + _proto.parentheses = function parentheses() { + var last = this.current.last; + var unbalanced = 1; + this.position++; + + if (last && last.type === types.PSEUDO) { + var selector = new _selector["default"]({ + source: { + start: tokenStart(this.tokens[this.position - 1]) + } + }); + var cache = this.current; + last.append(selector); + this.current = selector; + + while (this.position < this.tokens.length && unbalanced) { + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { + unbalanced++; + } + + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { + unbalanced--; + } + + if (unbalanced) { + this.parse(); + } else { + this.current.source.end = tokenEnd(this.currToken); + this.current.parent.source.end = tokenEnd(this.currToken); + this.position++; + } + } + + this.current = cache; + } else { + // I think this case should be an error. It's used to implement a basic parse of media queries + // but I don't think it's a good idea. + var parenStart = this.currToken; + var parenValue = "("; + var parenEnd; + + while (this.position < this.tokens.length && unbalanced) { + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { + unbalanced++; + } + + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { + unbalanced--; + } + + parenEnd = this.currToken; + parenValue += this.parseParenthesisToken(this.currToken); + this.position++; + } + + if (last) { + last.appendToPropertyAndEscape("value", parenValue, parenValue); + } else { + this.newNode(new _string["default"]({ + value: parenValue, + source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]), + sourceIndex: parenStart[_tokenize.FIELDS.START_POS] + })); + } + } + + if (unbalanced) { + return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]); + } + }; + + _proto.pseudo = function pseudo() { + var _this4 = this; + + var pseudoStr = ''; + var startingToken = this.currToken; + + while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) { + pseudoStr += this.content(); + this.position++; + } + + if (!this.currToken) { + return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1); + } + + if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) { + this.splitWord(false, function (first, length) { + pseudoStr += first; + + _this4.newNode(new _pseudo["default"]({ + value: pseudoStr, + source: getTokenSourceSpan(startingToken, _this4.currToken), + sourceIndex: startingToken[_tokenize.FIELDS.START_POS] + })); + + if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { + _this4.error('Misplaced parenthesis.', { + index: _this4.nextToken[_tokenize.FIELDS.START_POS] + }); + } + }); + } else { + return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]); + } + }; + + _proto.space = function space() { + var content = this.content(); // Handle space before and after the selector + + if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) { + return node.type === 'comment'; + })) { + this.spaces = this.optionalSpace(content); + this.position++; + } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { + this.current.last.spaces.after = this.optionalSpace(content); + this.position++; + } else { + this.combinator(); + } + }; + + _proto.string = function string() { + var current = this.currToken; + this.newNode(new _string["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + })); + this.position++; + }; + + _proto.universal = function universal(namespace) { + var nextToken = this.nextToken; + + if (nextToken && this.content(nextToken) === '|') { + this.position++; + return this.namespace(); + } + + var current = this.currToken; + this.newNode(new _universal["default"]({ + value: this.content(), + source: getTokenSource(current), + sourceIndex: current[_tokenize.FIELDS.START_POS] + }), namespace); + this.position++; + }; + + _proto.splitWord = function splitWord(namespace, firstCallback) { + var _this5 = this; + + var nextToken = this.nextToken; + var word = this.content(); + + while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) { + this.position++; + var current = this.content(); + word += current; + + if (current.lastIndexOf('\\') === current.length - 1) { + var next = this.nextToken; + + if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) { + word += this.requiredSpace(this.content(next)); + this.position++; + } + } + + nextToken = this.nextToken; + } + + var hasClass = indexesOf(word, '.').filter(function (i) { + // Allow escaped dot within class name + var escapedDot = word[i - 1] === '\\'; // Allow decimal numbers percent in @keyframes + + var isKeyframesPercent = /^\d+\.\d+%$/.test(word); + return !escapedDot && !isKeyframesPercent; + }); + var hasId = indexesOf(word, '#').filter(function (i) { + return word[i - 1] !== '\\'; + }); // Eliminate Sass interpolations from the list of id indexes + + var interpolations = indexesOf(word, '#{'); + + if (interpolations.length) { + hasId = hasId.filter(function (hashIndex) { + return !~interpolations.indexOf(hashIndex); + }); + } + + var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId))); + indices.forEach(function (ind, i) { + var index = indices[i + 1] || word.length; + var value = word.slice(ind, index); + + if (i === 0 && firstCallback) { + return firstCallback.call(_this5, value, indices.length); + } + + var node; + var current = _this5.currToken; + var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i]; + var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1)); + + if (~hasClass.indexOf(ind)) { + var classNameOpts = { + value: value.slice(1), + source: source, + sourceIndex: sourceIndex + }; + node = new _className["default"](unescapeProp(classNameOpts, "value")); + } else if (~hasId.indexOf(ind)) { + var idOpts = { + value: value.slice(1), + source: source, + sourceIndex: sourceIndex + }; + node = new _id["default"](unescapeProp(idOpts, "value")); + } else { + var tagOpts = { + value: value, + source: source, + sourceIndex: sourceIndex + }; + unescapeProp(tagOpts, "value"); + node = new _tag["default"](tagOpts); + } + + _this5.newNode(node, namespace); // Ensure that the namespace is used only once + + + namespace = null; + }); + this.position++; + }; + + _proto.word = function word(namespace) { + var nextToken = this.nextToken; + + if (nextToken && this.content(nextToken) === '|') { + this.position++; + return this.namespace(); + } + + return this.splitWord(namespace); + }; + + _proto.loop = function loop() { + while (this.position < this.tokens.length) { + this.parse(true); + } + + this.current._inferEndPosition(); + + return this.root; + }; + + _proto.parse = function parse(throwOnParenthesis) { + switch (this.currToken[_tokenize.FIELDS.TYPE]) { + case tokens.space: + this.space(); + break; + + case tokens.comment: + this.comment(); + break; + + case tokens.openParenthesis: + this.parentheses(); + break; + + case tokens.closeParenthesis: + if (throwOnParenthesis) { + this.missingParenthesis(); + } + + break; + + case tokens.openSquare: + this.attribute(); + break; + + case tokens.dollar: + case tokens.caret: + case tokens.equals: + case tokens.word: + this.word(); + break; + + case tokens.colon: + this.pseudo(); + break; + + case tokens.comma: + this.comma(); + break; + + case tokens.asterisk: + this.universal(); + break; + + case tokens.ampersand: + this.nesting(); + break; + + case tokens.slash: + case tokens.combinator: + this.combinator(); + break; + + case tokens.str: + this.string(); + break; + // These cases throw; no break needed. + + case tokens.closeSquare: + this.missingSquareBracket(); + + case tokens.semicolon: + this.missingBackslash(); + + default: + this.unexpected(); + } + } + /** + * Helpers + */ + ; + + _proto.expected = function expected(description, index, found) { + if (Array.isArray(description)) { + var last = description.pop(); + description = description.join(', ') + " or " + last; + } + + var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a'; + + if (!found) { + return this.error("Expected " + an + " " + description + ".", { + index: index + }); + } + + return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", { + index: index + }); + }; + + _proto.requiredSpace = function requiredSpace(space) { + return this.options.lossy ? ' ' : space; + }; + + _proto.optionalSpace = function optionalSpace(space) { + return this.options.lossy ? '' : space; + }; + + _proto.lossySpace = function lossySpace(space, required) { + if (this.options.lossy) { + return required ? ' ' : ''; + } else { + return space; + } + }; + + _proto.parseParenthesisToken = function parseParenthesisToken(token) { + var content = this.content(token); + + if (token[_tokenize.FIELDS.TYPE] === tokens.space) { + return this.requiredSpace(content); + } else { + return content; + } + }; + + _proto.newNode = function newNode(node, namespace) { + if (namespace) { + if (/^ +$/.test(namespace)) { + if (!this.options.lossy) { + this.spaces = (this.spaces || '') + namespace; + } + + namespace = true; + } + + node.namespace = namespace; + unescapeProp(node, "namespace"); + } + + if (this.spaces) { + node.spaces.before = this.spaces; + this.spaces = ''; + } + + return this.current.append(node); + }; + + _proto.content = function content(token) { + if (token === void 0) { + token = this.currToken; + } + + return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]); + }; + + /** + * returns the index of the next non-whitespace, non-comment token. + * returns -1 if no meaningful token is found. + */ + _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) { + if (startPosition === void 0) { + startPosition = this.position + 1; + } + + var searchPosition = startPosition; + + while (searchPosition < this.tokens.length) { + if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) { + searchPosition++; + continue; + } else { + return searchPosition; + } + } + + return -1; + }; + + _createClass(Parser, [{ + key: "currToken", + get: function get() { + return this.tokens[this.position]; + } + }, { + key: "nextToken", + get: function get() { + return this.tokens[this.position + 1]; + } + }, { + key: "prevToken", + get: function get() { + return this.tokens[this.position - 1]; + } + }]); + + return Parser; +}(); + +exports["default"] = Parser; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/processor.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/processor.js new file mode 100644 index 0000000..a00170c --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/processor.js @@ -0,0 +1,206 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _parser = _interopRequireDefault(require("./parser")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +var Processor = /*#__PURE__*/function () { + function Processor(func, options) { + this.func = func || function noop() {}; + + this.funcRes = null; + this.options = options; + } + + var _proto = Processor.prototype; + + _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) { + if (options === void 0) { + options = {}; + } + + var merged = Object.assign({}, this.options, options); + + if (merged.updateSelector === false) { + return false; + } else { + return typeof rule !== "string"; + } + }; + + _proto._isLossy = function _isLossy(options) { + if (options === void 0) { + options = {}; + } + + var merged = Object.assign({}, this.options, options); + + if (merged.lossless === false) { + return true; + } else { + return false; + } + }; + + _proto._root = function _root(rule, options) { + if (options === void 0) { + options = {}; + } + + var parser = new _parser["default"](rule, this._parseOptions(options)); + return parser.root; + }; + + _proto._parseOptions = function _parseOptions(options) { + return { + lossy: this._isLossy(options) + }; + }; + + _proto._run = function _run(rule, options) { + var _this = this; + + if (options === void 0) { + options = {}; + } + + return new Promise(function (resolve, reject) { + try { + var root = _this._root(rule, options); + + Promise.resolve(_this.func(root)).then(function (transform) { + var string = undefined; + + if (_this._shouldUpdateSelector(rule, options)) { + string = root.toString(); + rule.selector = string; + } + + return { + transform: transform, + root: root, + string: string + }; + }).then(resolve, reject); + } catch (e) { + reject(e); + return; + } + }); + }; + + _proto._runSync = function _runSync(rule, options) { + if (options === void 0) { + options = {}; + } + + var root = this._root(rule, options); + + var transform = this.func(root); + + if (transform && typeof transform.then === "function") { + throw new Error("Selector processor returned a promise to a synchronous call."); + } + + var string = undefined; + + if (options.updateSelector && typeof rule !== "string") { + string = root.toString(); + rule.selector = string; + } + + return { + transform: transform, + root: root, + string: string + }; + } + /** + * Process rule into a selector AST. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {Promise} The AST of the selector after processing it. + */ + ; + + _proto.ast = function ast(rule, options) { + return this._run(rule, options).then(function (result) { + return result.root; + }); + } + /** + * Process rule into a selector AST synchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {parser.Root} The AST of the selector after processing it. + */ + ; + + _proto.astSync = function astSync(rule, options) { + return this._runSync(rule, options).root; + } + /** + * Process a selector into a transformed value asynchronously + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {Promise} The value returned by the processor. + */ + ; + + _proto.transform = function transform(rule, options) { + return this._run(rule, options).then(function (result) { + return result.transform; + }); + } + /** + * Process a selector into a transformed value synchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {any} The value returned by the processor. + */ + ; + + _proto.transformSync = function transformSync(rule, options) { + return this._runSync(rule, options).transform; + } + /** + * Process a selector into a new selector string asynchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {string} the selector after processing. + */ + ; + + _proto.process = function process(rule, options) { + return this._run(rule, options).then(function (result) { + return result.string || result.root.toString(); + }); + } + /** + * Process a selector into a new selector string synchronously. + * + * @param rule {postcss.Rule | string} The css selector to be processed + * @param options The options for processing + * @returns {string} the selector after processing. + */ + ; + + _proto.processSync = function processSync(rule, options) { + var result = this._runSync(rule, options); + + return result.string || result.root.toString(); + }; + + return Processor; +}(); + +exports["default"] = Processor; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/attribute.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/attribute.js new file mode 100644 index 0000000..9edc30b --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/attribute.js @@ -0,0 +1,540 @@ +"use strict"; + +exports.__esModule = true; +exports.unescapeValue = unescapeValue; +exports["default"] = void 0; + +var _cssesc = _interopRequireDefault(require("cssesc")); + +var _unesc = _interopRequireDefault(require("../util/unesc")); + +var _namespace = _interopRequireDefault(require("./namespace")); + +var _types = require("./types"); + +var _CSSESC_QUOTE_OPTIONS; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var deprecate = require("util-deprecate"); + +var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/; +var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead."); +var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead."); +var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now."); + +function unescapeValue(value) { + var deprecatedUsage = false; + var quoteMark = null; + var unescaped = value; + var m = unescaped.match(WRAPPED_IN_QUOTES); + + if (m) { + quoteMark = m[1]; + unescaped = m[2]; + } + + unescaped = (0, _unesc["default"])(unescaped); + + if (unescaped !== value) { + deprecatedUsage = true; + } + + return { + deprecatedUsage: deprecatedUsage, + unescaped: unescaped, + quoteMark: quoteMark + }; +} + +function handleDeprecatedContructorOpts(opts) { + if (opts.quoteMark !== undefined) { + return opts; + } + + if (opts.value === undefined) { + return opts; + } + + warnOfDeprecatedConstructor(); + + var _unescapeValue = unescapeValue(opts.value), + quoteMark = _unescapeValue.quoteMark, + unescaped = _unescapeValue.unescaped; + + if (!opts.raws) { + opts.raws = {}; + } + + if (opts.raws.value === undefined) { + opts.raws.value = opts.value; + } + + opts.value = unescaped; + opts.quoteMark = quoteMark; + return opts; +} + +var Attribute = /*#__PURE__*/function (_Namespace) { + _inheritsLoose(Attribute, _Namespace); + + function Attribute(opts) { + var _this; + + if (opts === void 0) { + opts = {}; + } + + _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this; + _this.type = _types.ATTRIBUTE; + _this.raws = _this.raws || {}; + Object.defineProperty(_this.raws, 'unquoted', { + get: deprecate(function () { + return _this.value; + }, "attr.raws.unquoted is deprecated. Call attr.value instead."), + set: deprecate(function () { + return _this.value; + }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.") + }); + _this._constructed = true; + return _this; + } + /** + * Returns the Attribute's value quoted such that it would be legal to use + * in the value of a css file. The original value's quotation setting + * used for stringification is left unchanged. See `setValue(value, options)` + * if you want to control the quote settings of a new value for the attribute. + * + * You can also change the quotation used for the current value by setting quoteMark. + * + * Options: + * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this + * option is not set, the original value for quoteMark will be used. If + * indeterminate, a double quote is used. The legal values are: + * * `null` - the value will be unquoted and characters will be escaped as necessary. + * * `'` - the value will be quoted with a single quote and single quotes are escaped. + * * `"` - the value will be quoted with a double quote and double quotes are escaped. + * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark + * over the quoteMark option value. + * * smart {boolean} - if true, will select a quote mark based on the value + * and the other options specified here. See the `smartQuoteMark()` + * method. + **/ + + + var _proto = Attribute.prototype; + + _proto.getQuotedValue = function getQuotedValue(options) { + if (options === void 0) { + options = {}; + } + + var quoteMark = this._determineQuoteMark(options); + + var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark]; + var escaped = (0, _cssesc["default"])(this._value, cssescopts); + return escaped; + }; + + _proto._determineQuoteMark = function _determineQuoteMark(options) { + return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options); + } + /** + * Set the unescaped value with the specified quotation options. The value + * provided must not include any wrapping quote marks -- those quotes will + * be interpreted as part of the value and escaped accordingly. + */ + ; + + _proto.setValue = function setValue(value, options) { + if (options === void 0) { + options = {}; + } + + this._value = value; + this._quoteMark = this._determineQuoteMark(options); + + this._syncRawValue(); + } + /** + * Intelligently select a quoteMark value based on the value's contents. If + * the value is a legal CSS ident, it will not be quoted. Otherwise a quote + * mark will be picked that minimizes the number of escapes. + * + * If there's no clear winner, the quote mark from these options is used, + * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is + * true). If the quoteMark is unspecified, a double quote is used. + * + * @param options This takes the quoteMark and preferCurrentQuoteMark options + * from the quoteValue method. + */ + ; + + _proto.smartQuoteMark = function smartQuoteMark(options) { + var v = this.value; + var numSingleQuotes = v.replace(/[^']/g, '').length; + var numDoubleQuotes = v.replace(/[^"]/g, '').length; + + if (numSingleQuotes + numDoubleQuotes === 0) { + var escaped = (0, _cssesc["default"])(v, { + isIdentifier: true + }); + + if (escaped === v) { + return Attribute.NO_QUOTE; + } else { + var pref = this.preferredQuoteMark(options); + + if (pref === Attribute.NO_QUOTE) { + // pick a quote mark that isn't none and see if it's smaller + var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE; + var opts = CSSESC_QUOTE_OPTIONS[quote]; + var quoteValue = (0, _cssesc["default"])(v, opts); + + if (quoteValue.length < escaped.length) { + return quote; + } + } + + return pref; + } + } else if (numDoubleQuotes === numSingleQuotes) { + return this.preferredQuoteMark(options); + } else if (numDoubleQuotes < numSingleQuotes) { + return Attribute.DOUBLE_QUOTE; + } else { + return Attribute.SINGLE_QUOTE; + } + } + /** + * Selects the preferred quote mark based on the options and the current quote mark value. + * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)` + * instead. + */ + ; + + _proto.preferredQuoteMark = function preferredQuoteMark(options) { + var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark; + + if (quoteMark === undefined) { + quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark; + } + + if (quoteMark === undefined) { + quoteMark = Attribute.DOUBLE_QUOTE; + } + + return quoteMark; + }; + + _proto._syncRawValue = function _syncRawValue() { + var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]); + + if (rawValue === this._value) { + if (this.raws) { + delete this.raws.value; + } + } else { + this.raws.value = rawValue; + } + }; + + _proto._handleEscapes = function _handleEscapes(prop, value) { + if (this._constructed) { + var escaped = (0, _cssesc["default"])(value, { + isIdentifier: true + }); + + if (escaped !== value) { + this.raws[prop] = escaped; + } else { + delete this.raws[prop]; + } + } + }; + + _proto._spacesFor = function _spacesFor(name) { + var attrSpaces = { + before: '', + after: '' + }; + var spaces = this.spaces[name] || {}; + var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {}; + return Object.assign(attrSpaces, spaces, rawSpaces); + }; + + _proto._stringFor = function _stringFor(name, spaceName, concat) { + if (spaceName === void 0) { + spaceName = name; + } + + if (concat === void 0) { + concat = defaultAttrConcat; + } + + var attrSpaces = this._spacesFor(spaceName); + + return concat(this.stringifyProperty(name), attrSpaces); + } + /** + * returns the offset of the attribute part specified relative to the + * start of the node of the output string. + * + * * "ns" - alias for "namespace" + * * "namespace" - the namespace if it exists. + * * "attribute" - the attribute name + * * "attributeNS" - the start of the attribute or its namespace + * * "operator" - the match operator of the attribute + * * "value" - The value (string or identifier) + * * "insensitive" - the case insensitivity flag; + * @param part One of the possible values inside an attribute. + * @returns -1 if the name is invalid or the value doesn't exist in this attribute. + */ + ; + + _proto.offsetOf = function offsetOf(name) { + var count = 1; + + var attributeSpaces = this._spacesFor("attribute"); + + count += attributeSpaces.before.length; + + if (name === "namespace" || name === "ns") { + return this.namespace ? count : -1; + } + + if (name === "attributeNS") { + return count; + } + + count += this.namespaceString.length; + + if (this.namespace) { + count += 1; + } + + if (name === "attribute") { + return count; + } + + count += this.stringifyProperty("attribute").length; + count += attributeSpaces.after.length; + + var operatorSpaces = this._spacesFor("operator"); + + count += operatorSpaces.before.length; + var operator = this.stringifyProperty("operator"); + + if (name === "operator") { + return operator ? count : -1; + } + + count += operator.length; + count += operatorSpaces.after.length; + + var valueSpaces = this._spacesFor("value"); + + count += valueSpaces.before.length; + var value = this.stringifyProperty("value"); + + if (name === "value") { + return value ? count : -1; + } + + count += value.length; + count += valueSpaces.after.length; + + var insensitiveSpaces = this._spacesFor("insensitive"); + + count += insensitiveSpaces.before.length; + + if (name === "insensitive") { + return this.insensitive ? count : -1; + } + + return -1; + }; + + _proto.toString = function toString() { + var _this2 = this; + + var selector = [this.rawSpaceBefore, '[']; + selector.push(this._stringFor('qualifiedAttribute', 'attribute')); + + if (this.operator && (this.value || this.value === '')) { + selector.push(this._stringFor('operator')); + selector.push(this._stringFor('value')); + selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) { + if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) { + attrSpaces.before = " "; + } + + return defaultAttrConcat(attrValue, attrSpaces); + })); + } + + selector.push(']'); + selector.push(this.rawSpaceAfter); + return selector.join(''); + }; + + _createClass(Attribute, [{ + key: "quoted", + get: function get() { + var qm = this.quoteMark; + return qm === "'" || qm === '"'; + }, + set: function set(value) { + warnOfDeprecatedQuotedAssignment(); + } + /** + * returns a single (`'`) or double (`"`) quote character if the value is quoted. + * returns `null` if the value is not quoted. + * returns `undefined` if the quotation state is unknown (this can happen when + * the attribute is constructed without specifying a quote mark.) + */ + + }, { + key: "quoteMark", + get: function get() { + return this._quoteMark; + } + /** + * Set the quote mark to be used by this attribute's value. + * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute + * value is updated accordingly. + * + * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted. + */ + , + set: function set(quoteMark) { + if (!this._constructed) { + this._quoteMark = quoteMark; + return; + } + + if (this._quoteMark !== quoteMark) { + this._quoteMark = quoteMark; + + this._syncRawValue(); + } + } + }, { + key: "qualifiedAttribute", + get: function get() { + return this.qualifiedName(this.raws.attribute || this.attribute); + } + }, { + key: "insensitiveFlag", + get: function get() { + return this.insensitive ? 'i' : ''; + } + }, { + key: "value", + get: function get() { + return this._value; + }, + set: + /** + * Before 3.0, the value had to be set to an escaped value including any wrapped + * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value + * is unescaped during parsing and any quote marks are removed. + * + * Because the ambiguity of this semantic change, if you set `attr.value = newValue`, + * a deprecation warning is raised when the new value contains any characters that would + * require escaping (including if it contains wrapped quotes). + * + * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe + * how the new value is quoted. + */ + function set(v) { + if (this._constructed) { + var _unescapeValue2 = unescapeValue(v), + deprecatedUsage = _unescapeValue2.deprecatedUsage, + unescaped = _unescapeValue2.unescaped, + quoteMark = _unescapeValue2.quoteMark; + + if (deprecatedUsage) { + warnOfDeprecatedValueAssignment(); + } + + if (unescaped === this._value && quoteMark === this._quoteMark) { + return; + } + + this._value = unescaped; + this._quoteMark = quoteMark; + + this._syncRawValue(); + } else { + this._value = v; + } + } + }, { + key: "insensitive", + get: function get() { + return this._insensitive; + } + /** + * Set the case insensitive flag. + * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag` + * of the attribute is updated accordingly. + * + * @param {true | false} insensitive true if the attribute should match case-insensitively. + */ + , + set: function set(insensitive) { + if (!insensitive) { + this._insensitive = false; // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation. + // When setting `attr.insensitive = false` both should be erased to ensure correct serialization. + + if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) { + this.raws.insensitiveFlag = undefined; + } + } + + this._insensitive = insensitive; + } + }, { + key: "attribute", + get: function get() { + return this._attribute; + }, + set: function set(name) { + this._handleEscapes("attribute", name); + + this._attribute = name; + } + }]); + + return Attribute; +}(_namespace["default"]); + +exports["default"] = Attribute; +Attribute.NO_QUOTE = null; +Attribute.SINGLE_QUOTE = "'"; +Attribute.DOUBLE_QUOTE = '"'; +var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = { + "'": { + quotes: 'single', + wrap: true + }, + '"': { + quotes: 'double', + wrap: true + } +}, _CSSESC_QUOTE_OPTIONS[null] = { + isIdentifier: true +}, _CSSESC_QUOTE_OPTIONS); + +function defaultAttrConcat(attrValue, attrSpaces) { + return "" + attrSpaces.before + attrValue + attrSpaces.after; +} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/className.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/className.js new file mode 100644 index 0000000..2240991 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/className.js @@ -0,0 +1,69 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _cssesc = _interopRequireDefault(require("cssesc")); + +var _util = require("../util"); + +var _node = _interopRequireDefault(require("./node")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ClassName = /*#__PURE__*/function (_Node) { + _inheritsLoose(ClassName, _Node); + + function ClassName(opts) { + var _this; + + _this = _Node.call(this, opts) || this; + _this.type = _types.CLASS; + _this._constructed = true; + return _this; + } + + var _proto = ClassName.prototype; + + _proto.valueToString = function valueToString() { + return '.' + _Node.prototype.valueToString.call(this); + }; + + _createClass(ClassName, [{ + key: "value", + get: function get() { + return this._value; + }, + set: function set(v) { + if (this._constructed) { + var escaped = (0, _cssesc["default"])(v, { + isIdentifier: true + }); + + if (escaped !== v) { + (0, _util.ensureObject)(this, "raws"); + this.raws.value = escaped; + } else if (this.raws) { + delete this.raws.value; + } + } + + this._value = v; + } + }]); + + return ClassName; +}(_node["default"]); + +exports["default"] = ClassName; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/combinator.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/combinator.js new file mode 100644 index 0000000..271ab4d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/combinator.js @@ -0,0 +1,31 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _node = _interopRequireDefault(require("./node")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Combinator = /*#__PURE__*/function (_Node) { + _inheritsLoose(Combinator, _Node); + + function Combinator(opts) { + var _this; + + _this = _Node.call(this, opts) || this; + _this.type = _types.COMBINATOR; + return _this; + } + + return Combinator; +}(_node["default"]); + +exports["default"] = Combinator; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/comment.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/comment.js new file mode 100644 index 0000000..e778094 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/comment.js @@ -0,0 +1,31 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _node = _interopRequireDefault(require("./node")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Comment = /*#__PURE__*/function (_Node) { + _inheritsLoose(Comment, _Node); + + function Comment(opts) { + var _this; + + _this = _Node.call(this, opts) || this; + _this.type = _types.COMMENT; + return _this; + } + + return Comment; +}(_node["default"]); + +exports["default"] = Comment; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/constructors.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/constructors.js new file mode 100644 index 0000000..078023e --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/constructors.js @@ -0,0 +1,102 @@ +"use strict"; + +exports.__esModule = true; +exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0; + +var _attribute = _interopRequireDefault(require("./attribute")); + +var _className = _interopRequireDefault(require("./className")); + +var _combinator = _interopRequireDefault(require("./combinator")); + +var _comment = _interopRequireDefault(require("./comment")); + +var _id = _interopRequireDefault(require("./id")); + +var _nesting = _interopRequireDefault(require("./nesting")); + +var _pseudo = _interopRequireDefault(require("./pseudo")); + +var _root = _interopRequireDefault(require("./root")); + +var _selector = _interopRequireDefault(require("./selector")); + +var _string = _interopRequireDefault(require("./string")); + +var _tag = _interopRequireDefault(require("./tag")); + +var _universal = _interopRequireDefault(require("./universal")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +var attribute = function attribute(opts) { + return new _attribute["default"](opts); +}; + +exports.attribute = attribute; + +var className = function className(opts) { + return new _className["default"](opts); +}; + +exports.className = className; + +var combinator = function combinator(opts) { + return new _combinator["default"](opts); +}; + +exports.combinator = combinator; + +var comment = function comment(opts) { + return new _comment["default"](opts); +}; + +exports.comment = comment; + +var id = function id(opts) { + return new _id["default"](opts); +}; + +exports.id = id; + +var nesting = function nesting(opts) { + return new _nesting["default"](opts); +}; + +exports.nesting = nesting; + +var pseudo = function pseudo(opts) { + return new _pseudo["default"](opts); +}; + +exports.pseudo = pseudo; + +var root = function root(opts) { + return new _root["default"](opts); +}; + +exports.root = root; + +var selector = function selector(opts) { + return new _selector["default"](opts); +}; + +exports.selector = selector; + +var string = function string(opts) { + return new _string["default"](opts); +}; + +exports.string = string; + +var tag = function tag(opts) { + return new _tag["default"](opts); +}; + +exports.tag = tag; + +var universal = function universal(opts) { + return new _universal["default"](opts); +}; + +exports.universal = universal; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/container.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/container.js new file mode 100644 index 0000000..2626fb8 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/container.js @@ -0,0 +1,395 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _node = _interopRequireDefault(require("./node")); + +var types = _interopRequireWildcard(require("./types")); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Container = /*#__PURE__*/function (_Node) { + _inheritsLoose(Container, _Node); + + function Container(opts) { + var _this; + + _this = _Node.call(this, opts) || this; + + if (!_this.nodes) { + _this.nodes = []; + } + + return _this; + } + + var _proto = Container.prototype; + + _proto.append = function append(selector) { + selector.parent = this; + this.nodes.push(selector); + return this; + }; + + _proto.prepend = function prepend(selector) { + selector.parent = this; + this.nodes.unshift(selector); + return this; + }; + + _proto.at = function at(index) { + return this.nodes[index]; + }; + + _proto.index = function index(child) { + if (typeof child === 'number') { + return child; + } + + return this.nodes.indexOf(child); + }; + + _proto.removeChild = function removeChild(child) { + child = this.index(child); + this.at(child).parent = undefined; + this.nodes.splice(child, 1); + var index; + + for (var id in this.indexes) { + index = this.indexes[id]; + + if (index >= child) { + this.indexes[id] = index - 1; + } + } + + return this; + }; + + _proto.removeAll = function removeAll() { + for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done;) { + var node = _step.value; + node.parent = undefined; + } + + this.nodes = []; + return this; + }; + + _proto.empty = function empty() { + return this.removeAll(); + }; + + _proto.insertAfter = function insertAfter(oldNode, newNode) { + newNode.parent = this; + var oldIndex = this.index(oldNode); + this.nodes.splice(oldIndex + 1, 0, newNode); + newNode.parent = this; + var index; + + for (var id in this.indexes) { + index = this.indexes[id]; + + if (oldIndex <= index) { + this.indexes[id] = index + 1; + } + } + + return this; + }; + + _proto.insertBefore = function insertBefore(oldNode, newNode) { + newNode.parent = this; + var oldIndex = this.index(oldNode); + this.nodes.splice(oldIndex, 0, newNode); + newNode.parent = this; + var index; + + for (var id in this.indexes) { + index = this.indexes[id]; + + if (index <= oldIndex) { + this.indexes[id] = index + 1; + } + } + + return this; + }; + + _proto._findChildAtPosition = function _findChildAtPosition(line, col) { + var found = undefined; + this.each(function (node) { + if (node.atPosition) { + var foundChild = node.atPosition(line, col); + + if (foundChild) { + found = foundChild; + return false; + } + } else if (node.isAtPosition(line, col)) { + found = node; + return false; + } + }); + return found; + } + /** + * Return the most specific node at the line and column number given. + * The source location is based on the original parsed location, locations aren't + * updated as selector nodes are mutated. + * + * Note that this location is relative to the location of the first character + * of the selector, and not the location of the selector in the overall document + * when used in conjunction with postcss. + * + * If not found, returns undefined. + * @param {number} line The line number of the node to find. (1-based index) + * @param {number} col The column number of the node to find. (1-based index) + */ + ; + + _proto.atPosition = function atPosition(line, col) { + if (this.isAtPosition(line, col)) { + return this._findChildAtPosition(line, col) || this; + } else { + return undefined; + } + }; + + _proto._inferEndPosition = function _inferEndPosition() { + if (this.last && this.last.source && this.last.source.end) { + this.source = this.source || {}; + this.source.end = this.source.end || {}; + Object.assign(this.source.end, this.last.source.end); + } + }; + + _proto.each = function each(callback) { + if (!this.lastEach) { + this.lastEach = 0; + } + + if (!this.indexes) { + this.indexes = {}; + } + + this.lastEach++; + var id = this.lastEach; + this.indexes[id] = 0; + + if (!this.length) { + return undefined; + } + + var index, result; + + while (this.indexes[id] < this.length) { + index = this.indexes[id]; + result = callback(this.at(index), index); + + if (result === false) { + break; + } + + this.indexes[id] += 1; + } + + delete this.indexes[id]; + + if (result === false) { + return false; + } + }; + + _proto.walk = function walk(callback) { + return this.each(function (node, i) { + var result = callback(node, i); + + if (result !== false && node.length) { + result = node.walk(callback); + } + + if (result === false) { + return false; + } + }); + }; + + _proto.walkAttributes = function walkAttributes(callback) { + var _this2 = this; + + return this.walk(function (selector) { + if (selector.type === types.ATTRIBUTE) { + return callback.call(_this2, selector); + } + }); + }; + + _proto.walkClasses = function walkClasses(callback) { + var _this3 = this; + + return this.walk(function (selector) { + if (selector.type === types.CLASS) { + return callback.call(_this3, selector); + } + }); + }; + + _proto.walkCombinators = function walkCombinators(callback) { + var _this4 = this; + + return this.walk(function (selector) { + if (selector.type === types.COMBINATOR) { + return callback.call(_this4, selector); + } + }); + }; + + _proto.walkComments = function walkComments(callback) { + var _this5 = this; + + return this.walk(function (selector) { + if (selector.type === types.COMMENT) { + return callback.call(_this5, selector); + } + }); + }; + + _proto.walkIds = function walkIds(callback) { + var _this6 = this; + + return this.walk(function (selector) { + if (selector.type === types.ID) { + return callback.call(_this6, selector); + } + }); + }; + + _proto.walkNesting = function walkNesting(callback) { + var _this7 = this; + + return this.walk(function (selector) { + if (selector.type === types.NESTING) { + return callback.call(_this7, selector); + } + }); + }; + + _proto.walkPseudos = function walkPseudos(callback) { + var _this8 = this; + + return this.walk(function (selector) { + if (selector.type === types.PSEUDO) { + return callback.call(_this8, selector); + } + }); + }; + + _proto.walkTags = function walkTags(callback) { + var _this9 = this; + + return this.walk(function (selector) { + if (selector.type === types.TAG) { + return callback.call(_this9, selector); + } + }); + }; + + _proto.walkUniversals = function walkUniversals(callback) { + var _this10 = this; + + return this.walk(function (selector) { + if (selector.type === types.UNIVERSAL) { + return callback.call(_this10, selector); + } + }); + }; + + _proto.split = function split(callback) { + var _this11 = this; + + var current = []; + return this.reduce(function (memo, node, index) { + var split = callback.call(_this11, node); + current.push(node); + + if (split) { + memo.push(current); + current = []; + } else if (index === _this11.length - 1) { + memo.push(current); + } + + return memo; + }, []); + }; + + _proto.map = function map(callback) { + return this.nodes.map(callback); + }; + + _proto.reduce = function reduce(callback, memo) { + return this.nodes.reduce(callback, memo); + }; + + _proto.every = function every(callback) { + return this.nodes.every(callback); + }; + + _proto.some = function some(callback) { + return this.nodes.some(callback); + }; + + _proto.filter = function filter(callback) { + return this.nodes.filter(callback); + }; + + _proto.sort = function sort(callback) { + return this.nodes.sort(callback); + }; + + _proto.toString = function toString() { + return this.map(String).join(''); + }; + + _createClass(Container, [{ + key: "first", + get: function get() { + return this.at(0); + } + }, { + key: "last", + get: function get() { + return this.at(this.length - 1); + } + }, { + key: "length", + get: function get() { + return this.nodes.length; + } + }]); + + return Container; +}(_node["default"]); + +exports["default"] = Container; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/guards.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/guards.js new file mode 100644 index 0000000..c949af5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/guards.js @@ -0,0 +1,64 @@ +"use strict"; + +exports.__esModule = true; +exports.isNode = isNode; +exports.isPseudoElement = isPseudoElement; +exports.isPseudoClass = isPseudoClass; +exports.isContainer = isContainer; +exports.isNamespace = isNamespace; +exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = exports.isPseudo = exports.isNesting = exports.isIdentifier = exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0; + +var _types = require("./types"); + +var _IS_TYPE; + +var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE); + +function isNode(node) { + return typeof node === "object" && IS_TYPE[node.type]; +} + +function isNodeType(type, node) { + return isNode(node) && node.type === type; +} + +var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE); +exports.isAttribute = isAttribute; +var isClassName = isNodeType.bind(null, _types.CLASS); +exports.isClassName = isClassName; +var isCombinator = isNodeType.bind(null, _types.COMBINATOR); +exports.isCombinator = isCombinator; +var isComment = isNodeType.bind(null, _types.COMMENT); +exports.isComment = isComment; +var isIdentifier = isNodeType.bind(null, _types.ID); +exports.isIdentifier = isIdentifier; +var isNesting = isNodeType.bind(null, _types.NESTING); +exports.isNesting = isNesting; +var isPseudo = isNodeType.bind(null, _types.PSEUDO); +exports.isPseudo = isPseudo; +var isRoot = isNodeType.bind(null, _types.ROOT); +exports.isRoot = isRoot; +var isSelector = isNodeType.bind(null, _types.SELECTOR); +exports.isSelector = isSelector; +var isString = isNodeType.bind(null, _types.STRING); +exports.isString = isString; +var isTag = isNodeType.bind(null, _types.TAG); +exports.isTag = isTag; +var isUniversal = isNodeType.bind(null, _types.UNIVERSAL); +exports.isUniversal = isUniversal; + +function isPseudoElement(node) { + return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after" || node.value.toLowerCase() === ":first-letter" || node.value.toLowerCase() === ":first-line"); +} + +function isPseudoClass(node) { + return isPseudo(node) && !isPseudoElement(node); +} + +function isContainer(node) { + return !!(isNode(node) && node.walk); +} + +function isNamespace(node) { + return isAttribute(node) || isTag(node); +} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/id.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/id.js new file mode 100644 index 0000000..4e83147 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/id.js @@ -0,0 +1,37 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _node = _interopRequireDefault(require("./node")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var ID = /*#__PURE__*/function (_Node) { + _inheritsLoose(ID, _Node); + + function ID(opts) { + var _this; + + _this = _Node.call(this, opts) || this; + _this.type = _types.ID; + return _this; + } + + var _proto = ID.prototype; + + _proto.valueToString = function valueToString() { + return '#' + _Node.prototype.valueToString.call(this); + }; + + return ID; +}(_node["default"]); + +exports["default"] = ID; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/index.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/index.js new file mode 100644 index 0000000..1fe9b13 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/index.js @@ -0,0 +1,27 @@ +"use strict"; + +exports.__esModule = true; + +var _types = require("./types"); + +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _types[key]) return; + exports[key] = _types[key]; +}); + +var _constructors = require("./constructors"); + +Object.keys(_constructors).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _constructors[key]) return; + exports[key] = _constructors[key]; +}); + +var _guards = require("./guards"); + +Object.keys(_guards).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _guards[key]) return; + exports[key] = _guards[key]; +}); \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/namespace.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/namespace.js new file mode 100644 index 0000000..fd6c729 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/namespace.js @@ -0,0 +1,101 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _cssesc = _interopRequireDefault(require("cssesc")); + +var _util = require("../util"); + +var _node = _interopRequireDefault(require("./node")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Namespace = /*#__PURE__*/function (_Node) { + _inheritsLoose(Namespace, _Node); + + function Namespace() { + return _Node.apply(this, arguments) || this; + } + + var _proto = Namespace.prototype; + + _proto.qualifiedName = function qualifiedName(value) { + if (this.namespace) { + return this.namespaceString + "|" + value; + } else { + return value; + } + }; + + _proto.valueToString = function valueToString() { + return this.qualifiedName(_Node.prototype.valueToString.call(this)); + }; + + _createClass(Namespace, [{ + key: "namespace", + get: function get() { + return this._namespace; + }, + set: function set(namespace) { + if (namespace === true || namespace === "*" || namespace === "&") { + this._namespace = namespace; + + if (this.raws) { + delete this.raws.namespace; + } + + return; + } + + var escaped = (0, _cssesc["default"])(namespace, { + isIdentifier: true + }); + this._namespace = namespace; + + if (escaped !== namespace) { + (0, _util.ensureObject)(this, "raws"); + this.raws.namespace = escaped; + } else if (this.raws) { + delete this.raws.namespace; + } + } + }, { + key: "ns", + get: function get() { + return this._namespace; + }, + set: function set(namespace) { + this.namespace = namespace; + } + }, { + key: "namespaceString", + get: function get() { + if (this.namespace) { + var ns = this.stringifyProperty("namespace"); + + if (ns === true) { + return ''; + } else { + return ns; + } + } else { + return ''; + } + } + }]); + + return Namespace; +}(_node["default"]); + +exports["default"] = Namespace; +; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/nesting.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/nesting.js new file mode 100644 index 0000000..3288c78 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/nesting.js @@ -0,0 +1,32 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _node = _interopRequireDefault(require("./node")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Nesting = /*#__PURE__*/function (_Node) { + _inheritsLoose(Nesting, _Node); + + function Nesting(opts) { + var _this; + + _this = _Node.call(this, opts) || this; + _this.type = _types.NESTING; + _this.value = '&'; + return _this; + } + + return Nesting; +}(_node["default"]); + +exports["default"] = Nesting; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/node.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/node.js new file mode 100644 index 0000000..e8eca11 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/node.js @@ -0,0 +1,239 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _util = require("../util"); + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var cloneNode = function cloneNode(obj, parent) { + if (typeof obj !== 'object' || obj === null) { + return obj; + } + + var cloned = new obj.constructor(); + + for (var i in obj) { + if (!obj.hasOwnProperty(i)) { + continue; + } + + var value = obj[i]; + var type = typeof value; + + if (i === 'parent' && type === 'object') { + if (parent) { + cloned[i] = parent; + } + } else if (value instanceof Array) { + cloned[i] = value.map(function (j) { + return cloneNode(j, cloned); + }); + } else { + cloned[i] = cloneNode(value, cloned); + } + } + + return cloned; +}; + +var Node = /*#__PURE__*/function () { + function Node(opts) { + if (opts === void 0) { + opts = {}; + } + + Object.assign(this, opts); + this.spaces = this.spaces || {}; + this.spaces.before = this.spaces.before || ''; + this.spaces.after = this.spaces.after || ''; + } + + var _proto = Node.prototype; + + _proto.remove = function remove() { + if (this.parent) { + this.parent.removeChild(this); + } + + this.parent = undefined; + return this; + }; + + _proto.replaceWith = function replaceWith() { + if (this.parent) { + for (var index in arguments) { + this.parent.insertBefore(this, arguments[index]); + } + + this.remove(); + } + + return this; + }; + + _proto.next = function next() { + return this.parent.at(this.parent.index(this) + 1); + }; + + _proto.prev = function prev() { + return this.parent.at(this.parent.index(this) - 1); + }; + + _proto.clone = function clone(overrides) { + if (overrides === void 0) { + overrides = {}; + } + + var cloned = cloneNode(this); + + for (var name in overrides) { + cloned[name] = overrides[name]; + } + + return cloned; + } + /** + * Some non-standard syntax doesn't follow normal escaping rules for css. + * This allows non standard syntax to be appended to an existing property + * by specifying the escaped value. By specifying the escaped value, + * illegal characters are allowed to be directly inserted into css output. + * @param {string} name the property to set + * @param {any} value the unescaped value of the property + * @param {string} valueEscaped optional. the escaped value of the property. + */ + ; + + _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) { + if (!this.raws) { + this.raws = {}; + } + + var originalValue = this[name]; + var originalEscaped = this.raws[name]; + this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first. + + if (originalEscaped || valueEscaped !== value) { + this.raws[name] = (originalEscaped || originalValue) + valueEscaped; + } else { + delete this.raws[name]; // delete any escaped value that was created by the setter. + } + } + /** + * Some non-standard syntax doesn't follow normal escaping rules for css. + * This allows the escaped value to be specified directly, allowing illegal + * characters to be directly inserted into css output. + * @param {string} name the property to set + * @param {any} value the unescaped value of the property + * @param {string} valueEscaped the escaped value of the property. + */ + ; + + _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) { + if (!this.raws) { + this.raws = {}; + } + + this[name] = value; // this may trigger a setter that updates raws, so it has to be set first. + + this.raws[name] = valueEscaped; + } + /** + * When you want a value to passed through to CSS directly. This method + * deletes the corresponding raw value causing the stringifier to fallback + * to the unescaped value. + * @param {string} name the property to set. + * @param {any} value The value that is both escaped and unescaped. + */ + ; + + _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) { + this[name] = value; // this may trigger a setter that updates raws, so it has to be set first. + + if (this.raws) { + delete this.raws[name]; + } + } + /** + * + * @param {number} line The number (starting with 1) + * @param {number} column The column number (starting with 1) + */ + ; + + _proto.isAtPosition = function isAtPosition(line, column) { + if (this.source && this.source.start && this.source.end) { + if (this.source.start.line > line) { + return false; + } + + if (this.source.end.line < line) { + return false; + } + + if (this.source.start.line === line && this.source.start.column > column) { + return false; + } + + if (this.source.end.line === line && this.source.end.column < column) { + return false; + } + + return true; + } + + return undefined; + }; + + _proto.stringifyProperty = function stringifyProperty(name) { + return this.raws && this.raws[name] || this[name]; + }; + + _proto.valueToString = function valueToString() { + return String(this.stringifyProperty("value")); + }; + + _proto.toString = function toString() { + return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join(''); + }; + + _createClass(Node, [{ + key: "rawSpaceBefore", + get: function get() { + var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before; + + if (rawSpace === undefined) { + rawSpace = this.spaces && this.spaces.before; + } + + return rawSpace || ""; + }, + set: function set(raw) { + (0, _util.ensureObject)(this, "raws", "spaces"); + this.raws.spaces.before = raw; + } + }, { + key: "rawSpaceAfter", + get: function get() { + var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after; + + if (rawSpace === undefined) { + rawSpace = this.spaces.after; + } + + return rawSpace || ""; + }, + set: function set(raw) { + (0, _util.ensureObject)(this, "raws", "spaces"); + this.raws.spaces.after = raw; + } + }]); + + return Node; +}(); + +exports["default"] = Node; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/pseudo.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/pseudo.js new file mode 100644 index 0000000..a0e7bca --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/pseudo.js @@ -0,0 +1,38 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _container = _interopRequireDefault(require("./container")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Pseudo = /*#__PURE__*/function (_Container) { + _inheritsLoose(Pseudo, _Container); + + function Pseudo(opts) { + var _this; + + _this = _Container.call(this, opts) || this; + _this.type = _types.PSEUDO; + return _this; + } + + var _proto = Pseudo.prototype; + + _proto.toString = function toString() { + var params = this.length ? '(' + this.map(String).join(',') + ')' : ''; + return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join(''); + }; + + return Pseudo; +}(_container["default"]); + +exports["default"] = Pseudo; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/root.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/root.js new file mode 100644 index 0000000..be5c2cc --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/root.js @@ -0,0 +1,60 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _container = _interopRequireDefault(require("./container")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Root = /*#__PURE__*/function (_Container) { + _inheritsLoose(Root, _Container); + + function Root(opts) { + var _this; + + _this = _Container.call(this, opts) || this; + _this.type = _types.ROOT; + return _this; + } + + var _proto = Root.prototype; + + _proto.toString = function toString() { + var str = this.reduce(function (memo, selector) { + memo.push(String(selector)); + return memo; + }, []).join(','); + return this.trailingComma ? str + ',' : str; + }; + + _proto.error = function error(message, options) { + if (this._error) { + return this._error(message, options); + } else { + return new Error(message); + } + }; + + _createClass(Root, [{ + key: "errorGenerator", + set: function set(handler) { + this._error = handler; + } + }]); + + return Root; +}(_container["default"]); + +exports["default"] = Root; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/selector.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/selector.js new file mode 100644 index 0000000..699eeb6 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/selector.js @@ -0,0 +1,31 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _container = _interopRequireDefault(require("./container")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Selector = /*#__PURE__*/function (_Container) { + _inheritsLoose(Selector, _Container); + + function Selector(opts) { + var _this; + + _this = _Container.call(this, opts) || this; + _this.type = _types.SELECTOR; + return _this; + } + + return Selector; +}(_container["default"]); + +exports["default"] = Selector; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/string.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/string.js new file mode 100644 index 0000000..e61df30 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/string.js @@ -0,0 +1,31 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _node = _interopRequireDefault(require("./node")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var String = /*#__PURE__*/function (_Node) { + _inheritsLoose(String, _Node); + + function String(opts) { + var _this; + + _this = _Node.call(this, opts) || this; + _this.type = _types.STRING; + return _this; + } + + return String; +}(_node["default"]); + +exports["default"] = String; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/tag.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/tag.js new file mode 100644 index 0000000..e298db1 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/tag.js @@ -0,0 +1,31 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _namespace = _interopRequireDefault(require("./namespace")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Tag = /*#__PURE__*/function (_Namespace) { + _inheritsLoose(Tag, _Namespace); + + function Tag(opts) { + var _this; + + _this = _Namespace.call(this, opts) || this; + _this.type = _types.TAG; + return _this; + } + + return Tag; +}(_namespace["default"]); + +exports["default"] = Tag; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/types.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/types.js new file mode 100644 index 0000000..ab897b8 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/types.js @@ -0,0 +1,28 @@ +"use strict"; + +exports.__esModule = true; +exports.UNIVERSAL = exports.ATTRIBUTE = exports.CLASS = exports.COMBINATOR = exports.COMMENT = exports.ID = exports.NESTING = exports.PSEUDO = exports.ROOT = exports.SELECTOR = exports.STRING = exports.TAG = void 0; +var TAG = 'tag'; +exports.TAG = TAG; +var STRING = 'string'; +exports.STRING = STRING; +var SELECTOR = 'selector'; +exports.SELECTOR = SELECTOR; +var ROOT = 'root'; +exports.ROOT = ROOT; +var PSEUDO = 'pseudo'; +exports.PSEUDO = PSEUDO; +var NESTING = 'nesting'; +exports.NESTING = NESTING; +var ID = 'id'; +exports.ID = ID; +var COMMENT = 'comment'; +exports.COMMENT = COMMENT; +var COMBINATOR = 'combinator'; +exports.COMBINATOR = COMBINATOR; +var CLASS = 'class'; +exports.CLASS = CLASS; +var ATTRIBUTE = 'attribute'; +exports.ATTRIBUTE = ATTRIBUTE; +var UNIVERSAL = 'universal'; +exports.UNIVERSAL = UNIVERSAL; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/universal.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/universal.js new file mode 100644 index 0000000..cf25473 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/selectors/universal.js @@ -0,0 +1,32 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = void 0; + +var _namespace = _interopRequireDefault(require("./namespace")); + +var _types = require("./types"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +var Universal = /*#__PURE__*/function (_Namespace) { + _inheritsLoose(Universal, _Namespace); + + function Universal(opts) { + var _this; + + _this = _Namespace.call(this, opts) || this; + _this.type = _types.UNIVERSAL; + _this.value = '*'; + return _this; + } + + return Universal; +}(_namespace["default"]); + +exports["default"] = Universal; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/sortAscending.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/sortAscending.js new file mode 100644 index 0000000..3ef56ac --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/sortAscending.js @@ -0,0 +1,13 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = sortAscending; + +function sortAscending(list) { + return list.sort(function (a, b) { + return a - b; + }); +} + +; +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/tokenTypes.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/tokenTypes.js new file mode 100644 index 0000000..48314b9 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/tokenTypes.js @@ -0,0 +1,95 @@ +"use strict"; + +exports.__esModule = true; +exports.combinator = exports.word = exports.comment = exports.str = exports.tab = exports.newline = exports.feed = exports.cr = exports.backslash = exports.bang = exports.slash = exports.doubleQuote = exports.singleQuote = exports.space = exports.greaterThan = exports.pipe = exports.equals = exports.plus = exports.caret = exports.tilde = exports.dollar = exports.closeSquare = exports.openSquare = exports.closeParenthesis = exports.openParenthesis = exports.semicolon = exports.colon = exports.comma = exports.at = exports.asterisk = exports.ampersand = void 0; +var ampersand = 38; // `&`.charCodeAt(0); + +exports.ampersand = ampersand; +var asterisk = 42; // `*`.charCodeAt(0); + +exports.asterisk = asterisk; +var at = 64; // `@`.charCodeAt(0); + +exports.at = at; +var comma = 44; // `,`.charCodeAt(0); + +exports.comma = comma; +var colon = 58; // `:`.charCodeAt(0); + +exports.colon = colon; +var semicolon = 59; // `;`.charCodeAt(0); + +exports.semicolon = semicolon; +var openParenthesis = 40; // `(`.charCodeAt(0); + +exports.openParenthesis = openParenthesis; +var closeParenthesis = 41; // `)`.charCodeAt(0); + +exports.closeParenthesis = closeParenthesis; +var openSquare = 91; // `[`.charCodeAt(0); + +exports.openSquare = openSquare; +var closeSquare = 93; // `]`.charCodeAt(0); + +exports.closeSquare = closeSquare; +var dollar = 36; // `$`.charCodeAt(0); + +exports.dollar = dollar; +var tilde = 126; // `~`.charCodeAt(0); + +exports.tilde = tilde; +var caret = 94; // `^`.charCodeAt(0); + +exports.caret = caret; +var plus = 43; // `+`.charCodeAt(0); + +exports.plus = plus; +var equals = 61; // `=`.charCodeAt(0); + +exports.equals = equals; +var pipe = 124; // `|`.charCodeAt(0); + +exports.pipe = pipe; +var greaterThan = 62; // `>`.charCodeAt(0); + +exports.greaterThan = greaterThan; +var space = 32; // ` `.charCodeAt(0); + +exports.space = space; +var singleQuote = 39; // `'`.charCodeAt(0); + +exports.singleQuote = singleQuote; +var doubleQuote = 34; // `"`.charCodeAt(0); + +exports.doubleQuote = doubleQuote; +var slash = 47; // `/`.charCodeAt(0); + +exports.slash = slash; +var bang = 33; // `!`.charCodeAt(0); + +exports.bang = bang; +var backslash = 92; // '\\'.charCodeAt(0); + +exports.backslash = backslash; +var cr = 13; // '\r'.charCodeAt(0); + +exports.cr = cr; +var feed = 12; // '\f'.charCodeAt(0); + +exports.feed = feed; +var newline = 10; // '\n'.charCodeAt(0); + +exports.newline = newline; +var tab = 9; // '\t'.charCodeAt(0); +// Expose aliases primarily for readability. + +exports.tab = tab; +var str = singleQuote; // No good single character representation! + +exports.str = str; +var comment = -1; +exports.comment = comment; +var word = -2; +exports.word = word; +var combinator = -3; +exports.combinator = combinator; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/tokenize.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/tokenize.js new file mode 100644 index 0000000..bee9fee --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/tokenize.js @@ -0,0 +1,271 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = tokenize; +exports.FIELDS = void 0; + +var t = _interopRequireWildcard(require("./tokenTypes")); + +var _unescapable, _wordDelimiters; + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable); +var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters); +var hex = {}; +var hexChars = "0123456789abcdefABCDEF"; + +for (var i = 0; i < hexChars.length; i++) { + hex[hexChars.charCodeAt(i)] = true; +} +/** + * Returns the last index of the bar css word + * @param {string} css The string in which the word begins + * @param {number} start The index into the string where word's first letter occurs + */ + + +function consumeWord(css, start) { + var next = start; + var code; + + do { + code = css.charCodeAt(next); + + if (wordDelimiters[code]) { + return next - 1; + } else if (code === t.backslash) { + next = consumeEscape(css, next) + 1; + } else { + // All other characters are part of the word + next++; + } + } while (next < css.length); + + return next - 1; +} +/** + * Returns the last index of the escape sequence + * @param {string} css The string in which the sequence begins + * @param {number} start The index into the string where escape character (`\`) occurs. + */ + + +function consumeEscape(css, start) { + var next = start; + var code = css.charCodeAt(next + 1); + + if (unescapable[code]) {// just consume the escape char + } else if (hex[code]) { + var hexDigits = 0; // consume up to 6 hex chars + + do { + next++; + hexDigits++; + code = css.charCodeAt(next + 1); + } while (hex[code] && hexDigits < 6); // if fewer than 6 hex chars, a trailing space ends the escape + + + if (hexDigits < 6 && code === t.space) { + next++; + } + } else { + // the next char is part of the current word + next++; + } + + return next; +} + +var FIELDS = { + TYPE: 0, + START_LINE: 1, + START_COL: 2, + END_LINE: 3, + END_COL: 4, + START_POS: 5, + END_POS: 6 +}; +exports.FIELDS = FIELDS; + +function tokenize(input) { + var tokens = []; + var css = input.css.valueOf(); + var _css = css, + length = _css.length; + var offset = -1; + var line = 1; + var start = 0; + var end = 0; + var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType; + + function unclosed(what, fix) { + if (input.safe) { + // fyi: this is never set to true. + css += fix; + next = css.length - 1; + } else { + throw input.error('Unclosed ' + what, line, start - offset, start); + } + } + + while (start < length) { + code = css.charCodeAt(start); + + if (code === t.newline) { + offset = start; + line += 1; + } + + switch (code) { + case t.space: + case t.tab: + case t.newline: + case t.cr: + case t.feed: + next = start; + + do { + next += 1; + code = css.charCodeAt(next); + + if (code === t.newline) { + offset = next; + line += 1; + } + } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed); + + tokenType = t.space; + endLine = line; + endColumn = next - offset - 1; + end = next; + break; + + case t.plus: + case t.greaterThan: + case t.tilde: + case t.pipe: + next = start; + + do { + next += 1; + code = css.charCodeAt(next); + } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe); + + tokenType = t.combinator; + endLine = line; + endColumn = start - offset; + end = next; + break; + // Consume these characters as single tokens. + + case t.asterisk: + case t.ampersand: + case t.bang: + case t.comma: + case t.equals: + case t.dollar: + case t.caret: + case t.openSquare: + case t.closeSquare: + case t.colon: + case t.semicolon: + case t.openParenthesis: + case t.closeParenthesis: + next = start; + tokenType = code; + endLine = line; + endColumn = start - offset; + end = next + 1; + break; + + case t.singleQuote: + case t.doubleQuote: + quote = code === t.singleQuote ? "'" : '"'; + next = start; + + do { + escaped = false; + next = css.indexOf(quote, next + 1); + + if (next === -1) { + unclosed('quote', quote); + } + + escapePos = next; + + while (css.charCodeAt(escapePos - 1) === t.backslash) { + escapePos -= 1; + escaped = !escaped; + } + } while (escaped); + + tokenType = t.str; + endLine = line; + endColumn = start - offset; + end = next + 1; + break; + + default: + if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) { + next = css.indexOf('*/', start + 2) + 1; + + if (next === 0) { + unclosed('comment', '*/'); + } + + content = css.slice(start, next + 1); + lines = content.split('\n'); + last = lines.length - 1; + + if (last > 0) { + nextLine = line + last; + nextOffset = next - lines[last].length; + } else { + nextLine = line; + nextOffset = offset; + } + + tokenType = t.comment; + line = nextLine; + endLine = nextLine; + endColumn = next - nextOffset; + } else if (code === t.slash) { + next = start; + tokenType = code; + endLine = line; + endColumn = start - offset; + end = next + 1; + } else { + next = consumeWord(css, start); + tokenType = t.word; + endLine = line; + endColumn = next - offset; + } + + end = next + 1; + break; + } // Ensure that the token structure remains consistent + + + tokens.push([tokenType, // [0] Token type + line, // [1] Starting line + start - offset, // [2] Starting column + endLine, // [3] Ending line + endColumn, // [4] Ending column + start, // [5] Start position / Source index + end // [6] End position + ]); // Reset offset for the next token + + if (nextOffset) { + offset = nextOffset; + nextOffset = null; + } + + start = end; + } + + return tokens; +} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/ensureObject.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/ensureObject.js new file mode 100644 index 0000000..3472e07 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/ensureObject.js @@ -0,0 +1,22 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = ensureObject; + +function ensureObject(obj) { + for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + props[_key - 1] = arguments[_key]; + } + + while (props.length > 0) { + var prop = props.shift(); + + if (!obj[prop]) { + obj[prop] = {}; + } + + obj = obj[prop]; + } +} + +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/getProp.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/getProp.js new file mode 100644 index 0000000..53e07c9 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/getProp.js @@ -0,0 +1,24 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = getProp; + +function getProp(obj) { + for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + props[_key - 1] = arguments[_key]; + } + + while (props.length > 0) { + var prop = props.shift(); + + if (!obj[prop]) { + return undefined; + } + + obj = obj[prop]; + } + + return obj; +} + +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/index.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/index.js new file mode 100644 index 0000000..043fda8 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/index.js @@ -0,0 +1,22 @@ +"use strict"; + +exports.__esModule = true; +exports.stripComments = exports.ensureObject = exports.getProp = exports.unesc = void 0; + +var _unesc = _interopRequireDefault(require("./unesc")); + +exports.unesc = _unesc["default"]; + +var _getProp = _interopRequireDefault(require("./getProp")); + +exports.getProp = _getProp["default"]; + +var _ensureObject = _interopRequireDefault(require("./ensureObject")); + +exports.ensureObject = _ensureObject["default"]; + +var _stripComments = _interopRequireDefault(require("./stripComments")); + +exports.stripComments = _stripComments["default"]; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/stripComments.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/stripComments.js new file mode 100644 index 0000000..c74f1fe --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/stripComments.js @@ -0,0 +1,27 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = stripComments; + +function stripComments(str) { + var s = ""; + var commentStart = str.indexOf("/*"); + var lastEnd = 0; + + while (commentStart >= 0) { + s = s + str.slice(lastEnd, commentStart); + var commentEnd = str.indexOf("*/", commentStart + 2); + + if (commentEnd < 0) { + return s; + } + + lastEnd = commentEnd + 2; + commentStart = str.indexOf("/*", lastEnd); + } + + s = s + str.slice(lastEnd); + return s; +} + +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/unesc.js b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/unesc.js new file mode 100644 index 0000000..3136e7e --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/postcss-selector-parser/dist/util/unesc.js @@ -0,0 +1,93 @@ +"use strict"; + +exports.__esModule = true; +exports["default"] = unesc; + +// Many thanks for this post which made this migration much easier. +// https://mathiasbynens.be/notes/css-escapes + +/** + * + * @param {string} str + * @returns {[string, number]|undefined} + */ +function gobbleHex(str) { + var lower = str.toLowerCase(); + var hex = ''; + var spaceTerminated = false; + + for (var i = 0; i < 6 && lower[i] !== undefined; i++) { + var code = lower.charCodeAt(i); // check to see if we are dealing with a valid hex char [a-f|0-9] + + var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57; // https://drafts.csswg.org/css-syntax/#consume-escaped-code-point + + spaceTerminated = code === 32; + + if (!valid) { + break; + } + + hex += lower[i]; + } + + if (hex.length === 0) { + return undefined; + } + + var codePoint = parseInt(hex, 16); + var isSurrogate = codePoint >= 0xD800 && codePoint <= 0xDFFF; // Add special case for + // "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point" + // https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point + + if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10FFFF) { + return ["\uFFFD", hex.length + (spaceTerminated ? 1 : 0)]; + } + + return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)]; +} + +var CONTAINS_ESCAPE = /\\/; + +function unesc(str) { + var needToProcess = CONTAINS_ESCAPE.test(str); + + if (!needToProcess) { + return str; + } + + var ret = ""; + + for (var i = 0; i < str.length; i++) { + if (str[i] === "\\") { + var gobbled = gobbleHex(str.slice(i + 1, i + 7)); + + if (gobbled !== undefined) { + ret += gobbled[0]; + i += gobbled[1]; + continue; + } // Retain a pair of \\ if double escaped `\\\\` + // https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e + + + if (str[i + 1] === "\\") { + ret += "\\"; + i++; + continue; + } // if \\ is at the end of the string retain it + // https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb + + + if (str.length === i + 1) { + ret += str[i]; + } + + continue; + } + + ret += str[i]; + } + + return ret; +} + +module.exports = exports.default; \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/format.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/format.d.ts new file mode 100644 index 0000000..185b4c2 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/format.d.ts @@ -0,0 +1,5 @@ +/// +/// +import { KeyObject } from 'crypto'; +import { CertificateRequest } from '../client/fulcio'; +export declare function toCertificateRequest(publicKey: KeyObject, challenge: Buffer): CertificateRequest; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/format.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/format.js new file mode 100644 index 0000000..f168cbe --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/format.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toCertificateRequest = void 0; +function toCertificateRequest(publicKey, challenge) { + return { + publicKey: { + content: publicKey + .export({ type: 'spki', format: 'der' }) + .toString('base64'), + }, + signedEmailAddress: challenge.toString('base64'), + }; +} +exports.toCertificateRequest = toCertificateRequest; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/index.d.ts new file mode 100644 index 0000000..0ee0bf4 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/index.d.ts @@ -0,0 +1,14 @@ +/// +/// +import { KeyObject } from 'crypto'; +export interface CA { + createSigningCertificate: (identityToken: string, publicKey: KeyObject, challenge: Buffer) => Promise; +} +export interface CAClientOptions { + fulcioBaseURL: string; +} +export declare class CAClient implements CA { + private fulcio; + constructor(options: CAClientOptions); + createSigningCertificate(identityToken: string, publicKey: KeyObject, challenge: Buffer): Promise; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/index.js new file mode 100644 index 0000000..3b90f86 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/index.js @@ -0,0 +1,23 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CAClient = void 0; +const client_1 = require("../client"); +const error_1 = require("../error"); +const util_1 = require("../util"); +const format_1 = require("./format"); +class CAClient { + constructor(options) { + this.fulcio = new client_1.Fulcio({ baseURL: options.fulcioBaseURL }); + } + async createSigningCertificate(identityToken, publicKey, challenge) { + const request = (0, format_1.toCertificateRequest)(publicKey, challenge); + try { + const certificate = await this.fulcio.createSigningCertificate(identityToken, request); + return util_1.pem.split(certificate); + } + catch (err) { + throw new error_1.InternalError('error creating signing certificate', err); + } + } +} +exports.CAClient = CAClient; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/chain.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/chain.d.ts new file mode 100644 index 0000000..7ccc0dc --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/chain.d.ts @@ -0,0 +1,3 @@ +import * as sigstore from '../../types/sigstore'; +import { x509Certificate } from '../../x509/cert'; +export declare function verifyChain(bundleCerts: sigstore.X509Certificate[], certificateAuthorities: sigstore.CertificateAuthority[]): x509Certificate[]; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/chain.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/chain.js new file mode 100644 index 0000000..0f6f714 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/chain.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifyChain = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = require("../../error"); +const cert_1 = require("../../x509/cert"); +const verify_1 = require("../../x509/verify"); +function verifyChain(bundleCerts, certificateAuthorities) { + const certs = parseCerts(bundleCerts); + const signingCert = certs[0]; + // Filter the list of certificate authorities to those which are valid for the + // signing certificate's notBefore date. + const validCAs = filterCertificateAuthorities(certificateAuthorities, signingCert.notBefore); + if (validCAs.length === 0) { + throw new error_1.VerificationError('No valid certificate authorities'); + } + let trustedChain = []; + // Loop through all valid CAs and attempt to verify the certificate chain + const verified = validCAs.find((ca) => { + const trustedCerts = parseCerts(ca.certChain?.certificates || []); + try { + trustedChain = (0, verify_1.verifyCertificateChain)({ + trustedCerts, + certs, + validAt: signingCert.notBefore, + }); + return true; + } + catch (e) { + return false; + } + }); + if (!verified) { + throw new error_1.VerificationError('No valid certificate chain'); + } + return trustedChain; +} +exports.verifyChain = verifyChain; +// Filter the list of certificate authorities to those which are valid for the +// given date. +function filterCertificateAuthorities(certificateAuthorities, validAt) { + return certificateAuthorities.filter((ca) => ca.validFor && + ca.validFor.start && + ca.validFor.start <= validAt && + (!ca.validFor.end || validAt <= ca.validFor.end)); +} +// Parse the raw bytes of a certificate into an x509Certificate object. +function parseCerts(certs) { + return certs.map((cert) => cert_1.x509Certificate.parse(cert.rawBytes)); +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/index.d.ts new file mode 100644 index 0000000..ddf65ff --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/index.d.ts @@ -0,0 +1,2 @@ +import * as sigstore from '../../types/sigstore'; +export declare function verifySigningCertificate(bundle: sigstore.BundleWithCertificateChain, trustedRoot: sigstore.TrustedRoot, options: sigstore.CAArtifactVerificationOptions): void; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/index.js new file mode 100644 index 0000000..9c42f30 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/index.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySigningCertificate = void 0; +const chain_1 = require("./chain"); +const sct_1 = require("./sct"); +const signer_1 = require("./signer"); +function verifySigningCertificate(bundle, trustedRoot, options) { + // Check that a trusted certificate chain can be found for the signing + // certificate in the bundle + const trustedChain = (0, chain_1.verifyChain)(bundle.verificationMaterial.content.x509CertificateChain.certificates, trustedRoot.certificateAuthorities); + // Unless disabled, verify the SCTs in the signing certificate + if (options.ctlogOptions.disable === false) { + (0, sct_1.verifySCTs)(trustedChain, trustedRoot.ctlogs, options.ctlogOptions); + } + // Verify the signing certificate against the provided identities + // if provided + if (options.signers) { + (0, signer_1.verifySignerIdentity)(trustedChain[0], options.signers.certificateIdentities); + } +} +exports.verifySigningCertificate = verifySigningCertificate; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/sct.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/sct.d.ts new file mode 100644 index 0000000..29391a7 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/sct.d.ts @@ -0,0 +1,3 @@ +import * as sigstore from '../../types/sigstore'; +import { x509Certificate } from '../../x509/cert'; +export declare function verifySCTs(certificateChain: x509Certificate[], ctLogs: sigstore.TransparencyLogInstance[], options: sigstore.ArtifactVerificationOptions_CtlogOptions): void; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/sct.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/sct.js new file mode 100644 index 0000000..771c6dd --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/sct.js @@ -0,0 +1,30 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySCTs = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = require("../../error"); +function verifySCTs(certificateChain, ctLogs, options) { + const signingCert = certificateChain[0]; + const issuerCert = certificateChain[1]; + const sctResults = signingCert.verifySCTs(issuerCert, ctLogs); + // Count the number of verified SCTs which were found + const verifiedSCTCount = sctResults.filter((sct) => sct.verified).length; + if (verifiedSCTCount < options.threshold) { + throw new error_1.VerificationError(`Not enough SCTs verified (found ${verifiedSCTCount}, need ${options.threshold})`); + } +} +exports.verifySCTs = verifySCTs; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/signer.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/signer.d.ts new file mode 100644 index 0000000..7241b90 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/signer.d.ts @@ -0,0 +1,3 @@ +import * as sigstore from '../../types/sigstore'; +import { x509Certificate } from '../../x509/cert'; +export declare function verifySignerIdentity(signingCert: x509Certificate, identities: sigstore.CertificateIdentities): void; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/signer.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/signer.js new file mode 100644 index 0000000..2c49f0b --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/ca/verify/signer.js @@ -0,0 +1,131 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySignerIdentity = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = require("../../error"); +const sigstore = __importStar(require("../../types/sigstore")); +// https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#1361415726411--issuer +const OID_FULCIO_ISSUER = '1.3.6.1.4.1.57264.1.1'; +// https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#1361415726417--othername-san +const OID_FULCIO_USERNAME_SUBJECT = '1.3.6.1.4.1.57264.1.7'; +// Verifies the identity embedded in a Fulcio-issued signing certificate against +// the list of trusted identities. Returns without error if at least one of the +// identities matches the signing certificate; otherwise, throws a +// VerificationError. +function verifySignerIdentity(signingCert, identities) { + // Check that the signing certificate was issued to at least one of the + // specified identities + const signerVerified = identities.identities.some((identity) => verifyIdentity(signingCert, identity)); + if (!signerVerified) { + throw new error_1.PolicyError('Certificate issued to untrusted signer'); + } +} +exports.verifySignerIdentity = verifySignerIdentity; +// Checks that the specified certificate was issued to the specified identity. +// The certificate must match the issuer, subject alternative name, and an +// optional list of certificate extensions. Returns true if the certificate was +// issued to the identity; otherwise, returns false. +function verifyIdentity(cert, identity) { + return (verifyIssuer(cert, identity.issuer) && + verifySAN(cert, identity.san) && + verifyOIDs(cert, identity.oids)); +} +// Checks the Fulcio issuer extension against the expected issuer. Returns true +// if the issuer matches; otherwise, returns false. +function verifyIssuer(cert, issuer) { + const issuerExtension = cert.extension(OID_FULCIO_ISSUER); + return issuerExtension?.value.toString('ascii') === issuer; +} +// Checks the certificate against the expected subject alternative name. Returns +// true if the SAN matches; otherwise, returns false. +function verifySAN(cert, expectedSAN) { + // Fail if the SAN is not specified or is not a supported type + if (expectedSAN === undefined || + expectedSAN.identity === undefined || + expectedSAN.type === + sigstore.SubjectAlternativeNameType + .SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED) { + return false; + } + const sanExtension = cert.extSubjectAltName; + // Fail if the certificate does not have a SAN extension + if (!sanExtension) { + return false; + } + let sanValue; + switch (expectedSAN.type) { + case sigstore.SubjectAlternativeNameType.EMAIL: + sanValue = sanExtension.rfc822Name; + break; + case sigstore.SubjectAlternativeNameType.URI: + sanValue = sanExtension.uri; + break; + case sigstore.SubjectAlternativeNameType.OTHER_NAME: + sanValue = sanExtension.otherName(OID_FULCIO_USERNAME_SUBJECT); + break; + } + // Missing SAN value is an automatic failure + if (sanValue === undefined) { + return false; + } + let match; + switch (expectedSAN.identity.$case) { + case 'value': + match = expectedSAN.identity.value; + break; + case 'regexp': + // TODO support regex + break; + } + return sanValue === match; +} +// Checks that the certificate contains the specified extensions. Returns true +// if all extensions are present and match the expected values; otherwise, +// returns false. +function verifyOIDs(cert, oids) { + return oids.every((expectedExtension) => { + if (!expectedExtension.oid) { + return false; + } + const oid = expectedExtension.oid.id.join('.'); + const extension = cert.extension(oid); + return extension?.value.equals(expectedExtension.value); + }); +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/cli/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/cli/index.d.ts new file mode 100644 index 0000000..395f0a5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/cli/index.d.ts @@ -0,0 +1 @@ +export declare function processArgv(): Promise; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/cli/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/cli/index.js new file mode 100644 index 0000000..0937d36 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/cli/index.js @@ -0,0 +1,113 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.processArgv = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const fs_1 = __importDefault(require("fs")); +const index_1 = require("../index"); +const INTOTO_PAYLOAD_TYPE = 'application/vnd.in-toto+json'; +async function cli(args) { + switch (args[0]) { + case 'sign': + await sign(args[1]); + break; + case 'attest': + await attest(args[1], args[2]); + break; + case 'verify': + await verify(args[1], args[2]); + break; + case 'version': + case '-version': + case '--version': + case '-v': + // eslint-disable-next-line @typescript-eslint/no-var-requires + console.log(require('../../package.json').version); + break; + case 'help': + case '--help': + case '-h': + case '-?': + printUsage(); + break; + default: + throw 'Unknown command'; + } +} +function printUsage() { + console.log(`sigstore + + Usage: + + sigstore sign sign an artifact + sigstore attest sign an artifact using dsse (Dead Simple Signing Envelope) + sigstore verify verify an artifact + sigstore version print version information + sigstore help print help information + `); +} +const signOptions = { + oidcClientID: 'sigstore', + oidcIssuer: 'https://oauth2.sigstore.dev/auth', + rekorURL: index_1.sigstore.DEFAULT_REKOR_URL, +}; +async function sign(artifactPath) { + const buffer = fs_1.default.readFileSync(artifactPath); + const bundle = await index_1.sigstore.sign(buffer, signOptions); + const url = `${signOptions.rekorURL}/api/v1/log/entries`; + const logIndex = bundle.verificationMaterial?.tlogEntries[0].logIndex; + console.error(`Created entry at index ${logIndex}, available at`); + console.error(`${url}?logIndex=${logIndex}`); + console.log(JSON.stringify(bundle)); +} +async function attest(artifactPath, payloadType = INTOTO_PAYLOAD_TYPE) { + const buffer = fs_1.default.readFileSync(artifactPath); + const bundle = await index_1.sigstore.attest(buffer, payloadType, signOptions); + console.log(JSON.stringify(bundle)); +} +async function verify(bundlePath, artifactPath) { + let payload = undefined; + if (artifactPath) { + payload = fs_1.default.readFileSync(artifactPath); + } + const bundleFile = fs_1.default.readFileSync(bundlePath); + const bundle = JSON.parse(bundleFile.toString('utf-8')); + try { + await index_1.sigstore.verify(bundle, payload, {}); + console.error('Verified OK'); + } + catch (e) { + console.error('Verification failed'); + if (e instanceof Error) { + console.error('Error: ' + e.message); + } + process.exit(1); + } +} +async function processArgv() { + try { + await cli(process.argv.slice(2)); + process.exit(0); + } + catch (e) { + console.error(e); + process.exit(1); + } +} +exports.processArgv = processArgv; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/client/error.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/error.d.ts new file mode 100644 index 0000000..87a4bc5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/error.d.ts @@ -0,0 +1,10 @@ +import fetch from 'make-fetch-happen'; +type Response = Awaited>; +export declare class HTTPError extends Error { + response: Response; + statusCode: number; + location?: string; + constructor(response: Response); +} +export declare const checkStatus: (response: Response) => Response; +export {}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/client/error.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/error.js new file mode 100644 index 0000000..d1e1c3d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/error.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.checkStatus = exports.HTTPError = void 0; +class HTTPError extends Error { + constructor(response) { + super(`HTTP Error: ${response.status} ${response.statusText}`); + this.response = response; + this.statusCode = response.status; + this.location = response.headers?.get('Location') || undefined; + } +} +exports.HTTPError = HTTPError; +const checkStatus = (response) => { + if (response.ok) { + return response; + } + else { + throw new HTTPError(response); + } +}; +exports.checkStatus = checkStatus; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/client/fulcio.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/fulcio.d.ts new file mode 100644 index 0000000..72ed51a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/fulcio.d.ts @@ -0,0 +1,18 @@ +export interface FulcioOptions { + baseURL: string; +} +export interface CertificateRequest { + publicKey: { + content: string; + }; + signedEmailAddress: string; +} +/** + * Fulcio API client. + */ +export declare class Fulcio { + private fetch; + private baseUrl; + constructor(options: FulcioOptions); + createSigningCertificate(idToken: string, request: CertificateRequest): Promise; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/client/fulcio.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/fulcio.js new file mode 100644 index 0000000..0404138 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/fulcio.js @@ -0,0 +1,53 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Fulcio = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const make_fetch_happen_1 = __importDefault(require("make-fetch-happen")); +const util_1 = require("../util"); +const error_1 = require("./error"); +/** + * Fulcio API client. + */ +class Fulcio { + constructor(options) { + this.fetch = make_fetch_happen_1.default.defaults({ + retry: { retries: 2 }, + timeout: 5000, + headers: { + Accept: 'application/pem-certificate-chain', + 'Content-Type': 'application/json', + 'User-Agent': util_1.ua.getUserAgent(), + }, + }); + this.baseUrl = options.baseURL; + } + async createSigningCertificate(idToken, request) { + const url = `${this.baseUrl}/api/v1/signingCert`; + const response = await this.fetch(url, { + method: 'POST', + headers: { Authorization: `Bearer ${idToken}` }, + body: JSON.stringify(request), + }); + (0, error_1.checkStatus)(response); + const data = await response.text(); + return data; + } +} +exports.Fulcio = Fulcio; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/client/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/index.d.ts new file mode 100644 index 0000000..2102381 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/index.d.ts @@ -0,0 +1,2 @@ +export { Fulcio } from './fulcio'; +export { Rekor } from './rekor'; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/client/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/index.js new file mode 100644 index 0000000..c6d1d9a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/index.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Rekor = exports.Fulcio = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +var fulcio_1 = require("./fulcio"); +Object.defineProperty(exports, "Fulcio", { enumerable: true, get: function () { return fulcio_1.Fulcio; } }); +var rekor_1 = require("./rekor"); +Object.defineProperty(exports, "Rekor", { enumerable: true, get: function () { return rekor_1.Rekor; } }); diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/client/rekor.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/rekor.d.ts new file mode 100644 index 0000000..55a909f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/rekor.d.ts @@ -0,0 +1,45 @@ +import { Entry, EntryKind } from '../tlog'; +export interface RekorOptions { + baseURL: string; +} +export interface SearchIndex { + email?: string; + hash?: string; +} +export interface SearchLogQuery { + entries?: EntryKind[]; + entryUUIDs?: string[]; + logIndexes?: number[]; +} +/** + * Rekor API client. + */ +export declare class Rekor { + private fetch; + private baseUrl; + constructor(options: RekorOptions); + /** + * Create a new entry in the Rekor log. + * @param propsedEntry {EntryKind} Data to create a new entry + * @returns {Promise} The created entry + */ + createEntry(propsedEntry: EntryKind): Promise; + /** + * Get an entry from the Rekor log. + * @param uuid {string} The UUID of the entry to retrieve + * @returns {Promise} The retrieved entry + */ + getEntry(uuid: string): Promise; + /** + * Search the Rekor log index for entries matching the given query. + * @param opts {SearchIndex} Options to search the Rekor log + * @returns {Promise} UUIDs of matching entries + */ + searchIndex(opts: SearchIndex): Promise; + /** + * Search the Rekor logs for matching the given query. + * @param opts {SearchLogQuery} Query to search the Rekor log + * @returns {Promise} List of matching entries + */ + searchLog(opts: SearchLogQuery): Promise; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/client/rekor.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/rekor.js new file mode 100644 index 0000000..6bb085c --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/client/rekor.js @@ -0,0 +1,115 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Rekor = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const make_fetch_happen_1 = __importDefault(require("make-fetch-happen")); +const util_1 = require("../util"); +const error_1 = require("./error"); +/** + * Rekor API client. + */ +class Rekor { + constructor(options) { + this.fetch = make_fetch_happen_1.default.defaults({ + retry: { retries: 2 }, + timeout: 5000, + headers: { + Accept: 'application/json', + 'User-Agent': util_1.ua.getUserAgent(), + }, + }); + this.baseUrl = options.baseURL; + } + /** + * Create a new entry in the Rekor log. + * @param propsedEntry {EntryKind} Data to create a new entry + * @returns {Promise} The created entry + */ + async createEntry(propsedEntry) { + const url = `${this.baseUrl}/api/v1/log/entries`; + const response = await this.fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(propsedEntry), + }); + (0, error_1.checkStatus)(response); + const data = await response.json(); + return entryFromResponse(data); + } + /** + * Get an entry from the Rekor log. + * @param uuid {string} The UUID of the entry to retrieve + * @returns {Promise} The retrieved entry + */ + async getEntry(uuid) { + const url = `${this.baseUrl}/api/v1/log/entries/${uuid}`; + const response = await this.fetch(url); + (0, error_1.checkStatus)(response); + const data = await response.json(); + return entryFromResponse(data); + } + /** + * Search the Rekor log index for entries matching the given query. + * @param opts {SearchIndex} Options to search the Rekor log + * @returns {Promise} UUIDs of matching entries + */ + async searchIndex(opts) { + const url = `${this.baseUrl}/api/v1/index/retrieve`; + const response = await this.fetch(url, { + method: 'POST', + body: JSON.stringify(opts), + headers: { 'Content-Type': 'application/json' }, + }); + (0, error_1.checkStatus)(response); + const data = await response.json(); + return data; + } + /** + * Search the Rekor logs for matching the given query. + * @param opts {SearchLogQuery} Query to search the Rekor log + * @returns {Promise} List of matching entries + */ + async searchLog(opts) { + const url = `${this.baseUrl}/api/v1/log/entries/retrieve`; + const response = await this.fetch(url, { + method: 'POST', + body: JSON.stringify(opts), + headers: { 'Content-Type': 'application/json' }, + }); + (0, error_1.checkStatus)(response); + const rawData = await response.json(); + const data = rawData.map((d) => entryFromResponse(d)); + return data; + } +} +exports.Rekor = Rekor; +// Unpack the response from the Rekor API into a more convenient format. +function entryFromResponse(data) { + const entries = Object.entries(data); + if (entries.length != 1) { + throw new Error('Received multiple entries in Rekor response'); + } + // Grab UUID and entry data from the response + const [uuid, entry] = Object.entries(data)[0]; + return { + ...entry, + uuid, + }; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/error.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/error.d.ts new file mode 100644 index 0000000..0e2dad0 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/error.d.ts @@ -0,0 +1,13 @@ +declare class BaseError extends Error { + cause: any | undefined; + constructor(message: string, cause?: any); +} +export declare class VerificationError extends BaseError { +} +export declare class ValidationError extends BaseError { +} +export declare class InternalError extends BaseError { +} +export declare class PolicyError extends BaseError { +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/error.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/error.js new file mode 100644 index 0000000..e302d3a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/error.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PolicyError = exports.InternalError = exports.ValidationError = exports.VerificationError = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +/* eslint-disable @typescript-eslint/no-explicit-any */ +class BaseError extends Error { + constructor(message, cause) { + super(message); + this.name = this.constructor.name; + this.cause = cause; + } +} +class VerificationError extends BaseError { +} +exports.VerificationError = VerificationError; +class ValidationError extends BaseError { +} +exports.ValidationError = ValidationError; +class InternalError extends BaseError { +} +exports.InternalError = InternalError; +class PolicyError extends BaseError { +} +exports.PolicyError = PolicyError; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/ci.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/ci.d.ts new file mode 100644 index 0000000..428606f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/ci.d.ts @@ -0,0 +1,11 @@ +import { Provider } from './provider'; +/** + * CIContextProvider is a composite identity provider which will iterate + * over all of the CI-specific providers and return the token from the first + * one that resolves. + */ +export declare class CIContextProvider implements Provider { + private audience; + constructor(audience: string); + getToken(): Promise; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/ci.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/ci.js new file mode 100644 index 0000000..fecf63f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/ci.js @@ -0,0 +1,65 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CIContextProvider = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const make_fetch_happen_1 = __importDefault(require("make-fetch-happen")); +const util_1 = require("../util"); +// Collection of all the CI-specific providers we have implemented +const providers = [getGHAToken]; +/** + * CIContextProvider is a composite identity provider which will iterate + * over all of the CI-specific providers and return the token from the first + * one that resolves. + */ +class CIContextProvider { + constructor(audience) { + this.audience = audience; + } + // Invoke all registered ProviderFuncs and return the value of whichever one + // resolves first. + async getToken() { + return util_1.promise + .promiseAny(providers.map((getToken) => getToken(this.audience))) + .catch(() => Promise.reject('CI: no tokens available')); + } +} +exports.CIContextProvider = CIContextProvider; +/** + * getGHAToken can retrieve an OIDC token when running in a GitHub Actions + * workflow + */ +async function getGHAToken(audience) { + // Check to see if we're running in GitHub Actions + if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL || + !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) { + return Promise.reject('no token available'); + } + // Construct URL to request token w/ appropriate audience + const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL); + url.searchParams.append('audience', audience); + const response = await (0, make_fetch_happen_1.default)(url.href, { + retry: 2, + headers: { + Accept: 'application/json', + Authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}`, + }, + }); + return response.json().then((data) => data.value); +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/index.d.ts new file mode 100644 index 0000000..e3d23b4 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/index.d.ts @@ -0,0 +1,25 @@ +import { Provider } from './provider'; +/** + * oauthProvider returns a new Provider instance which attempts to retrieve + * an identity token from the configured OAuth2 issuer. + * + * @param issuer Base URL of the issuer + * @param clientID Client ID for the issuer + * @param clientSecret Client secret for the issuer (optional) + * @returns {Provider} + */ +declare function oauthProvider(issuer: string, clientID: string, clientSecret?: string): Provider; +/** + * ciContextProvider returns a new Provider instance which attempts to retrieve + * an identity token from the CI context. + * + * @param audience audience claim for the generated token + * @returns {Provider} + */ +declare function ciContextProvider(audience?: string): Provider; +declare const _default: { + ciContextProvider: typeof ciContextProvider; + oauthProvider: typeof oauthProvider; +}; +export default _default; +export { Provider } from './provider'; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/index.js new file mode 100644 index 0000000..bfb203a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/index.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const ci_1 = require("./ci"); +const issuer_1 = require("./issuer"); +const oauth_1 = require("./oauth"); +/** + * oauthProvider returns a new Provider instance which attempts to retrieve + * an identity token from the configured OAuth2 issuer. + * + * @param issuer Base URL of the issuer + * @param clientID Client ID for the issuer + * @param clientSecret Client secret for the issuer (optional) + * @returns {Provider} + */ +function oauthProvider(issuer, clientID, clientSecret) { + return new oauth_1.OAuthProvider(new issuer_1.Issuer(issuer), clientID, clientSecret); +} +/** + * ciContextProvider returns a new Provider instance which attempts to retrieve + * an identity token from the CI context. + * + * @param audience audience claim for the generated token + * @returns {Provider} + */ +function ciContextProvider(audience = 'sigstore') { + return new ci_1.CIContextProvider(audience); +} +exports.default = { + ciContextProvider, + oauthProvider, +}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/issuer.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/issuer.d.ts new file mode 100644 index 0000000..37ad713 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/issuer.d.ts @@ -0,0 +1,15 @@ +/** + * The Issuer reperesents a single OAuth2 provider. + * + * The Issuer is configured with a provider's base OAuth2 endpoint which is + * used to retrieve the associated configuration information. + */ +export declare class Issuer { + private baseURL; + private fetch; + private config?; + constructor(baseURL: string); + authEndpoint(): Promise; + tokenEndpoint(): Promise; + private loadOpenIDConfig; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/issuer.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/issuer.js new file mode 100644 index 0000000..2bf6c20 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/issuer.js @@ -0,0 +1,53 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Issuer = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const make_fetch_happen_1 = __importDefault(require("make-fetch-happen")); +// Standard endpoint for retrieving OpenID configuration information +const OPENID_CONFIG_PATH = '/.well-known/openid-configuration'; +/** + * The Issuer reperesents a single OAuth2 provider. + * + * The Issuer is configured with a provider's base OAuth2 endpoint which is + * used to retrieve the associated configuration information. + */ +class Issuer { + constructor(baseURL) { + this.baseURL = baseURL; + this.fetch = make_fetch_happen_1.default.defaults({ retry: 2 }); + } + async authEndpoint() { + if (!this.config) { + this.config = await this.loadOpenIDConfig(); + } + return this.config.authorization_endpoint; + } + async tokenEndpoint() { + if (!this.config) { + this.config = await this.loadOpenIDConfig(); + } + return this.config.token_endpoint; + } + async loadOpenIDConfig() { + const url = `${this.baseURL}${OPENID_CONFIG_PATH}`; + return this.fetch(url).then((res) => res.json()); + } +} +exports.Issuer = Issuer; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/oauth.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/oauth.d.ts new file mode 100644 index 0000000..d02e212 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/oauth.d.ts @@ -0,0 +1,19 @@ +import { Issuer } from './issuer'; +import { Provider } from './provider'; +export declare class OAuthProvider implements Provider { + private clientID; + private clientSecret; + private issuer; + private codeVerifier; + private state; + private redirectURI?; + constructor(issuer: Issuer, clientID: string, clientSecret?: string); + getToken(): Promise; + private initiateAuthRequest; + private getIDToken; + private getBasicAuthHeaderValue; + private getAuthRequestURL; + private getAuthRequestParams; + private getCodeChallenge; + private openURL; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/oauth.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/oauth.js new file mode 100644 index 0000000..651a0c7 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/oauth.js @@ -0,0 +1,188 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OAuthProvider = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const assert_1 = __importDefault(require("assert")); +const child_process_1 = __importDefault(require("child_process")); +const http_1 = __importDefault(require("http")); +const make_fetch_happen_1 = __importDefault(require("make-fetch-happen")); +const url_1 = require("url"); +const util_1 = require("../util"); +class OAuthProvider { + constructor(issuer, clientID, clientSecret) { + this.clientID = clientID; + this.clientSecret = clientSecret || ''; + this.issuer = issuer; + this.codeVerifier = generateRandomString(32); + this.state = generateRandomString(16); + } + async getToken() { + const authCode = await this.initiateAuthRequest(); + return this.getIDToken(authCode); + } + // Initates the authorization request. This will start an HTTP server to + // receive the post-auth redirect and then open the user's default browser to + // the provider's authorization page. + async initiateAuthRequest() { + const server = http_1.default.createServer(); + const sockets = new Set(); + // Start server and wait till it is listening + await new Promise((resolve) => { + server.listen(0, resolve); + }); + // Keep track of connections to the server so we can force a shutdown + server.on('connection', (socket) => { + sockets.add(socket); + socket.once('close', () => { + sockets.delete(socket); + }); + }); + // Get port the server is listening on and construct the server URL + const port = server.address().port; + this.redirectURI = `http://localhost:${port}`; + const result = new Promise((resolve, reject) => { + // Set-up handler for post-auth redirect + server.on('request', (req, res) => { + if (!req.url) { + reject('invalid server request'); + return; + } + res.writeHead(200); + res.end('Auth Successful'); + // Parse incoming request URL + const query = new url_1.URL(req.url, this.redirectURI).searchParams; + // Check to see if the state matches + if (query.get('state') !== this.state) { + reject('invalid state value'); + return; + } + const authCode = query.get('code'); + // Force-close any open connections to the server so we can get a + // clean shutdown + for (const socket of sockets) { + socket.destroy(); + sockets.delete(socket); + } + // Return auth code once we've shutdown server + server.close(() => { + if (!authCode) { + reject('authorization code not found'); + } + else { + resolve(authCode); + } + }); + }); + }); + try { + // Open browser to start authorization request + const authBaseURL = await this.issuer.authEndpoint(); + const authURL = this.getAuthRequestURL(authBaseURL); + await this.openURL(authURL); + } + catch (err) { + // Prevent leaked server handler on error + server.close(); + throw err; + } + return result; + } + // Uses the provided authorization code, to retrieve the ID token from the + // provider + async getIDToken(authCode) { + (0, assert_1.default)(this.redirectURI); + const tokenEndpointURL = await this.issuer.tokenEndpoint(); + const params = new url_1.URLSearchParams(); + params.append('grant_type', 'authorization_code'); + params.append('code', authCode); + params.append('redirect_uri', this.redirectURI); + params.append('code_verifier', this.codeVerifier); + const response = await (0, make_fetch_happen_1.default)(tokenEndpointURL, { + method: 'POST', + headers: { Authorization: `Basic ${this.getBasicAuthHeaderValue()}` }, + body: params, + }).then((r) => r.json()); + return response.id_token; + } + // Construct the basic auth header value from the client ID and secret + getBasicAuthHeaderValue() { + return util_1.encoding.base64Encode(`${this.clientID}:${this.clientSecret}`); + } + // Generate starting URL for authorization request + getAuthRequestURL(baseURL) { + const params = this.getAuthRequestParams(); + return `${baseURL}?${params.toString()}`; + } + // Collect parameters for authorization request + getAuthRequestParams() { + (0, assert_1.default)(this.redirectURI); + const codeChallenge = this.getCodeChallenge(); + return new url_1.URLSearchParams({ + response_type: 'code', + client_id: this.clientID, + client_secret: this.clientSecret, + scope: 'openid email', + redirect_uri: this.redirectURI, + code_challenge: codeChallenge, + code_challenge_method: 'S256', + state: this.state, + nonce: generateRandomString(16), + }); + } + // Generate code challenge for authorization request + getCodeChallenge() { + return util_1.encoding.base64URLEscape(util_1.crypto.hash(this.codeVerifier).toString('base64')); + } + // Open the supplied URL in the user's default browser + async openURL(url) { + return new Promise((resolve, reject) => { + let open = null; + let command = `"${url}"`; + switch (process.platform) { + case 'darwin': + open = 'open'; + break; + case 'linux' || 'freebsd' || 'netbsd' || 'openbsd': + open = 'xdg-open'; + break; + case 'win32': + open = 'start'; + command = `"" ${command}`; + break; + default: + return reject(`OAuth: unsupported platform: ${process.platform}`); + } + console.error(`Your browser will now be opened to: ${url}`); + child_process_1.default.exec(`${open} ${command}`, undefined, (err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + }); + } +} +exports.OAuthProvider = OAuthProvider; +// Generate random code verifier value +function generateRandomString(len) { + return util_1.encoding.base64URLEscape(util_1.crypto.randomBytes(len).toString('base64')); +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/provider.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/provider.d.ts new file mode 100644 index 0000000..95ec03e --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/provider.d.ts @@ -0,0 +1,3 @@ +export interface Provider { + getToken: () => Promise; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/provider.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/provider.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/identity/provider.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/index.d.ts new file mode 100644 index 0000000..fb23e5e --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/index.d.ts @@ -0,0 +1 @@ +export * as sigstore from './sigstore'; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/index.js new file mode 100644 index 0000000..502155e --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/index.js @@ -0,0 +1,42 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.sigstore = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +exports.sigstore = __importStar(require("./sigstore")); diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/digest.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/digest.d.ts new file mode 100644 index 0000000..5c69221 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/digest.d.ts @@ -0,0 +1,8 @@ +/// +export declare class Hasher { + private algorithm; + constructor(algorithm?: string); + size(): number; + hashLeaf(leaf: Buffer): Buffer; + hashChildren(l: Buffer, r: Buffer): Buffer; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/digest.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/digest.js new file mode 100644 index 0000000..5b7ff04 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/digest.js @@ -0,0 +1,48 @@ +"use strict"; +/* +Copyright 2022 GitHub, Inc + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Hasher = void 0; +const crypto_1 = __importDefault(require("crypto")); +const RFC6962LeafHashPrefix = Buffer.from([0x00]); +const RFC6962NodeHashPrefix = Buffer.from([0x01]); +// Implements Merkle Tree Hash logic according to RFC6962. +// https://datatracker.ietf.org/doc/html/rfc6962#section-2 +class Hasher { + constructor(algorithm = 'sha256') { + this.algorithm = algorithm; + } + size() { + return crypto_1.default.createHash(this.algorithm).digest().length; + } + hashLeaf(leaf) { + const hasher = crypto_1.default.createHash(this.algorithm); + hasher.update(RFC6962LeafHashPrefix); + hasher.update(leaf); + return hasher.digest(); + } + hashChildren(l, r) { + const hasher = crypto_1.default.createHash(this.algorithm); + hasher.update(RFC6962NodeHashPrefix); + hasher.update(l); + hasher.update(r); + return hasher.digest(); + } +} +exports.Hasher = Hasher; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/index.d.ts new file mode 100644 index 0000000..d8ffe7c --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/index.d.ts @@ -0,0 +1,2 @@ +export { Hasher } from './digest'; +export { verifyInclusion } from './verify'; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/index.js new file mode 100644 index 0000000..2dd39f1 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/index.js @@ -0,0 +1,22 @@ +"use strict"; +/* +Copyright 2022 GitHub, Inc + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifyInclusion = exports.Hasher = void 0; +var digest_1 = require("./digest"); +Object.defineProperty(exports, "Hasher", { enumerable: true, get: function () { return digest_1.Hasher; } }); +var verify_1 = require("./verify"); +Object.defineProperty(exports, "verifyInclusion", { enumerable: true, get: function () { return verify_1.verifyInclusion; } }); diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/verify.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/verify.d.ts new file mode 100644 index 0000000..b1b28b7 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/verify.d.ts @@ -0,0 +1,3 @@ +/// +import { Hasher } from './digest'; +export declare function verifyInclusion(hasher: Hasher, index: bigint, size: bigint, leafHash: Buffer, proof: Buffer[], root: Buffer): boolean; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/verify.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/verify.js new file mode 100644 index 0000000..3455434 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/merkle/verify.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifyInclusion = void 0; +/* +Copyright 2022 GitHub, Inc + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +// Implementation largely copied from +// https://github.com/transparency-dev/merkle/blob/main/proof/verify.go#L46 +// Verifies the correctness of the inclusion proof for the given leaf hash +// and index relative to the tree of the given size and root hash. +function verifyInclusion(hasher, index, size, leafHash, proof, root) { + const calcroot = rootFromInclusionProof(hasher, index, size, leafHash, proof); + return calcroot.equals(root); +} +exports.verifyInclusion = verifyInclusion; +// Calculates the expected root hash for a tree of the given size, provided a +// leaf index and hash with corresponding inclusion proof. +function rootFromInclusionProof(hasher, index, size, leafHash, proof) { + if (index >= size) { + throw new Error('index exceeds size of tree'); + } + if (leafHash.length !== hasher.size()) { + throw new Error('leafHash has unexpected size'); + } + const { inner, border } = decompInclProof(index, size); + if (proof.length != inner + border) { + throw new Error('invalid proof length'); + } + let hash = chainInner(hasher, leafHash, proof.slice(0, inner), index); + hash = chainBorderRight(hasher, hash, proof.slice(inner)); + return hash; +} +// Breaks down inclusion proof for a leaf at the specified index in a tree of +// the specified size. The split point is where paths to the index leaf and +// the (size - 1) leaf diverge. Returns lengths of the bottom and upper proof +// parts. +function decompInclProof(index, size) { + const inner = innerProofSize(index, size); + const border = onesCount(index >> BigInt(inner)); + return { inner, border }; +} +// Computes a subtree hash for an node on or below the tree's right border. +// Assumes the provided proof hashes are ordered from lower to higher levels +// and seed is the initial hash of the node specified by the index. +function chainInner(hasher, seed, proof, index) { + return proof.reduce((acc, h, i) => { + if ((index >> BigInt(i)) & BigInt(1)) { + return hasher.hashChildren(h, acc); + } + else { + return hasher.hashChildren(acc, h); + } + }, seed); +} +// Computes a subtree hash for nodes along the tree's right border. +function chainBorderRight(hasher, seed, proof) { + return proof.reduce((acc, h) => hasher.hashChildren(h, acc), seed); +} +function innerProofSize(index, size) { + return (index ^ (size - BigInt(1))).toString(2).length; +} +// Counts the number of ones in the binary representation of the given number. +// https://en.wikipedia.org/wiki/Hamming_weight +function onesCount(x) { + return x.toString(2).split('1').length - 1; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/sign.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/sign.d.ts new file mode 100644 index 0000000..7d8b4f0 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/sign.d.ts @@ -0,0 +1,23 @@ +/// +import { CA } from './ca'; +import { Provider } from './identity'; +import { TLog } from './tlog'; +import { SignerFunc } from './types/signature'; +import { Bundle } from './types/sigstore'; +export interface SignOptions { + ca: CA; + tlog: TLog; + identityProviders: Provider[]; + signer?: SignerFunc; +} +export declare class Signer { + private ca; + private tlog; + private signer; + private identityProviders; + constructor(options: SignOptions); + signBlob(payload: Buffer): Promise; + signAttestation(payload: Buffer, payloadType: string): Promise; + private signWithEphemeralKey; + private getIdentityToken; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/sign.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/sign.js new file mode 100644 index 0000000..97c3da0 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/sign.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Signer = void 0; +const util_1 = require("./util"); +class Signer { + constructor(options) { + this.identityProviders = []; + this.ca = options.ca; + this.tlog = options.tlog; + this.identityProviders = options.identityProviders; + this.signer = options.signer || this.signWithEphemeralKey.bind(this); + } + async signBlob(payload) { + // Get signature and verification material for payload + const sigMaterial = await this.signer(payload); + // Calculate artifact digest + const digest = util_1.crypto.hash(payload); + // Create Rekor entry + return this.tlog.createMessageSignatureEntry(digest, sigMaterial); + } + async signAttestation(payload, payloadType) { + // Pre-authentication encoding to be signed + const paeBuffer = util_1.dsse.preAuthEncoding(payloadType, payload); + // Get signature and verification material for pae + const sigMaterial = await this.signer(paeBuffer); + const envelope = { + payloadType, + payload: payload, + signatures: [ + { + keyid: sigMaterial.key?.id || '', + sig: sigMaterial.signature, + }, + ], + }; + return this.tlog.createDSSEEntry(envelope, sigMaterial); + } + async signWithEphemeralKey(payload) { + // Create emphemeral key pair + const keypair = util_1.crypto.generateKeyPair(); + // Retrieve identity token from one of the supplied identity providers + const identityToken = await this.getIdentityToken(); + // Extract challenge claim from OIDC token + const subject = util_1.oidc.extractJWTSubject(identityToken); + // Construct challenge value by encrypting subject with private key + const challenge = util_1.crypto.signBlob(Buffer.from(subject), keypair.privateKey); + // Create signing certificate + const certificates = await this.ca.createSigningCertificate(identityToken, keypair.publicKey, challenge); + // Generate artifact signature + const signature = util_1.crypto.signBlob(payload, keypair.privateKey); + return { + signature, + certificates, + key: undefined, + }; + } + async getIdentityToken() { + const aggErrs = []; + for (const provider of this.identityProviders) { + try { + const token = await provider.getToken(); + if (token) { + return token; + } + } + catch (err) { + aggErrs.push(err); + } + } + throw new Error(`Identity token providers failed: ${aggErrs}`); + } +} +exports.Signer = Signer; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore-utils.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore-utils.d.ts new file mode 100644 index 0000000..e3e3fd4 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore-utils.d.ts @@ -0,0 +1,7 @@ +/// +import { Bundle, Envelope, SignOptions } from './sigstore'; +import { SignerFunc } from './types/signature'; +export declare function createDSSEEnvelope(payload: Buffer, payloadType: string, options: { + signer: SignerFunc; +}): Promise; +export declare function createRekorEntry(dsseEnvelope: Envelope, publicKey: string, options?: SignOptions): Promise; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore-utils.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore-utils.js new file mode 100644 index 0000000..f11cf8c --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore-utils.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createRekorEntry = exports.createDSSEEnvelope = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const sigstore_1 = require("./sigstore"); +const tlog_1 = require("./tlog"); +const signature_1 = require("./types/signature"); +const sigstore_2 = require("./types/sigstore"); +const util_1 = require("./util"); +function createTLogClient(options) { + return new tlog_1.TLogClient({ + rekorBaseURL: options.rekorURL || sigstore_1.DEFAULT_REKOR_URL, + }); +} +async function createDSSEEnvelope(payload, payloadType, options) { + // Pre-authentication encoding to be signed + const paeBuffer = util_1.dsse.preAuthEncoding(payloadType, payload); + // Get signature and verification material for pae + const sigMaterial = await options.signer(paeBuffer); + const envelope = { + payloadType, + payload, + signatures: [ + { + keyid: sigMaterial.key?.id || '', + sig: sigMaterial.signature, + }, + ], + }; + return (0, sigstore_2.envelopeToJSON)(envelope); +} +exports.createDSSEEnvelope = createDSSEEnvelope; +// Accepts a signed DSSE envelope and a PEM-encoded public key to be added to the +// transparency log. Returns a Sigstore bundle suitable for offline verification. +async function createRekorEntry(dsseEnvelope, publicKey, options = {}) { + const envelope = (0, sigstore_2.envelopeFromJSON)(dsseEnvelope); + const tlog = createTLogClient(options); + const sigMaterial = (0, signature_1.extractSignatureMaterial)(envelope, publicKey); + const bundle = await tlog.createDSSEEntry(envelope, sigMaterial, { + fetchOnConflict: true, + }); + return (0, sigstore_2.bundleToJSON)(bundle); +} +exports.createRekorEntry = createRekorEntry; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore.d.ts new file mode 100644 index 0000000..bb30343 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore.d.ts @@ -0,0 +1,30 @@ +/// +import * as sigstore from './types/sigstore'; +import { KeySelector } from './verify'; +export * as utils from './sigstore-utils'; +export { SerializedBundle as Bundle, SerializedEnvelope as Envelope, } from './types/sigstore'; +export declare const DEFAULT_FULCIO_URL = "https://fulcio.sigstore.dev"; +export declare const DEFAULT_REKOR_URL = "https://rekor.sigstore.dev"; +interface TLogOptions { + rekorURL?: string; +} +export type SignOptions = { + fulcioURL?: string; + identityToken?: string; + oidcIssuer?: string; + oidcClientID?: string; + oidcClientSecret?: string; +} & TLogOptions; +export type VerifyOptions = { + ctLogThreshold?: number; + tlogThreshold?: number; + certificateIssuer?: string; + certificateIdentityEmail?: string; + certificateIdentityURI?: string; + certificateOIDs?: Record; + keySelector?: KeySelector; +} & TLogOptions; +type Bundle = sigstore.SerializedBundle; +export declare function sign(payload: Buffer, options?: SignOptions): Promise; +export declare function attest(payload: Buffer, payloadType: string, options?: SignOptions): Promise; +export declare function verify(bundle: Bundle, payload?: Buffer, options?: VerifyOptions): Promise; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore.js new file mode 100644 index 0000000..ef8fb20 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/sigstore.js @@ -0,0 +1,188 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verify = exports.attest = exports.sign = exports.DEFAULT_REKOR_URL = exports.DEFAULT_FULCIO_URL = exports.utils = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const fs_1 = __importDefault(require("fs")); +const os_1 = __importDefault(require("os")); +const path_1 = __importDefault(require("path")); +const ca_1 = require("./ca"); +const identity_1 = __importDefault(require("./identity")); +const sign_1 = require("./sign"); +const tlog_1 = require("./tlog"); +const tuf = __importStar(require("./tuf")); +const sigstore = __importStar(require("./types/sigstore")); +const verify_1 = require("./verify"); +exports.utils = __importStar(require("./sigstore-utils")); +exports.DEFAULT_FULCIO_URL = 'https://fulcio.sigstore.dev'; +exports.DEFAULT_REKOR_URL = 'https://rekor.sigstore.dev'; +function createCAClient(options) { + return new ca_1.CAClient({ + fulcioBaseURL: options.fulcioURL || exports.DEFAULT_FULCIO_URL, + }); +} +function createTLogClient(options) { + return new tlog_1.TLogClient({ + rekorBaseURL: options.rekorURL || exports.DEFAULT_REKOR_URL, + }); +} +async function sign(payload, options = {}) { + const ca = createCAClient(options); + const tlog = createTLogClient(options); + const idps = configureIdentityProviders(options); + const signer = new sign_1.Signer({ + ca, + tlog, + identityProviders: idps, + }); + const bundle = await signer.signBlob(payload); + return sigstore.Bundle.toJSON(bundle); +} +exports.sign = sign; +async function attest(payload, payloadType, options = {}) { + const ca = createCAClient(options); + const tlog = createTLogClient(options); + const idps = configureIdentityProviders(options); + const signer = new sign_1.Signer({ + ca, + tlog, + identityProviders: idps, + }); + const bundle = await signer.signAttestation(payload, payloadType); + return sigstore.Bundle.toJSON(bundle); +} +exports.attest = attest; +async function verify(bundle, payload, options = {}) { + const cacheDir = defaultCacheDir(); + const trustedRoot = await tuf.getTrustedRoot(cacheDir); + const verifier = new verify_1.Verifier(trustedRoot, options.keySelector); + const deserializedBundle = sigstore.bundleFromJSON(bundle); + const opts = collectArtifactVerificationOptions(options); + return verifier.verify(deserializedBundle, opts, payload); +} +exports.verify = verify; +// Translates the IdenityProviderOptions into a list of Providers which +// should be queried to retrieve an identity token. +function configureIdentityProviders(options) { + const idps = []; + const token = options.identityToken; + // If an explicit identity token is provided, use that. Setup a dummy + // provider that just returns the token. Otherwise, setup the CI context + // provider and (optionally) the OAuth provider. + if (token) { + idps.push({ getToken: () => Promise.resolve(token) }); + } + else { + idps.push(identity_1.default.ciContextProvider()); + if (options.oidcIssuer && options.oidcClientID) { + idps.push(identity_1.default.oauthProvider(options.oidcIssuer, options.oidcClientID, options.oidcClientSecret)); + } + } + return idps; +} +function defaultCacheDir() { + let cacheRootDir = os_1.default.homedir(); + try { + fs_1.default.accessSync(os_1.default.homedir(), fs_1.default.constants.W_OK | fs_1.default.constants.R_OK); + } + catch (e) { + cacheRootDir = os_1.default.tmpdir(); + } + return path_1.default.join(cacheRootDir, '.sigstore', 'js-root'); +} +// Assembles the AtifactVerificationOptions from the supplied VerifyOptions. +function collectArtifactVerificationOptions(options) { + // The trusted signers are only used if the options contain a certificate + // issuer + let signers; + if (options.certificateIssuer) { + let san = undefined; + if (options.certificateIdentityEmail) { + san = { + type: sigstore.SubjectAlternativeNameType.EMAIL, + identity: { + $case: 'value', + value: options.certificateIdentityEmail, + }, + }; + } + else if (options.certificateIdentityURI) { + san = { + type: sigstore.SubjectAlternativeNameType.URI, + identity: { + $case: 'value', + value: options.certificateIdentityURI, + }, + }; + } + const oids = Object.entries(options.certificateOIDs || {}).map(([oid, value]) => ({ + oid: { id: oid.split('.').map((s) => parseInt(s, 10)) }, + value: Buffer.from(value), + })); + signers = { + $case: 'certificateIdentities', + certificateIdentities: { + identities: [ + { + issuer: options.certificateIssuer, + san: san, + oids: oids, + }, + ], + }, + }; + } + // Construct the artifact verification options w/ defaults + return { + ctlogOptions: { + disable: false, + threshold: options.ctLogThreshold || 1, + detachedSct: false, + }, + tlogOptions: { + disable: false, + threshold: options.tlogThreshold || 1, + performOnlineVerification: false, + }, + signers, + }; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/format.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/format.d.ts new file mode 100644 index 0000000..92251b3 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/format.d.ts @@ -0,0 +1,6 @@ +/// +import { SignatureMaterial } from '../types/signature'; +import { Envelope } from '../types/sigstore'; +import { HashedRekordKind, IntotoKind } from './types'; +export declare function toProposedHashedRekordEntry(digest: Buffer, signature: SignatureMaterial): HashedRekordKind; +export declare function toProposedIntotoEntry(envelope: Envelope, signature: SignatureMaterial, apiVersion?: string): IntotoKind; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/format.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/format.js new file mode 100644 index 0000000..6707709 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/format.js @@ -0,0 +1,105 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toProposedIntotoEntry = exports.toProposedHashedRekordEntry = void 0; +const util_1 = require("../util"); +const types_1 = require("./types"); +const DEFAULT_HASHEDREKORD_API_VERSION = '0.0.1'; +const DEFAULT_INTOTO_API_VERSION = '0.0.2'; +// Returns a properly formatted Rekor "hashedrekord" entry for the given digest +// and signature +function toProposedHashedRekordEntry(digest, signature) { + const hexDigest = digest.toString('hex'); + const b64Signature = signature.signature.toString('base64'); + const b64Key = util_1.encoding.base64Encode(toPublicKey(signature)); + return { + apiVersion: DEFAULT_HASHEDREKORD_API_VERSION, + kind: types_1.HASHEDREKORD_KIND, + spec: { + data: { + hash: { + algorithm: 'sha256', + value: hexDigest, + }, + }, + signature: { + content: b64Signature, + publicKey: { + content: b64Key, + }, + }, + }, + }; +} +exports.toProposedHashedRekordEntry = toProposedHashedRekordEntry; +// Returns a properly formatted Rekor "intoto" entry for the given DSSE +// envelope and signature +function toProposedIntotoEntry(envelope, signature, apiVersion = DEFAULT_INTOTO_API_VERSION) { + switch (apiVersion) { + case '0.0.2': + return toProposedIntotoV002Entry(envelope, signature); + default: + throw new Error(`Unsupported intoto kind API version: ${apiVersion}`); + } +} +exports.toProposedIntotoEntry = toProposedIntotoEntry; +function toProposedIntotoV002Entry(envelope, signature) { + // Calculate the value for the payloadHash field in the Rekor entry + const payloadHash = util_1.crypto.hash(envelope.payload).toString('hex'); + // Calculate the value for the hash field in the Rekor entry + const envelopeHash = calculateDSSEHash(envelope); + // Collect values for re-creating the DSSE envelope. + // Double-encode payload and signature cause that's what Rekor expects + const payload = util_1.encoding.base64Encode(envelope.payload.toString('base64')); + const sig = util_1.encoding.base64Encode(envelope.signatures[0].sig.toString('base64')); + const keyid = envelope.signatures[0].keyid; + const publicKey = util_1.encoding.base64Encode(toPublicKey(signature)); + // Create the envelope portion of the entry. Note the inclusion of the + // publicKey in the signature struct is not a standard part of a DSSE + // envelope, but is required by Rekor. + const dsse = { + payloadType: envelope.payloadType, + payload: payload, + signatures: [{ sig, publicKey }], + }; + // If the keyid is an empty string, Rekor seems to remove it altogether. We + // need to do the same here so that we can properly recreate the entry for + // verification. + if (keyid.length > 0) { + dsse.signatures[0].keyid = keyid; + } + return { + apiVersion: '0.0.2', + kind: types_1.INTOTO_KIND, + spec: { + content: { + envelope: dsse, + hash: { algorithm: 'sha256', value: envelopeHash }, + payloadHash: { algorithm: 'sha256', value: payloadHash }, + }, + }, + }; +} +// Calculates the hash of a DSSE envelope for inclusion in a Rekor entry. +// There is no standard way to do this, so the scheme we're using as as +// follows: +// * payload is base64 encoded +// * signature is base64 encoded (only the first signature is used) +// * keyid is included ONLY if it is NOT an empty string +// * The resulting JSON is canonicalized and hashed to a hex string +function calculateDSSEHash(envelope) { + const dsse = { + payloadType: envelope.payloadType, + payload: envelope.payload.toString('base64'), + signatures: [{ sig: envelope.signatures[0].sig.toString('base64') }], + }; + // If the keyid is an empty string, Rekor seems to remove it altogether. + if (envelope.signatures[0].keyid.length > 0) { + dsse.signatures[0].keyid = envelope.signatures[0].keyid; + } + return util_1.crypto.hash(util_1.json.canonicalize(dsse)).toString('hex'); +} +function toPublicKey(signature) { + return signature.certificates + ? signature.certificates[0] + : signature.key.value; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/index.d.ts new file mode 100644 index 0000000..9d9cc77 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/index.d.ts @@ -0,0 +1,21 @@ +/// +import { SignatureMaterial } from '../types/signature'; +import { Bundle, Envelope } from '../types/sigstore'; +interface CreateEntryOptions { + fetchOnConflict?: boolean; +} +export { Entry, EntryKind, HashedRekordKind } from './types'; +export interface TLog { + createMessageSignatureEntry: (digest: Buffer, sigMaterial: SignatureMaterial) => Promise; + createDSSEEntry: (envelope: Envelope, sigMaterial: SignatureMaterial, options?: CreateEntryOptions) => Promise; +} +export interface TLogClientOptions { + rekorBaseURL: string; +} +export declare class TLogClient implements TLog { + private rekor; + constructor(options: TLogClientOptions); + createMessageSignatureEntry(digest: Buffer, sigMaterial: SignatureMaterial, options?: CreateEntryOptions): Promise; + createDSSEEntry(envelope: Envelope, sigMaterial: SignatureMaterial, options?: CreateEntryOptions): Promise; + private createEntry; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/index.js new file mode 100644 index 0000000..c273480 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/index.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TLogClient = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const client_1 = require("../client"); +const error_1 = require("../client/error"); +const error_2 = require("../error"); +const sigstore_1 = require("../types/sigstore"); +const format_1 = require("./format"); +class TLogClient { + constructor(options) { + this.rekor = new client_1.Rekor({ baseURL: options.rekorBaseURL }); + } + async createMessageSignatureEntry(digest, sigMaterial, options = {}) { + const proposedEntry = (0, format_1.toProposedHashedRekordEntry)(digest, sigMaterial); + const entry = await this.createEntry(proposedEntry, options.fetchOnConflict); + return sigstore_1.bundle.toMessageSignatureBundle(digest, sigMaterial, entry); + } + async createDSSEEntry(envelope, sigMaterial, options = {}) { + const proposedEntry = (0, format_1.toProposedIntotoEntry)(envelope, sigMaterial); + const entry = await this.createEntry(proposedEntry, options.fetchOnConflict); + return sigstore_1.bundle.toDSSEBundle(envelope, sigMaterial, entry); + } + async createEntry(proposedEntry, fetchOnConflict = false) { + let entry; + try { + entry = await this.rekor.createEntry(proposedEntry); + } + catch (err) { + // If the entry already exists, fetch it (if enabled) + if (entryExistsError(err) && fetchOnConflict) { + // Grab the UUID of the existing entry from the location header + const uuid = err.location.split('/').pop() || ''; + try { + entry = await this.rekor.getEntry(uuid); + } + catch (err) { + throw new error_2.InternalError('error fetching tlog entry', err); + } + } + else { + throw new error_2.InternalError('error creating tlog entry', err); + } + } + return entry; + } +} +exports.TLogClient = TLogClient; +function entryExistsError(value) { + return (value instanceof error_1.HTTPError && + value.statusCode === 409 && + value.location !== undefined); +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/hashedrekord.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/hashedrekord.d.ts new file mode 100644 index 0000000..bfe4e83 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/hashedrekord.d.ts @@ -0,0 +1,50 @@ +/** + * This file was automatically generated by json-schema-to-typescript. + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, + * and run json-schema-to-typescript to regenerate this file. + */ +/** + * Schema for Rekord objects + */ +export type RekorSchema = HashedRekorV001Schema; +/** + * Schema for Hashed Rekord object + */ +export interface HashedRekorV001Schema { + /** + * Information about the detached signature associated with the entry + */ + signature: { + /** + * Specifies the content of the signature inline within the document + */ + content?: string; + /** + * The public key that can verify the signature; this can also be an X509 code signing certificate that contains the raw public key information + */ + publicKey?: { + /** + * Specifies the content of the public key or code signing certificate inline within the document + */ + content?: string; + }; + }; + /** + * Information about the content associated with the entry + */ + data: { + /** + * Specifies the hash algorithm and value for the content + */ + hash?: { + /** + * The hashing function used to compute the hash value + */ + algorithm: "sha256"; + /** + * The hash value for the content + */ + value: string; + }; + }; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/hashedrekord.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/hashedrekord.js new file mode 100644 index 0000000..5383a37 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/hashedrekord.js @@ -0,0 +1,8 @@ +"use strict"; +/* tslint:disable */ +/** + * This file was automatically generated by json-schema-to-typescript. + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, + * and run json-schema-to-typescript to regenerate this file. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/intoto.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/intoto.d.ts new file mode 100644 index 0000000..c60c7e0 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/intoto.d.ts @@ -0,0 +1,131 @@ +/** + * This file was automatically generated by json-schema-to-typescript. + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, + * and run json-schema-to-typescript to regenerate this file. + */ +/** + * Intoto for Rekord objects + */ +export type IntotoSchema = IntotoV001Schema | IntotoV002Schema; +/** + * Schema for intoto object + */ +export interface IntotoV001Schema { + content: { + /** + * envelope + */ + envelope?: string; + /** + * Specifies the hash algorithm and value encompassing the entire signed envelope + */ + hash?: { + /** + * The hashing function used to compute the hash value + */ + algorithm: "sha256"; + /** + * The hash value for the archive + */ + value: string; + }; + /** + * Specifies the hash algorithm and value covering the payload within the DSSE envelope + */ + payloadHash?: { + /** + * The hashing function used to compute the hash value + */ + algorithm: "sha256"; + /** + * The hash value for the envelope's payload + */ + value: string; + }; + }; + /** + * The public key that can verify the signature + */ + publicKey: string; +} +/** + * Schema for intoto object + */ +export interface IntotoV002Schema { + content: { + /** + * dsse envelope + */ + envelope?: { + /** + * payload of the envelope + */ + payload?: string; + /** + * type describing the payload + */ + payloadType: string; + /** + * collection of all signatures of the envelope's payload + * + * @minItems 1 + */ + signatures: [ + { + /** + * optional id of the key used to create the signature + */ + keyid?: string; + /** + * signature of the payload + */ + sig?: string; + /** + * public key that corresponds to this signature + */ + publicKey?: string; + }, + ...{ + /** + * optional id of the key used to create the signature + */ + keyid?: string; + /** + * signature of the payload + */ + sig?: string; + /** + * public key that corresponds to this signature + */ + publicKey?: string; + }[] + ]; + }; + /** + * Specifies the hash algorithm and value encompassing the entire signed envelope + */ + hash?: { + /** + * The hashing function used to compute the hash value + */ + algorithm: "sha256"; + /** + * The hash value for the archive + */ + value: string; + }; + /** + * Specifies the hash algorithm and value covering the payload within the DSSE envelope + */ + payloadHash?: { + /** + * The hashing function used to compute the hash value + */ + algorithm: "sha256"; + /** + * The hash value of the payload + */ + value: string; + }; + }; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/intoto.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/intoto.js new file mode 100644 index 0000000..5383a37 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/__generated__/intoto.js @@ -0,0 +1,8 @@ +"use strict"; +/* tslint:disable */ +/** + * This file was automatically generated by json-schema-to-typescript. + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, + * and run json-schema-to-typescript to regenerate this file. + */ +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/index.d.ts new file mode 100644 index 0000000..06be133 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/index.d.ts @@ -0,0 +1,38 @@ +import { HashedRekorV001Schema } from './__generated__/hashedrekord'; +import { IntotoV001Schema, IntotoV002Schema } from './__generated__/intoto'; +export declare const INTOTO_KIND = "intoto"; +export declare const HASHEDREKORD_KIND = "hashedrekord"; +export type HashedRekordKind = { + apiVersion: '0.0.1'; + kind: typeof HASHEDREKORD_KIND; + spec: HashedRekorV001Schema; +}; +export type IntotoKind = { + apiVersion: '0.0.1'; + kind: typeof INTOTO_KIND; + spec: IntotoV001Schema; +} | { + apiVersion: '0.0.2'; + kind: typeof INTOTO_KIND; + spec: IntotoV002Schema; +}; +export type EntryKind = HashedRekordKind | IntotoKind; +export interface Entry { + uuid: string; + body: string; + integratedTime: number; + logID: string; + logIndex: number; + verification: EntryVerification; + attestation?: object; +} +export interface EntryVerification { + inclusionProof: InclusionProof; + signedEntryTimestamp: string; +} +export interface InclusionProof { + hashes: string[]; + logIndex: number; + rootHash: string; + treeSize: number; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/index.js new file mode 100644 index 0000000..d6394a9 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/types/index.js @@ -0,0 +1,5 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HASHEDREKORD_KIND = exports.INTOTO_KIND = void 0; +exports.INTOTO_KIND = 'intoto'; +exports.HASHEDREKORD_KIND = 'hashedrekord'; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/body.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/body.d.ts new file mode 100644 index 0000000..17de4f5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/body.d.ts @@ -0,0 +1,2 @@ +import * as sigstore from '../../types/sigstore'; +export declare function verifyTLogBody(entry: sigstore.VerifiableTransparencyLogEntry, bundleContent: sigstore.Bundle['content']): boolean; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/body.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/body.js new file mode 100644 index 0000000..086e068 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/body.js @@ -0,0 +1,113 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifyTLogBody = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = require("../../error"); +const util_1 = require("../../util"); +const TLOG_MISMATCH_ERROR_MSG = 'bundle content and tlog entry do not match'; +// Compare the given tlog entry to the given bundle +function verifyTLogBody(entry, bundleContent) { + const { kind, version } = entry.kindVersion; + const body = JSON.parse(entry.canonicalizedBody.toString('utf8')); + try { + if (kind !== body.kind || version !== body.apiVersion) { + throw new error_1.VerificationError(TLOG_MISMATCH_ERROR_MSG); + } + switch (body.kind) { + case 'intoto': + verifyIntotoTLogBody(body, bundleContent); + break; + case 'hashedrekord': + verifyHashedRekordTLogBody(body, bundleContent); + break; + default: + throw new error_1.VerificationError(`unsupported kind in tlog entry: ${kind}`); + } + return true; + } + catch (e) { + return false; + } +} +exports.verifyTLogBody = verifyTLogBody; +// Compare the given intoto tlog entry to the given bundle +function verifyIntotoTLogBody(tlogEntry, content) { + if (content?.$case !== 'dsseEnvelope') { + throw new error_1.VerificationError(`unsupported bundle content: ${content?.$case || 'unknown'}`); + } + const dsse = content.dsseEnvelope; + switch (tlogEntry.apiVersion) { + case '0.0.2': + verifyIntoto002TLogBody(tlogEntry, dsse); + break; + default: + throw new error_1.VerificationError(`unsupported intoto version: ${tlogEntry.apiVersion}`); + } +} +// Compare the given hashedrekord tlog entry to the given bundle +function verifyHashedRekordTLogBody(tlogEntry, content) { + if (content?.$case !== 'messageSignature') { + throw new error_1.VerificationError(`unsupported bundle content: ${content?.$case || 'unknown'}`); + } + const messageSignature = content.messageSignature; + switch (tlogEntry.apiVersion) { + case '0.0.1': + verifyHashedrekor001TLogBody(tlogEntry, messageSignature); + break; + default: + throw new error_1.VerificationError(`unsupported hashedrekord version: ${tlogEntry.apiVersion}`); + } +} +// Compare the given intoto v0.0.2 tlog entry to the given DSSE envelope. +function verifyIntoto002TLogBody(tlogEntry, dsse) { + // Collect all of the signatures from the DSSE envelope + // Turns them into base64-encoded strings for comparison + const dsseSigs = dsse.signatures.map((signature) => signature.sig.toString('base64')); + // Collect all of the signatures from the tlog entry + // Remember that tlog signastures are double base64-encoded + const tlogSigs = tlogEntry.spec.content.envelope?.signatures.map((signature) => (signature.sig ? util_1.encoding.base64Decode(signature.sig) : '')); + // Ensure the bundle's DSSE and the tlog entry contain the same number of signatures + if (dsseSigs.length !== tlogSigs?.length) { + throw new error_1.VerificationError(TLOG_MISMATCH_ERROR_MSG); + } + // Ensure that every signature in the bundle's DSSE is present in the tlog entry + if (!dsseSigs.every((dsseSig) => tlogSigs.includes(dsseSig))) { + throw new error_1.VerificationError(TLOG_MISMATCH_ERROR_MSG); + } + // Ensure the digest of the bundle's DSSE payload matches the digest in the + // tlog entry + const dssePayloadHash = util_1.crypto.hash(dsse.payload).toString('hex'); + if (dssePayloadHash !== tlogEntry.spec.content.payloadHash?.value) { + throw new error_1.VerificationError(TLOG_MISMATCH_ERROR_MSG); + } +} +// Compare the given hashedrekord v0.0.1 tlog entry to the given message +// signature +function verifyHashedrekor001TLogBody(tlogEntry, messageSignature) { + // Ensure that the bundles message signature matches the tlog entry + const msgSig = messageSignature.signature.toString('base64'); + const tlogSig = tlogEntry.spec.signature.content; + if (msgSig !== tlogSig) { + throw new error_1.VerificationError(TLOG_MISMATCH_ERROR_MSG); + } + // Ensure that the bundle's message digest matches the tlog entry + const msgDigest = messageSignature.messageDigest?.digest.toString('hex'); + const tlogDigest = tlogEntry.spec.data.hash?.value; + if (msgDigest !== tlogDigest) { + throw new error_1.VerificationError(TLOG_MISMATCH_ERROR_MSG); + } +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/index.d.ts new file mode 100644 index 0000000..8ab4276 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/index.d.ts @@ -0,0 +1,2 @@ +import * as sigstore from '../../types/sigstore'; +export declare function verifyTLogEntries(bundle: sigstore.BundleWithVerificationMaterial, trustedRoot: sigstore.TrustedRoot, options: sigstore.ArtifactVerificationOptions_TlogOptions): void; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/index.js new file mode 100644 index 0000000..ad655b6 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/index.js @@ -0,0 +1,75 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifyTLogEntries = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = require("../../error"); +const sigstore = __importStar(require("../../types/sigstore")); +const body_1 = require("./body"); +const set_1 = require("./set"); +// Verifies that the number of tlog entries that pass offline verification +// is greater than or equal to the threshold specified in the options. +function verifyTLogEntries(bundle, trustedRoot, options) { + if (options.performOnlineVerification) { + throw new error_1.VerificationError('Online verification not implemented'); + } + // Extract the signing cert, if available + const signingCert = sigstore.signingCertificate(bundle); + // Iterate over the tlog entries and verify each one + const verifiedEntries = bundle.verificationMaterial.tlogEntries.filter((entry) => verifyTLogEntryOffline(entry, bundle.content, trustedRoot.tlogs, signingCert)); + if (verifiedEntries.length < options.threshold) { + throw new error_1.VerificationError('tlog verification failed'); + } +} +exports.verifyTLogEntries = verifyTLogEntries; +function verifyTLogEntryOffline(entry, bundleContent, tlogs, signingCert) { + // Check that the TLog entry has the fields necessary for verification + if (!sigstore.isVerifiableTransparencyLogEntry(entry)) { + return false; + } + // If there is a signing certificate availble, check that the tlog integrated + // time is within the certificate's validity period; otherwise, skip this + // check. + const verifyTLogIntegrationTime = signingCert + ? () => signingCert.validForDate(new Date(Number(entry.integratedTime) * 1000)) + : () => true; + return ((0, body_1.verifyTLogBody)(entry, bundleContent) && + (0, set_1.verifyTLogSET)(entry, tlogs) && + verifyTLogIntegrationTime()); +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/set.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/set.d.ts new file mode 100644 index 0000000..2783174 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/set.d.ts @@ -0,0 +1,2 @@ +import * as sigstore from '../../types/sigstore'; +export declare function verifyTLogSET(entry: sigstore.VerifiableTransparencyLogEntry, tlogs: sigstore.TransparencyLogInstance[]): boolean; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/set.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/set.js new file mode 100644 index 0000000..89a5442 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tlog/verify/set.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifyTLogSET = void 0; +const util_1 = require("../../util"); +// Verifies the SET for the given entry against the list of trusted +// transparency logs. Returns true if the SET can be verified against at least +// one of the trusted logs; otherwise, returns false. +function verifyTLogSET(entry, tlogs) { + // Filter the list of tlog instances to only those which might be able to + // verify the SET + const validTLogs = filterTLogInstances(tlogs, entry.logId.keyId, entry.integratedTime); + // Check to see if we can verify the SET against any of the valid tlogs + return validTLogs.some((tlog) => { + if (!tlog.publicKey?.rawBytes) { + return false; + } + const publicKey = util_1.crypto.createPublicKey(tlog.publicKey.rawBytes); + // Re-create the original Rekor verification payload + const payload = toVerificationPayload(entry); + // Canonicalize the payload and turn into a buffer for verification + const data = Buffer.from(util_1.json.canonicalize(payload), 'utf8'); + // Extract the SET from the tlog entry + const signature = entry.inclusionPromise.signedEntryTimestamp; + return util_1.crypto.verifyBlob(data, publicKey, signature); + }); +} +exports.verifyTLogSET = verifyTLogSET; +// Returns a properly formatted "VerificationPayload" for one of the +// transaction log entires in the given bundle which can be used for SET +// verification. +function toVerificationPayload(entry) { + const { integratedTime, logIndex, logId, canonicalizedBody } = entry; + return { + body: canonicalizedBody.toString('base64'), + integratedTime: Number(integratedTime), + logIndex: Number(logIndex), + logID: logId.keyId.toString('hex'), + }; +} +// Filter the list of tlog instances to only those which match the given log +// ID and have public keys which are valid for the given integrated time. +function filterTLogInstances(tlogInstances, logID, integratedTime) { + const targetDate = new Date(Number(integratedTime) * 1000); + return tlogInstances.filter((tlog) => { + // If the log IDs don't match, we can't use this tlog + if (!tlog.logId?.keyId.equals(logID)) { + return false; + } + // If the tlog doesn't have a public key, we can't use it + const publicKey = tlog.publicKey; + if (publicKey === undefined) { + return false; + } + // If the tlog doesn't have a rawBytes field, we can't use it + if (publicKey.rawBytes === undefined) { + return false; + } + // If the tlog doesn't have a validFor field, we don't need to check it + if (publicKey.validFor === undefined) { + return true; + } + // Check that the integrated time is within the validFor range + return (publicKey.validFor.start && + publicKey.validFor.start <= targetDate && + (!publicKey.validFor.end || targetDate <= publicKey.validFor.end)); + }); +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/index.d.ts new file mode 100644 index 0000000..349ff08 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/index.d.ts @@ -0,0 +1,2 @@ +import * as sigstore from '../types/sigstore'; +export declare function getTrustedRoot(cacheDir: string): Promise; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/index.js new file mode 100644 index 0000000..1aea238 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/index.js @@ -0,0 +1,76 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getTrustedRoot = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const fs_1 = __importDefault(require("fs")); +const path_1 = __importDefault(require("path")); +const tuf_js_1 = require("tuf-js"); +const trustroot_1 = require("./trustroot"); +async function getTrustedRoot(cacheDir) { + initTufCache(cacheDir); + const repoMap = initRepoMap(cacheDir); + const repoClients = Object.entries(repoMap.repositories).map(([name, urls]) => initClient(name, urls[0], cacheDir)); + // TODO: Add support for multiple repositories. For now, we just use the first + // one (the production Sigstore TUF repository). + const fetcher = new trustroot_1.TrustedRootFetcher(repoClients[0]); + return fetcher.getTrustedRoot(); +} +exports.getTrustedRoot = getTrustedRoot; +// Initializes the root TUF cache directory +function initTufCache(cacheDir) { + if (!fs_1.default.existsSync(cacheDir)) { + fs_1.default.mkdirSync(cacheDir, { recursive: true }); + } +} +// Initializes the repo map (copying it to the cache root dir) and returns the +// content of the repository map. +function initRepoMap(rootDir) { + const mapDest = path_1.default.join(rootDir, 'map.json'); + if (!fs_1.default.existsSync(mapDest)) { + const mapSrc = require.resolve('../../store/map.json'); + fs_1.default.copyFileSync(mapSrc, mapDest); + } + const buf = fs_1.default.readFileSync(mapDest); + return JSON.parse(buf.toString('utf-8')); +} +function initClient(name, url, rootDir) { + const repoCachePath = path_1.default.join(rootDir, name); + const targetCachePath = path_1.default.join(repoCachePath, 'targets'); + const tufRootDest = path_1.default.join(repoCachePath, 'root.json'); + // Only copy the TUF trusted root if it doesn't already exist. It's possible + // that the cached root has already been updated, so we don't want to roll it + // back. + if (!fs_1.default.existsSync(tufRootDest)) { + const tufRootSrc = require.resolve(`../../store/${name}-root.json`); + fs_1.default.mkdirSync(repoCachePath); + fs_1.default.copyFileSync(tufRootSrc, tufRootDest); + } + if (!fs_1.default.existsSync(targetCachePath)) { + fs_1.default.mkdirSync(targetCachePath); + } + // TODO: Is there some better way to derive the base URL for the targets? + // Hard-coding for now based on current Sigstore TUF repo layout. + return new tuf_js_1.Updater({ + metadataBaseUrl: url, + targetBaseUrl: `${url}/targets`, + metadataDir: repoCachePath, + targetDir: targetCachePath, + }); +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/trustroot.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/trustroot.d.ts new file mode 100644 index 0000000..615fffa --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/trustroot.d.ts @@ -0,0 +1,11 @@ +import { Updater } from 'tuf-js'; +import * as sigstore from '../types/sigstore'; +export declare class TrustedRootFetcher { + private tuf; + constructor(tuf: Updater); + getTrustedRoot(): Promise; + private allTargets; + private getTLogKeys; + private getCAKeys; + private readTargetBytes; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/trustroot.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/trustroot.js new file mode 100644 index 0000000..dcf491c --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/tuf/trustroot.js @@ -0,0 +1,163 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TrustedRootFetcher = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const fs_1 = __importDefault(require("fs")); +const error_1 = require("../error"); +const sigstore = __importStar(require("../types/sigstore")); +const util_1 = require("../util"); +const TRUSTED_ROOT_MEDIA_TYPE = 'application/vnd.dev.sigstore.trustedroot+json;version=0.1'; +// Type guard for SigstoreTargetMetadata +function isTargetMetadata(m) { + return (m !== undefined && + m !== null && + typeof m === 'object' && + 'status' in m && + 'usage' in m && + 'uri' in m); +} +class TrustedRootFetcher { + constructor(tuf) { + this.tuf = tuf; + } + // Assembles a TrustedRoot from the targets in the TUF repo + async getTrustedRoot() { + // Get all available targets + const targets = await this.allTargets(); + const cas = await this.getCAKeys(targets, 'Fulcio'); + const ctlogs = await this.getTLogKeys(targets, 'CTFE'); + const tlogs = await this.getTLogKeys(targets, 'Rekor'); + return { + mediaType: TRUSTED_ROOT_MEDIA_TYPE, + certificateAuthorities: cas, + ctlogs: ctlogs, + tlogs: tlogs, + timestampAuthorities: [], + }; + } + // Retrieves the list of TUF targets. + // NOTE: This is a HACK to get around the fact that the TUF library doesn't + // expose the list of targets. This is a temporary solution until TUF comes up + // with a story for target discovery. + // https://docs.google.com/document/d/1rWHAM2qCUtnjWD4lOrGWE2EIDLoA7eSy4-jB66Wgh0o + async allTargets() { + try { + await this.tuf.refresh(); + } + catch (e) { + throw new error_1.InternalError('error refreshing trust metadata'); + } + return Object.values( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.tuf.trustedSet.targets?.signed.targets || {}); + } + // Filters the supplied list of targets to those with the specified usage + // and returns a new TransparencyLogInstance for each with the associated + // public key populated. + async getTLogKeys(targets, usage) { + const filteredTargets = filterByUsage(targets, usage); + return Promise.all(filteredTargets.map(async (target) => { + const keyBytes = await this.readTargetBytes(target); + const uri = isTargetMetadata(target.custom.sigstore) + ? target.custom.sigstore.uri + : ''; + // The log ID is not present in the Sigstore target metadata, but + // can be derived by hashing the contents of the public key. + return { + baseUrl: uri, + hashAlgorithm: sigstore.HashAlgorithm.SHA2_256, + logId: { keyId: util_1.crypto.hash(keyBytes) }, + publicKey: { + keyDetails: sigstore.PublicKeyDetails.PKIX_ECDSA_P256_SHA_256, + rawBytes: keyBytes, + }, + }; + })); + } + // Filters the supplied list of targets to those with the specified usage + // and returns a new CertificateAuthority populated with all of the associated + // certificates. + // NOTE: The Sigstore target metadata does NOT provide any mechanism to link + // related certificates (e.g. a root and intermediate). As a result, we + // assume that all certificates located here are part of the same chain. + // This works out OK since our certificate chain verification code tries all + // possible permutations of the certificates until it finds one that results + // in a valid, trusted chain. + async getCAKeys(targets, usage) { + const filteredTargets = filterByUsage(targets, usage); + const certs = await Promise.all(filteredTargets.map(async (target) => await this.readTargetBytes(target))); + return [ + { + uri: '', + subject: undefined, + validFor: { start: new Date(0) }, + certChain: { + certificates: certs.map((cert) => ({ rawBytes: cert })), + }, + }, + ]; + } + // Reads the contents of the specified target file as a DER-encoded buffer. + async readTargetBytes(target) { + try { + let path = await this.tuf.findCachedTarget(target); + // An empty path here means the target has not been cached locally, or is + // out of date. In either case, we need to download it. + if (!path) { + path = await this.tuf.downloadTarget(target); + } + const file = fs_1.default.readFileSync(path); + return util_1.pem.toDER(file.toString('utf-8')); + } + catch (err) { + throw new error_1.InternalError(`error reading key/certificate for ${target.path}`); + } + } +} +exports.TrustedRootFetcher = TrustedRootFetcher; +function filterByUsage(targets, usage) { + return targets.filter((target) => { + const meta = target.custom.sigstore; + return isTargetMetadata(meta) && meta.usage === usage; + }); +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/signature.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/signature.d.ts new file mode 100644 index 0000000..40b4fbe --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/signature.d.ts @@ -0,0 +1,16 @@ +/// +import { Envelope } from './sigstore'; +import { OneOf } from './utility'; +interface VerificationMaterial { + certificates: string[]; + key: { + id?: string; + value: string; + }; +} +export type SignatureMaterial = { + signature: Buffer; +} & OneOf; +export type SignerFunc = (payload: Buffer) => Promise; +export declare function extractSignatureMaterial(dsseEnvelope: Envelope, publicKey: string): SignatureMaterial; +export {}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/signature.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/signature.js new file mode 100644 index 0000000..339e2a2 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/signature.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.extractSignatureMaterial = void 0; +function extractSignatureMaterial(dsseEnvelope, publicKey) { + const signature = dsseEnvelope.signatures[0]; + return { + signature: signature.sig, + key: { + id: signature.keyid, + value: publicKey, + }, + certificates: undefined, + }; +} +exports.extractSignatureMaterial = extractSignatureMaterial; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/envelope.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/envelope.d.ts new file mode 100644 index 0000000..81422a0 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/envelope.d.ts @@ -0,0 +1,46 @@ +/// +/** An authenticated message of arbitrary type. */ +export interface Envelope { + /** + * Message to be signed. (In JSON, this is encoded as base64.) + * REQUIRED. + */ + payload: Buffer; + /** + * String unambiguously identifying how to interpret payload. + * REQUIRED. + */ + payloadType: string; + /** + * Signature over: + * PAE(type, body) + * Where PAE is defined as: + * PAE(type, body) = "DSSEv1" + SP + LEN(type) + SP + type + SP + LEN(body) + SP + body + * + = concatenation + * SP = ASCII space [0x20] + * "DSSEv1" = ASCII [0x44, 0x53, 0x53, 0x45, 0x76, 0x31] + * LEN(s) = ASCII decimal encoding of the byte length of s, with no leading zeros + * REQUIRED (length >= 1). + */ + signatures: Signature[]; +} +export interface Signature { + /** + * Signature itself. (In JSON, this is encoded as base64.) + * REQUIRED. + */ + sig: Buffer; + /** + * Unauthenticated* hint identifying which public key was used. + * OPTIONAL. + */ + keyid: string; +} +export declare const Envelope: { + fromJSON(object: any): Envelope; + toJSON(message: Envelope): unknown; +}; +export declare const Signature: { + fromJSON(object: any): Signature; + toJSON(message: Signature): unknown; +}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/envelope.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/envelope.js new file mode 100644 index 0000000..715bb1a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/envelope.js @@ -0,0 +1,89 @@ +"use strict"; +/* eslint-disable */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Signature = exports.Envelope = void 0; +function createBaseEnvelope() { + return { payload: Buffer.alloc(0), payloadType: "", signatures: [] }; +} +exports.Envelope = { + fromJSON(object) { + return { + payload: isSet(object.payload) ? Buffer.from(bytesFromBase64(object.payload)) : Buffer.alloc(0), + payloadType: isSet(object.payloadType) ? String(object.payloadType) : "", + signatures: Array.isArray(object?.signatures) ? object.signatures.map((e) => exports.Signature.fromJSON(e)) : [], + }; + }, + toJSON(message) { + const obj = {}; + message.payload !== undefined && + (obj.payload = base64FromBytes(message.payload !== undefined ? message.payload : Buffer.alloc(0))); + message.payloadType !== undefined && (obj.payloadType = message.payloadType); + if (message.signatures) { + obj.signatures = message.signatures.map((e) => e ? exports.Signature.toJSON(e) : undefined); + } + else { + obj.signatures = []; + } + return obj; + }, +}; +function createBaseSignature() { + return { sig: Buffer.alloc(0), keyid: "" }; +} +exports.Signature = { + fromJSON(object) { + return { + sig: isSet(object.sig) ? Buffer.from(bytesFromBase64(object.sig)) : Buffer.alloc(0), + keyid: isSet(object.keyid) ? String(object.keyid) : "", + }; + }, + toJSON(message) { + const obj = {}; + message.sig !== undefined && (obj.sig = base64FromBytes(message.sig !== undefined ? message.sig : Buffer.alloc(0))); + message.keyid !== undefined && (obj.keyid = message.keyid); + return obj; + }, +}; +var globalThis = (() => { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw "Unable to locate global object"; +})(); +function bytesFromBase64(b64) { + if (globalThis.Buffer) { + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); + } + else { + const bin = globalThis.atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; ++i) { + arr[i] = bin.charCodeAt(i); + } + return arr; + } +} +function base64FromBytes(arr) { + if (globalThis.Buffer) { + return globalThis.Buffer.from(arr).toString("base64"); + } + else { + const bin = []; + arr.forEach((byte) => { + bin.push(String.fromCharCode(byte)); + }); + return globalThis.btoa(bin.join("")); + } +} +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/api/field_behavior.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/api/field_behavior.d.ts new file mode 100644 index 0000000..1b4ed47 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/api/field_behavior.d.ts @@ -0,0 +1,52 @@ +/** + * An indicator of the behavior of a given field (for example, that a field + * is required in requests, or given as output but ignored as input). + * This **does not** change the behavior in protocol buffers itself; it only + * denotes the behavior and may affect how API tooling handles the field. + * + * Note: This enum **may** receive new values in the future. + */ +export declare enum FieldBehavior { + /** FIELD_BEHAVIOR_UNSPECIFIED - Conventional default for enums. Do not use this. */ + FIELD_BEHAVIOR_UNSPECIFIED = 0, + /** + * OPTIONAL - Specifically denotes a field as optional. + * While all fields in protocol buffers are optional, this may be specified + * for emphasis if appropriate. + */ + OPTIONAL = 1, + /** + * REQUIRED - Denotes a field as required. + * This indicates that the field **must** be provided as part of the request, + * and failure to do so will cause an error (usually `INVALID_ARGUMENT`). + */ + REQUIRED = 2, + /** + * OUTPUT_ONLY - Denotes a field as output only. + * This indicates that the field is provided in responses, but including the + * field in a request does nothing (the server *must* ignore it and + * *must not* throw an error as a result of the field's presence). + */ + OUTPUT_ONLY = 3, + /** + * INPUT_ONLY - Denotes a field as input only. + * This indicates that the field is provided in requests, and the + * corresponding field is not included in output. + */ + INPUT_ONLY = 4, + /** + * IMMUTABLE - Denotes a field as immutable. + * This indicates that the field may be set once in a request to create a + * resource, but may not be changed thereafter. + */ + IMMUTABLE = 5, + /** + * UNORDERED_LIST - Denotes that a (repeated) field is an unordered list. + * This indicates that the service may provide the elements of the list + * in any arbitrary order, rather than the order the user originally + * provided. Additionally, the list's order may or may not be stable. + */ + UNORDERED_LIST = 6 +} +export declare function fieldBehaviorFromJSON(object: any): FieldBehavior; +export declare function fieldBehaviorToJSON(object: FieldBehavior): string; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/api/field_behavior.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/api/field_behavior.js new file mode 100644 index 0000000..f9b57cc --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/api/field_behavior.js @@ -0,0 +1,119 @@ +"use strict"; +/* eslint-disable */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fieldBehaviorToJSON = exports.fieldBehaviorFromJSON = exports.FieldBehavior = void 0; +/** + * An indicator of the behavior of a given field (for example, that a field + * is required in requests, or given as output but ignored as input). + * This **does not** change the behavior in protocol buffers itself; it only + * denotes the behavior and may affect how API tooling handles the field. + * + * Note: This enum **may** receive new values in the future. + */ +var FieldBehavior; +(function (FieldBehavior) { + /** FIELD_BEHAVIOR_UNSPECIFIED - Conventional default for enums. Do not use this. */ + FieldBehavior[FieldBehavior["FIELD_BEHAVIOR_UNSPECIFIED"] = 0] = "FIELD_BEHAVIOR_UNSPECIFIED"; + /** + * OPTIONAL - Specifically denotes a field as optional. + * While all fields in protocol buffers are optional, this may be specified + * for emphasis if appropriate. + */ + FieldBehavior[FieldBehavior["OPTIONAL"] = 1] = "OPTIONAL"; + /** + * REQUIRED - Denotes a field as required. + * This indicates that the field **must** be provided as part of the request, + * and failure to do so will cause an error (usually `INVALID_ARGUMENT`). + */ + FieldBehavior[FieldBehavior["REQUIRED"] = 2] = "REQUIRED"; + /** + * OUTPUT_ONLY - Denotes a field as output only. + * This indicates that the field is provided in responses, but including the + * field in a request does nothing (the server *must* ignore it and + * *must not* throw an error as a result of the field's presence). + */ + FieldBehavior[FieldBehavior["OUTPUT_ONLY"] = 3] = "OUTPUT_ONLY"; + /** + * INPUT_ONLY - Denotes a field as input only. + * This indicates that the field is provided in requests, and the + * corresponding field is not included in output. + */ + FieldBehavior[FieldBehavior["INPUT_ONLY"] = 4] = "INPUT_ONLY"; + /** + * IMMUTABLE - Denotes a field as immutable. + * This indicates that the field may be set once in a request to create a + * resource, but may not be changed thereafter. + */ + FieldBehavior[FieldBehavior["IMMUTABLE"] = 5] = "IMMUTABLE"; + /** + * UNORDERED_LIST - Denotes that a (repeated) field is an unordered list. + * This indicates that the service may provide the elements of the list + * in any arbitrary order, rather than the order the user originally + * provided. Additionally, the list's order may or may not be stable. + */ + FieldBehavior[FieldBehavior["UNORDERED_LIST"] = 6] = "UNORDERED_LIST"; +})(FieldBehavior = exports.FieldBehavior || (exports.FieldBehavior = {})); +function fieldBehaviorFromJSON(object) { + switch (object) { + case 0: + case "FIELD_BEHAVIOR_UNSPECIFIED": + return FieldBehavior.FIELD_BEHAVIOR_UNSPECIFIED; + case 1: + case "OPTIONAL": + return FieldBehavior.OPTIONAL; + case 2: + case "REQUIRED": + return FieldBehavior.REQUIRED; + case 3: + case "OUTPUT_ONLY": + return FieldBehavior.OUTPUT_ONLY; + case 4: + case "INPUT_ONLY": + return FieldBehavior.INPUT_ONLY; + case 5: + case "IMMUTABLE": + return FieldBehavior.IMMUTABLE; + case 6: + case "UNORDERED_LIST": + return FieldBehavior.UNORDERED_LIST; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldBehavior"); + } +} +exports.fieldBehaviorFromJSON = fieldBehaviorFromJSON; +function fieldBehaviorToJSON(object) { + switch (object) { + case FieldBehavior.FIELD_BEHAVIOR_UNSPECIFIED: + return "FIELD_BEHAVIOR_UNSPECIFIED"; + case FieldBehavior.OPTIONAL: + return "OPTIONAL"; + case FieldBehavior.REQUIRED: + return "REQUIRED"; + case FieldBehavior.OUTPUT_ONLY: + return "OUTPUT_ONLY"; + case FieldBehavior.INPUT_ONLY: + return "INPUT_ONLY"; + case FieldBehavior.IMMUTABLE: + return "IMMUTABLE"; + case FieldBehavior.UNORDERED_LIST: + return "UNORDERED_LIST"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldBehavior"); + } +} +exports.fieldBehaviorToJSON = fieldBehaviorToJSON; +var globalThis = (() => { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw "Unable to locate global object"; +})(); diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/descriptor.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/descriptor.d.ts new file mode 100644 index 0000000..ef43bf0 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/descriptor.d.ts @@ -0,0 +1,939 @@ +/// +/** + * The protocol compiler can output a FileDescriptorSet containing the .proto + * files it parses. + */ +export interface FileDescriptorSet { + file: FileDescriptorProto[]; +} +/** Describes a complete .proto file. */ +export interface FileDescriptorProto { + /** file name, relative to root of source tree */ + name: string; + /** e.g. "foo", "foo.bar", etc. */ + package: string; + /** Names of files imported by this file. */ + dependency: string[]; + /** Indexes of the public imported files in the dependency list above. */ + publicDependency: number[]; + /** + * Indexes of the weak imported files in the dependency list. + * For Google-internal migration only. Do not use. + */ + weakDependency: number[]; + /** All top-level definitions in this file. */ + messageType: DescriptorProto[]; + enumType: EnumDescriptorProto[]; + service: ServiceDescriptorProto[]; + extension: FieldDescriptorProto[]; + options: FileOptions | undefined; + /** + * This field contains optional information about the original source code. + * You may safely remove this entire field without harming runtime + * functionality of the descriptors -- the information is needed only by + * development tools. + */ + sourceCodeInfo: SourceCodeInfo | undefined; + /** + * The syntax of the proto file. + * The supported values are "proto2" and "proto3". + */ + syntax: string; +} +/** Describes a message type. */ +export interface DescriptorProto { + name: string; + field: FieldDescriptorProto[]; + extension: FieldDescriptorProto[]; + nestedType: DescriptorProto[]; + enumType: EnumDescriptorProto[]; + extensionRange: DescriptorProto_ExtensionRange[]; + oneofDecl: OneofDescriptorProto[]; + options: MessageOptions | undefined; + reservedRange: DescriptorProto_ReservedRange[]; + /** + * Reserved field names, which may not be used by fields in the same message. + * A given name may only be reserved once. + */ + reservedName: string[]; +} +export interface DescriptorProto_ExtensionRange { + /** Inclusive. */ + start: number; + /** Exclusive. */ + end: number; + options: ExtensionRangeOptions | undefined; +} +/** + * Range of reserved tag numbers. Reserved tag numbers may not be used by + * fields or extension ranges in the same message. Reserved ranges may + * not overlap. + */ +export interface DescriptorProto_ReservedRange { + /** Inclusive. */ + start: number; + /** Exclusive. */ + end: number; +} +export interface ExtensionRangeOptions { + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} +/** Describes a field within a message. */ +export interface FieldDescriptorProto { + name: string; + number: number; + label: FieldDescriptorProto_Label; + /** + * If type_name is set, this need not be set. If both this and type_name + * are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + */ + type: FieldDescriptorProto_Type; + /** + * For message and enum types, this is the name of the type. If the name + * starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + * rules are used to find the type (i.e. first the nested types within this + * message are searched, then within the parent, on up to the root + * namespace). + */ + typeName: string; + /** + * For extensions, this is the name of the type being extended. It is + * resolved in the same manner as type_name. + */ + extendee: string; + /** + * For numeric types, contains the original text representation of the value. + * For booleans, "true" or "false". + * For strings, contains the default text contents (not escaped in any way). + * For bytes, contains the C escaped value. All bytes >= 128 are escaped. + */ + defaultValue: string; + /** + * If set, gives the index of a oneof in the containing type's oneof_decl + * list. This field is a member of that oneof. + */ + oneofIndex: number; + /** + * JSON name of this field. The value is set by protocol compiler. If the + * user has set a "json_name" option on this field, that option's value + * will be used. Otherwise, it's deduced from the field's name by converting + * it to camelCase. + */ + jsonName: string; + options: FieldOptions | undefined; + /** + * If true, this is a proto3 "optional". When a proto3 field is optional, it + * tracks presence regardless of field type. + * + * When proto3_optional is true, this field must be belong to a oneof to + * signal to old proto3 clients that presence is tracked for this field. This + * oneof is known as a "synthetic" oneof, and this field must be its sole + * member (each proto3 optional field gets its own synthetic oneof). Synthetic + * oneofs exist in the descriptor only, and do not generate any API. Synthetic + * oneofs must be ordered after all "real" oneofs. + * + * For message fields, proto3_optional doesn't create any semantic change, + * since non-repeated message fields always track presence. However it still + * indicates the semantic detail of whether the user wrote "optional" or not. + * This can be useful for round-tripping the .proto file. For consistency we + * give message fields a synthetic oneof also, even though it is not required + * to track presence. This is especially important because the parser can't + * tell if a field is a message or an enum, so it must always create a + * synthetic oneof. + * + * Proto2 optional fields do not set this flag, because they already indicate + * optional with `LABEL_OPTIONAL`. + */ + proto3Optional: boolean; +} +export declare enum FieldDescriptorProto_Type { + /** + * TYPE_DOUBLE - 0 is reserved for errors. + * Order is weird for historical reasons. + */ + TYPE_DOUBLE = 1, + TYPE_FLOAT = 2, + /** + * TYPE_INT64 - Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + * negative values are likely. + */ + TYPE_INT64 = 3, + TYPE_UINT64 = 4, + /** + * TYPE_INT32 - Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + * negative values are likely. + */ + TYPE_INT32 = 5, + TYPE_FIXED64 = 6, + TYPE_FIXED32 = 7, + TYPE_BOOL = 8, + TYPE_STRING = 9, + /** + * TYPE_GROUP - Tag-delimited aggregate. + * Group type is deprecated and not supported in proto3. However, Proto3 + * implementations should still be able to parse the group wire format and + * treat group fields as unknown fields. + */ + TYPE_GROUP = 10, + /** TYPE_MESSAGE - Length-delimited aggregate. */ + TYPE_MESSAGE = 11, + /** TYPE_BYTES - New in version 2. */ + TYPE_BYTES = 12, + TYPE_UINT32 = 13, + TYPE_ENUM = 14, + TYPE_SFIXED32 = 15, + TYPE_SFIXED64 = 16, + /** TYPE_SINT32 - Uses ZigZag encoding. */ + TYPE_SINT32 = 17, + /** TYPE_SINT64 - Uses ZigZag encoding. */ + TYPE_SINT64 = 18 +} +export declare function fieldDescriptorProto_TypeFromJSON(object: any): FieldDescriptorProto_Type; +export declare function fieldDescriptorProto_TypeToJSON(object: FieldDescriptorProto_Type): string; +export declare enum FieldDescriptorProto_Label { + /** LABEL_OPTIONAL - 0 is reserved for errors */ + LABEL_OPTIONAL = 1, + LABEL_REQUIRED = 2, + LABEL_REPEATED = 3 +} +export declare function fieldDescriptorProto_LabelFromJSON(object: any): FieldDescriptorProto_Label; +export declare function fieldDescriptorProto_LabelToJSON(object: FieldDescriptorProto_Label): string; +/** Describes a oneof. */ +export interface OneofDescriptorProto { + name: string; + options: OneofOptions | undefined; +} +/** Describes an enum type. */ +export interface EnumDescriptorProto { + name: string; + value: EnumValueDescriptorProto[]; + options: EnumOptions | undefined; + /** + * Range of reserved numeric values. Reserved numeric values may not be used + * by enum values in the same enum declaration. Reserved ranges may not + * overlap. + */ + reservedRange: EnumDescriptorProto_EnumReservedRange[]; + /** + * Reserved enum value names, which may not be reused. A given name may only + * be reserved once. + */ + reservedName: string[]; +} +/** + * Range of reserved numeric values. Reserved values may not be used by + * entries in the same enum. Reserved ranges may not overlap. + * + * Note that this is distinct from DescriptorProto.ReservedRange in that it + * is inclusive such that it can appropriately represent the entire int32 + * domain. + */ +export interface EnumDescriptorProto_EnumReservedRange { + /** Inclusive. */ + start: number; + /** Inclusive. */ + end: number; +} +/** Describes a value within an enum. */ +export interface EnumValueDescriptorProto { + name: string; + number: number; + options: EnumValueOptions | undefined; +} +/** Describes a service. */ +export interface ServiceDescriptorProto { + name: string; + method: MethodDescriptorProto[]; + options: ServiceOptions | undefined; +} +/** Describes a method of a service. */ +export interface MethodDescriptorProto { + name: string; + /** + * Input and output type names. These are resolved in the same way as + * FieldDescriptorProto.type_name, but must refer to a message type. + */ + inputType: string; + outputType: string; + options: MethodOptions | undefined; + /** Identifies if client streams multiple client messages */ + clientStreaming: boolean; + /** Identifies if server streams multiple server messages */ + serverStreaming: boolean; +} +export interface FileOptions { + /** + * Sets the Java package where classes generated from this .proto will be + * placed. By default, the proto package is used, but this is often + * inappropriate because proto packages do not normally start with backwards + * domain names. + */ + javaPackage: string; + /** + * Controls the name of the wrapper Java class generated for the .proto file. + * That class will always contain the .proto file's getDescriptor() method as + * well as any top-level extensions defined in the .proto file. + * If java_multiple_files is disabled, then all the other classes from the + * .proto file will be nested inside the single wrapper outer class. + */ + javaOuterClassname: string; + /** + * If enabled, then the Java code generator will generate a separate .java + * file for each top-level message, enum, and service defined in the .proto + * file. Thus, these types will *not* be nested inside the wrapper class + * named by java_outer_classname. However, the wrapper class will still be + * generated to contain the file's getDescriptor() method as well as any + * top-level extensions defined in the file. + */ + javaMultipleFiles: boolean; + /** + * This option does nothing. + * + * @deprecated + */ + javaGenerateEqualsAndHash: boolean; + /** + * If set true, then the Java2 code generator will generate code that + * throws an exception whenever an attempt is made to assign a non-UTF-8 + * byte sequence to a string field. + * Message reflection will do the same. + * However, an extension field still accepts non-UTF-8 byte sequences. + * This option has no effect on when used with the lite runtime. + */ + javaStringCheckUtf8: boolean; + optimizeFor: FileOptions_OptimizeMode; + /** + * Sets the Go package where structs generated from this .proto will be + * placed. If omitted, the Go package will be derived from the following: + * - The basename of the package import path, if provided. + * - Otherwise, the package statement in the .proto file, if present. + * - Otherwise, the basename of the .proto file, without extension. + */ + goPackage: string; + /** + * Should generic services be generated in each language? "Generic" services + * are not specific to any particular RPC system. They are generated by the + * main code generators in each language (without additional plugins). + * Generic services were the only kind of service generation supported by + * early versions of google.protobuf. + * + * Generic services are now considered deprecated in favor of using plugins + * that generate code specific to your particular RPC system. Therefore, + * these default to false. Old code which depends on generic services should + * explicitly set them to true. + */ + ccGenericServices: boolean; + javaGenericServices: boolean; + pyGenericServices: boolean; + phpGenericServices: boolean; + /** + * Is this file deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for everything in the file, or it will be completely ignored; in the very + * least, this is a formalization for deprecating files. + */ + deprecated: boolean; + /** + * Enables the use of arenas for the proto messages in this file. This applies + * only to generated classes for C++. + */ + ccEnableArenas: boolean; + /** + * Sets the objective c class prefix which is prepended to all objective c + * generated classes from this .proto. There is no default. + */ + objcClassPrefix: string; + /** Namespace for generated classes; defaults to the package. */ + csharpNamespace: string; + /** + * By default Swift generators will take the proto package and CamelCase it + * replacing '.' with underscore and use that to prefix the types/symbols + * defined. When this options is provided, they will use this value instead + * to prefix the types/symbols defined. + */ + swiftPrefix: string; + /** + * Sets the php class prefix which is prepended to all php generated classes + * from this .proto. Default is empty. + */ + phpClassPrefix: string; + /** + * Use this option to change the namespace of php generated classes. Default + * is empty. When this option is empty, the package name will be used for + * determining the namespace. + */ + phpNamespace: string; + /** + * Use this option to change the namespace of php generated metadata classes. + * Default is empty. When this option is empty, the proto file name will be + * used for determining the namespace. + */ + phpMetadataNamespace: string; + /** + * Use this option to change the package of ruby generated classes. Default + * is empty. When this option is not set, the package name will be used for + * determining the ruby package. + */ + rubyPackage: string; + /** + * The parser stores options it doesn't recognize here. + * See the documentation for the "Options" section above. + */ + uninterpretedOption: UninterpretedOption[]; +} +/** Generated classes can be optimized for speed or code size. */ +export declare enum FileOptions_OptimizeMode { + /** SPEED - Generate complete code for parsing, serialization, */ + SPEED = 1, + /** CODE_SIZE - etc. */ + CODE_SIZE = 2, + /** LITE_RUNTIME - Generate code using MessageLite and the lite runtime. */ + LITE_RUNTIME = 3 +} +export declare function fileOptions_OptimizeModeFromJSON(object: any): FileOptions_OptimizeMode; +export declare function fileOptions_OptimizeModeToJSON(object: FileOptions_OptimizeMode): string; +export interface MessageOptions { + /** + * Set true to use the old proto1 MessageSet wire format for extensions. + * This is provided for backwards-compatibility with the MessageSet wire + * format. You should not use this for any other reason: It's less + * efficient, has fewer features, and is more complicated. + * + * The message must be defined exactly as follows: + * message Foo { + * option message_set_wire_format = true; + * extensions 4 to max; + * } + * Note that the message cannot have any defined fields; MessageSets only + * have extensions. + * + * All extensions of your type must be singular messages; e.g. they cannot + * be int32s, enums, or repeated messages. + * + * Because this is an option, the above two restrictions are not enforced by + * the protocol compiler. + */ + messageSetWireFormat: boolean; + /** + * Disables the generation of the standard "descriptor()" accessor, which can + * conflict with a field of the same name. This is meant to make migration + * from proto1 easier; new code should avoid fields named "descriptor". + */ + noStandardDescriptorAccessor: boolean; + /** + * Is this message deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for the message, or it will be completely ignored; in the very least, + * this is a formalization for deprecating messages. + */ + deprecated: boolean; + /** + * Whether the message is an automatically generated map entry type for the + * maps field. + * + * For maps fields: + * map map_field = 1; + * The parsed descriptor looks like: + * message MapFieldEntry { + * option map_entry = true; + * optional KeyType key = 1; + * optional ValueType value = 2; + * } + * repeated MapFieldEntry map_field = 1; + * + * Implementations may choose not to generate the map_entry=true message, but + * use a native map in the target language to hold the keys and values. + * The reflection APIs in such implementations still need to work as + * if the field is a repeated message field. + * + * NOTE: Do not set the option in .proto files. Always use the maps syntax + * instead. The option should only be implicitly set by the proto compiler + * parser. + */ + mapEntry: boolean; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} +export interface FieldOptions { + /** + * The ctype option instructs the C++ code generator to use a different + * representation of the field than it normally would. See the specific + * options below. This option is not yet implemented in the open source + * release -- sorry, we'll try to include it in a future version! + */ + ctype: FieldOptions_CType; + /** + * The packed option can be enabled for repeated primitive fields to enable + * a more efficient representation on the wire. Rather than repeatedly + * writing the tag and type for each element, the entire array is encoded as + * a single length-delimited blob. In proto3, only explicit setting it to + * false will avoid using packed encoding. + */ + packed: boolean; + /** + * The jstype option determines the JavaScript type used for values of the + * field. The option is permitted only for 64 bit integral and fixed types + * (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + * is represented as JavaScript string, which avoids loss of precision that + * can happen when a large value is converted to a floating point JavaScript. + * Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + * use the JavaScript "number" type. The behavior of the default option + * JS_NORMAL is implementation dependent. + * + * This option is an enum to permit additional types to be added, e.g. + * goog.math.Integer. + */ + jstype: FieldOptions_JSType; + /** + * Should this field be parsed lazily? Lazy applies only to message-type + * fields. It means that when the outer message is initially parsed, the + * inner message's contents will not be parsed but instead stored in encoded + * form. The inner message will actually be parsed when it is first accessed. + * + * This is only a hint. Implementations are free to choose whether to use + * eager or lazy parsing regardless of the value of this option. However, + * setting this option true suggests that the protocol author believes that + * using lazy parsing on this field is worth the additional bookkeeping + * overhead typically needed to implement it. + * + * This option does not affect the public interface of any generated code; + * all method signatures remain the same. Furthermore, thread-safety of the + * interface is not affected by this option; const methods remain safe to + * call from multiple threads concurrently, while non-const methods continue + * to require exclusive access. + * + * Note that implementations may choose not to check required fields within + * a lazy sub-message. That is, calling IsInitialized() on the outer message + * may return true even if the inner message has missing required fields. + * This is necessary because otherwise the inner message would have to be + * parsed in order to perform the check, defeating the purpose of lazy + * parsing. An implementation which chooses not to check required fields + * must be consistent about it. That is, for any particular sub-message, the + * implementation must either *always* check its required fields, or *never* + * check its required fields, regardless of whether or not the message has + * been parsed. + * + * As of 2021, lazy does no correctness checks on the byte stream during + * parsing. This may lead to crashes if and when an invalid byte stream is + * finally parsed upon access. + * + * TODO(b/211906113): Enable validation on lazy fields. + */ + lazy: boolean; + /** + * unverified_lazy does no correctness checks on the byte stream. This should + * only be used where lazy with verification is prohibitive for performance + * reasons. + */ + unverifiedLazy: boolean; + /** + * Is this field deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for accessors, or it will be completely ignored; in the very least, this + * is a formalization for deprecating fields. + */ + deprecated: boolean; + /** For Google-internal migration only. Do not use. */ + weak: boolean; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} +export declare enum FieldOptions_CType { + /** STRING - Default mode. */ + STRING = 0, + CORD = 1, + STRING_PIECE = 2 +} +export declare function fieldOptions_CTypeFromJSON(object: any): FieldOptions_CType; +export declare function fieldOptions_CTypeToJSON(object: FieldOptions_CType): string; +export declare enum FieldOptions_JSType { + /** JS_NORMAL - Use the default type. */ + JS_NORMAL = 0, + /** JS_STRING - Use JavaScript strings. */ + JS_STRING = 1, + /** JS_NUMBER - Use JavaScript numbers. */ + JS_NUMBER = 2 +} +export declare function fieldOptions_JSTypeFromJSON(object: any): FieldOptions_JSType; +export declare function fieldOptions_JSTypeToJSON(object: FieldOptions_JSType): string; +export interface OneofOptions { + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} +export interface EnumOptions { + /** + * Set this option to true to allow mapping different tag names to the same + * value. + */ + allowAlias: boolean; + /** + * Is this enum deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for the enum, or it will be completely ignored; in the very least, this + * is a formalization for deprecating enums. + */ + deprecated: boolean; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} +export interface EnumValueOptions { + /** + * Is this enum value deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for the enum value, or it will be completely ignored; in the very least, + * this is a formalization for deprecating enum values. + */ + deprecated: boolean; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} +export interface ServiceOptions { + /** + * Is this service deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for the service, or it will be completely ignored; in the very least, + * this is a formalization for deprecating services. + */ + deprecated: boolean; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} +export interface MethodOptions { + /** + * Is this method deprecated? + * Depending on the target platform, this can emit Deprecated annotations + * for the method, or it will be completely ignored; in the very least, + * this is a formalization for deprecating methods. + */ + deprecated: boolean; + idempotencyLevel: MethodOptions_IdempotencyLevel; + /** The parser stores options it doesn't recognize here. See above. */ + uninterpretedOption: UninterpretedOption[]; +} +/** + * Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + * or neither? HTTP based RPC implementation may choose GET verb for safe + * methods, and PUT verb for idempotent methods instead of the default POST. + */ +export declare enum MethodOptions_IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = 0, + /** NO_SIDE_EFFECTS - implies idempotent */ + NO_SIDE_EFFECTS = 1, + /** IDEMPOTENT - idempotent, but may have side effects */ + IDEMPOTENT = 2 +} +export declare function methodOptions_IdempotencyLevelFromJSON(object: any): MethodOptions_IdempotencyLevel; +export declare function methodOptions_IdempotencyLevelToJSON(object: MethodOptions_IdempotencyLevel): string; +/** + * A message representing a option the parser does not recognize. This only + * appears in options protos created by the compiler::Parser class. + * DescriptorPool resolves these when building Descriptor objects. Therefore, + * options protos in descriptor objects (e.g. returned by Descriptor::options(), + * or produced by Descriptor::CopyTo()) will never have UninterpretedOptions + * in them. + */ +export interface UninterpretedOption { + name: UninterpretedOption_NamePart[]; + /** + * The value of the uninterpreted option, in whatever type the tokenizer + * identified it as during parsing. Exactly one of these should be set. + */ + identifierValue: string; + positiveIntValue: string; + negativeIntValue: string; + doubleValue: number; + stringValue: Buffer; + aggregateValue: string; +} +/** + * The name of the uninterpreted option. Each string represents a segment in + * a dot-separated name. is_extension is true iff a segment represents an + * extension (denoted with parentheses in options specs in .proto files). + * E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + * "foo.(bar.baz).moo". + */ +export interface UninterpretedOption_NamePart { + namePart: string; + isExtension: boolean; +} +/** + * Encapsulates information about the original source file from which a + * FileDescriptorProto was generated. + */ +export interface SourceCodeInfo { + /** + * A Location identifies a piece of source code in a .proto file which + * corresponds to a particular definition. This information is intended + * to be useful to IDEs, code indexers, documentation generators, and similar + * tools. + * + * For example, say we have a file like: + * message Foo { + * optional string foo = 1; + * } + * Let's look at just the field definition: + * optional string foo = 1; + * ^ ^^ ^^ ^ ^^^ + * a bc de f ghi + * We have the following locations: + * span path represents + * [a,i) [ 4, 0, 2, 0 ] The whole field definition. + * [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + * [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + * [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + * [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + * + * Notes: + * - A location may refer to a repeated field itself (i.e. not to any + * particular index within it). This is used whenever a set of elements are + * logically enclosed in a single code segment. For example, an entire + * extend block (possibly containing multiple extension definitions) will + * have an outer location whose path refers to the "extensions" repeated + * field without an index. + * - Multiple locations may have the same path. This happens when a single + * logical declaration is spread out across multiple places. The most + * obvious example is the "extend" block again -- there may be multiple + * extend blocks in the same scope, each of which will have the same path. + * - A location's span is not always a subset of its parent's span. For + * example, the "extendee" of an extension declaration appears at the + * beginning of the "extend" block and is shared by all extensions within + * the block. + * - Just because a location's span is a subset of some other location's span + * does not mean that it is a descendant. For example, a "group" defines + * both a type and a field in a single declaration. Thus, the locations + * corresponding to the type and field and their components will overlap. + * - Code which tries to interpret locations should probably be designed to + * ignore those that it doesn't understand, as more types of locations could + * be recorded in the future. + */ + location: SourceCodeInfo_Location[]; +} +export interface SourceCodeInfo_Location { + /** + * Identifies which part of the FileDescriptorProto was defined at this + * location. + * + * Each element is a field number or an index. They form a path from + * the root FileDescriptorProto to the place where the definition occurs. + * For example, this path: + * [ 4, 3, 2, 7, 1 ] + * refers to: + * file.message_type(3) // 4, 3 + * .field(7) // 2, 7 + * .name() // 1 + * This is because FileDescriptorProto.message_type has field number 4: + * repeated DescriptorProto message_type = 4; + * and DescriptorProto.field has field number 2: + * repeated FieldDescriptorProto field = 2; + * and FieldDescriptorProto.name has field number 1: + * optional string name = 1; + * + * Thus, the above path gives the location of a field name. If we removed + * the last element: + * [ 4, 3, 2, 7 ] + * this path refers to the whole field declaration (from the beginning + * of the label to the terminating semicolon). + */ + path: number[]; + /** + * Always has exactly three or four elements: start line, start column, + * end line (optional, otherwise assumed same as start line), end column. + * These are packed into a single field for efficiency. Note that line + * and column numbers are zero-based -- typically you will want to add + * 1 to each before displaying to a user. + */ + span: number[]; + /** + * If this SourceCodeInfo represents a complete declaration, these are any + * comments appearing before and after the declaration which appear to be + * attached to the declaration. + * + * A series of line comments appearing on consecutive lines, with no other + * tokens appearing on those lines, will be treated as a single comment. + * + * leading_detached_comments will keep paragraphs of comments that appear + * before (but not connected to) the current element. Each paragraph, + * separated by empty lines, will be one comment element in the repeated + * field. + * + * Only the comment content is provided; comment markers (e.g. //) are + * stripped out. For block comments, leading whitespace and an asterisk + * will be stripped from the beginning of each line other than the first. + * Newlines are included in the output. + * + * Examples: + * + * optional int32 foo = 1; // Comment attached to foo. + * // Comment attached to bar. + * optional int32 bar = 2; + * + * optional string baz = 3; + * // Comment attached to baz. + * // Another line attached to baz. + * + * // Comment attached to moo. + * // + * // Another line attached to moo. + * optional double moo = 4; + * + * // Detached comment for corge. This is not leading or trailing comments + * // to moo or corge because there are blank lines separating it from + * // both. + * + * // Detached comment for corge paragraph 2. + * + * optional string corge = 5; + * /* Block comment attached + * * to corge. Leading asterisks + * * will be removed. * / + * /* Block comment attached to + * * grault. * / + * optional int32 grault = 6; + * + * // ignored detached comments. + */ + leadingComments: string; + trailingComments: string; + leadingDetachedComments: string[]; +} +/** + * Describes the relationship between generated code and its original source + * file. A GeneratedCodeInfo message is associated with only one generated + * source file, but may contain references to different source .proto files. + */ +export interface GeneratedCodeInfo { + /** + * An Annotation connects some span of text in generated code to an element + * of its generating .proto file. + */ + annotation: GeneratedCodeInfo_Annotation[]; +} +export interface GeneratedCodeInfo_Annotation { + /** + * Identifies the element in the original source .proto file. This field + * is formatted the same as SourceCodeInfo.Location.path. + */ + path: number[]; + /** Identifies the filesystem path to the original source .proto. */ + sourceFile: string; + /** + * Identifies the starting offset in bytes in the generated code + * that relates to the identified object. + */ + begin: number; + /** + * Identifies the ending offset in bytes in the generated code that + * relates to the identified offset. The end offset should be one past + * the last relevant byte (so the length of the text = end - begin). + */ + end: number; +} +export declare const FileDescriptorSet: { + fromJSON(object: any): FileDescriptorSet; + toJSON(message: FileDescriptorSet): unknown; +}; +export declare const FileDescriptorProto: { + fromJSON(object: any): FileDescriptorProto; + toJSON(message: FileDescriptorProto): unknown; +}; +export declare const DescriptorProto: { + fromJSON(object: any): DescriptorProto; + toJSON(message: DescriptorProto): unknown; +}; +export declare const DescriptorProto_ExtensionRange: { + fromJSON(object: any): DescriptorProto_ExtensionRange; + toJSON(message: DescriptorProto_ExtensionRange): unknown; +}; +export declare const DescriptorProto_ReservedRange: { + fromJSON(object: any): DescriptorProto_ReservedRange; + toJSON(message: DescriptorProto_ReservedRange): unknown; +}; +export declare const ExtensionRangeOptions: { + fromJSON(object: any): ExtensionRangeOptions; + toJSON(message: ExtensionRangeOptions): unknown; +}; +export declare const FieldDescriptorProto: { + fromJSON(object: any): FieldDescriptorProto; + toJSON(message: FieldDescriptorProto): unknown; +}; +export declare const OneofDescriptorProto: { + fromJSON(object: any): OneofDescriptorProto; + toJSON(message: OneofDescriptorProto): unknown; +}; +export declare const EnumDescriptorProto: { + fromJSON(object: any): EnumDescriptorProto; + toJSON(message: EnumDescriptorProto): unknown; +}; +export declare const EnumDescriptorProto_EnumReservedRange: { + fromJSON(object: any): EnumDescriptorProto_EnumReservedRange; + toJSON(message: EnumDescriptorProto_EnumReservedRange): unknown; +}; +export declare const EnumValueDescriptorProto: { + fromJSON(object: any): EnumValueDescriptorProto; + toJSON(message: EnumValueDescriptorProto): unknown; +}; +export declare const ServiceDescriptorProto: { + fromJSON(object: any): ServiceDescriptorProto; + toJSON(message: ServiceDescriptorProto): unknown; +}; +export declare const MethodDescriptorProto: { + fromJSON(object: any): MethodDescriptorProto; + toJSON(message: MethodDescriptorProto): unknown; +}; +export declare const FileOptions: { + fromJSON(object: any): FileOptions; + toJSON(message: FileOptions): unknown; +}; +export declare const MessageOptions: { + fromJSON(object: any): MessageOptions; + toJSON(message: MessageOptions): unknown; +}; +export declare const FieldOptions: { + fromJSON(object: any): FieldOptions; + toJSON(message: FieldOptions): unknown; +}; +export declare const OneofOptions: { + fromJSON(object: any): OneofOptions; + toJSON(message: OneofOptions): unknown; +}; +export declare const EnumOptions: { + fromJSON(object: any): EnumOptions; + toJSON(message: EnumOptions): unknown; +}; +export declare const EnumValueOptions: { + fromJSON(object: any): EnumValueOptions; + toJSON(message: EnumValueOptions): unknown; +}; +export declare const ServiceOptions: { + fromJSON(object: any): ServiceOptions; + toJSON(message: ServiceOptions): unknown; +}; +export declare const MethodOptions: { + fromJSON(object: any): MethodOptions; + toJSON(message: MethodOptions): unknown; +}; +export declare const UninterpretedOption: { + fromJSON(object: any): UninterpretedOption; + toJSON(message: UninterpretedOption): unknown; +}; +export declare const UninterpretedOption_NamePart: { + fromJSON(object: any): UninterpretedOption_NamePart; + toJSON(message: UninterpretedOption_NamePart): unknown; +}; +export declare const SourceCodeInfo: { + fromJSON(object: any): SourceCodeInfo; + toJSON(message: SourceCodeInfo): unknown; +}; +export declare const SourceCodeInfo_Location: { + fromJSON(object: any): SourceCodeInfo_Location; + toJSON(message: SourceCodeInfo_Location): unknown; +}; +export declare const GeneratedCodeInfo: { + fromJSON(object: any): GeneratedCodeInfo; + toJSON(message: GeneratedCodeInfo): unknown; +}; +export declare const GeneratedCodeInfo_Annotation: { + fromJSON(object: any): GeneratedCodeInfo_Annotation; + toJSON(message: GeneratedCodeInfo_Annotation): unknown; +}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/descriptor.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/descriptor.js new file mode 100644 index 0000000..b8cfc86 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/descriptor.js @@ -0,0 +1,1308 @@ +"use strict"; +/* eslint-disable */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GeneratedCodeInfo_Annotation = exports.GeneratedCodeInfo = exports.SourceCodeInfo_Location = exports.SourceCodeInfo = exports.UninterpretedOption_NamePart = exports.UninterpretedOption = exports.MethodOptions = exports.ServiceOptions = exports.EnumValueOptions = exports.EnumOptions = exports.OneofOptions = exports.FieldOptions = exports.MessageOptions = exports.FileOptions = exports.MethodDescriptorProto = exports.ServiceDescriptorProto = exports.EnumValueDescriptorProto = exports.EnumDescriptorProto_EnumReservedRange = exports.EnumDescriptorProto = exports.OneofDescriptorProto = exports.FieldDescriptorProto = exports.ExtensionRangeOptions = exports.DescriptorProto_ReservedRange = exports.DescriptorProto_ExtensionRange = exports.DescriptorProto = exports.FileDescriptorProto = exports.FileDescriptorSet = exports.methodOptions_IdempotencyLevelToJSON = exports.methodOptions_IdempotencyLevelFromJSON = exports.MethodOptions_IdempotencyLevel = exports.fieldOptions_JSTypeToJSON = exports.fieldOptions_JSTypeFromJSON = exports.FieldOptions_JSType = exports.fieldOptions_CTypeToJSON = exports.fieldOptions_CTypeFromJSON = exports.FieldOptions_CType = exports.fileOptions_OptimizeModeToJSON = exports.fileOptions_OptimizeModeFromJSON = exports.FileOptions_OptimizeMode = exports.fieldDescriptorProto_LabelToJSON = exports.fieldDescriptorProto_LabelFromJSON = exports.FieldDescriptorProto_Label = exports.fieldDescriptorProto_TypeToJSON = exports.fieldDescriptorProto_TypeFromJSON = exports.FieldDescriptorProto_Type = void 0; +var FieldDescriptorProto_Type; +(function (FieldDescriptorProto_Type) { + /** + * TYPE_DOUBLE - 0 is reserved for errors. + * Order is weird for historical reasons. + */ + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_DOUBLE"] = 1] = "TYPE_DOUBLE"; + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_FLOAT"] = 2] = "TYPE_FLOAT"; + /** + * TYPE_INT64 - Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + * negative values are likely. + */ + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_INT64"] = 3] = "TYPE_INT64"; + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_UINT64"] = 4] = "TYPE_UINT64"; + /** + * TYPE_INT32 - Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + * negative values are likely. + */ + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_INT32"] = 5] = "TYPE_INT32"; + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_FIXED64"] = 6] = "TYPE_FIXED64"; + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_FIXED32"] = 7] = "TYPE_FIXED32"; + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_BOOL"] = 8] = "TYPE_BOOL"; + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_STRING"] = 9] = "TYPE_STRING"; + /** + * TYPE_GROUP - Tag-delimited aggregate. + * Group type is deprecated and not supported in proto3. However, Proto3 + * implementations should still be able to parse the group wire format and + * treat group fields as unknown fields. + */ + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_GROUP"] = 10] = "TYPE_GROUP"; + /** TYPE_MESSAGE - Length-delimited aggregate. */ + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_MESSAGE"] = 11] = "TYPE_MESSAGE"; + /** TYPE_BYTES - New in version 2. */ + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_BYTES"] = 12] = "TYPE_BYTES"; + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_UINT32"] = 13] = "TYPE_UINT32"; + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_ENUM"] = 14] = "TYPE_ENUM"; + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SFIXED32"] = 15] = "TYPE_SFIXED32"; + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SFIXED64"] = 16] = "TYPE_SFIXED64"; + /** TYPE_SINT32 - Uses ZigZag encoding. */ + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SINT32"] = 17] = "TYPE_SINT32"; + /** TYPE_SINT64 - Uses ZigZag encoding. */ + FieldDescriptorProto_Type[FieldDescriptorProto_Type["TYPE_SINT64"] = 18] = "TYPE_SINT64"; +})(FieldDescriptorProto_Type = exports.FieldDescriptorProto_Type || (exports.FieldDescriptorProto_Type = {})); +function fieldDescriptorProto_TypeFromJSON(object) { + switch (object) { + case 1: + case "TYPE_DOUBLE": + return FieldDescriptorProto_Type.TYPE_DOUBLE; + case 2: + case "TYPE_FLOAT": + return FieldDescriptorProto_Type.TYPE_FLOAT; + case 3: + case "TYPE_INT64": + return FieldDescriptorProto_Type.TYPE_INT64; + case 4: + case "TYPE_UINT64": + return FieldDescriptorProto_Type.TYPE_UINT64; + case 5: + case "TYPE_INT32": + return FieldDescriptorProto_Type.TYPE_INT32; + case 6: + case "TYPE_FIXED64": + return FieldDescriptorProto_Type.TYPE_FIXED64; + case 7: + case "TYPE_FIXED32": + return FieldDescriptorProto_Type.TYPE_FIXED32; + case 8: + case "TYPE_BOOL": + return FieldDescriptorProto_Type.TYPE_BOOL; + case 9: + case "TYPE_STRING": + return FieldDescriptorProto_Type.TYPE_STRING; + case 10: + case "TYPE_GROUP": + return FieldDescriptorProto_Type.TYPE_GROUP; + case 11: + case "TYPE_MESSAGE": + return FieldDescriptorProto_Type.TYPE_MESSAGE; + case 12: + case "TYPE_BYTES": + return FieldDescriptorProto_Type.TYPE_BYTES; + case 13: + case "TYPE_UINT32": + return FieldDescriptorProto_Type.TYPE_UINT32; + case 14: + case "TYPE_ENUM": + return FieldDescriptorProto_Type.TYPE_ENUM; + case 15: + case "TYPE_SFIXED32": + return FieldDescriptorProto_Type.TYPE_SFIXED32; + case 16: + case "TYPE_SFIXED64": + return FieldDescriptorProto_Type.TYPE_SFIXED64; + case 17: + case "TYPE_SINT32": + return FieldDescriptorProto_Type.TYPE_SINT32; + case 18: + case "TYPE_SINT64": + return FieldDescriptorProto_Type.TYPE_SINT64; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Type"); + } +} +exports.fieldDescriptorProto_TypeFromJSON = fieldDescriptorProto_TypeFromJSON; +function fieldDescriptorProto_TypeToJSON(object) { + switch (object) { + case FieldDescriptorProto_Type.TYPE_DOUBLE: + return "TYPE_DOUBLE"; + case FieldDescriptorProto_Type.TYPE_FLOAT: + return "TYPE_FLOAT"; + case FieldDescriptorProto_Type.TYPE_INT64: + return "TYPE_INT64"; + case FieldDescriptorProto_Type.TYPE_UINT64: + return "TYPE_UINT64"; + case FieldDescriptorProto_Type.TYPE_INT32: + return "TYPE_INT32"; + case FieldDescriptorProto_Type.TYPE_FIXED64: + return "TYPE_FIXED64"; + case FieldDescriptorProto_Type.TYPE_FIXED32: + return "TYPE_FIXED32"; + case FieldDescriptorProto_Type.TYPE_BOOL: + return "TYPE_BOOL"; + case FieldDescriptorProto_Type.TYPE_STRING: + return "TYPE_STRING"; + case FieldDescriptorProto_Type.TYPE_GROUP: + return "TYPE_GROUP"; + case FieldDescriptorProto_Type.TYPE_MESSAGE: + return "TYPE_MESSAGE"; + case FieldDescriptorProto_Type.TYPE_BYTES: + return "TYPE_BYTES"; + case FieldDescriptorProto_Type.TYPE_UINT32: + return "TYPE_UINT32"; + case FieldDescriptorProto_Type.TYPE_ENUM: + return "TYPE_ENUM"; + case FieldDescriptorProto_Type.TYPE_SFIXED32: + return "TYPE_SFIXED32"; + case FieldDescriptorProto_Type.TYPE_SFIXED64: + return "TYPE_SFIXED64"; + case FieldDescriptorProto_Type.TYPE_SINT32: + return "TYPE_SINT32"; + case FieldDescriptorProto_Type.TYPE_SINT64: + return "TYPE_SINT64"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Type"); + } +} +exports.fieldDescriptorProto_TypeToJSON = fieldDescriptorProto_TypeToJSON; +var FieldDescriptorProto_Label; +(function (FieldDescriptorProto_Label) { + /** LABEL_OPTIONAL - 0 is reserved for errors */ + FieldDescriptorProto_Label[FieldDescriptorProto_Label["LABEL_OPTIONAL"] = 1] = "LABEL_OPTIONAL"; + FieldDescriptorProto_Label[FieldDescriptorProto_Label["LABEL_REQUIRED"] = 2] = "LABEL_REQUIRED"; + FieldDescriptorProto_Label[FieldDescriptorProto_Label["LABEL_REPEATED"] = 3] = "LABEL_REPEATED"; +})(FieldDescriptorProto_Label = exports.FieldDescriptorProto_Label || (exports.FieldDescriptorProto_Label = {})); +function fieldDescriptorProto_LabelFromJSON(object) { + switch (object) { + case 1: + case "LABEL_OPTIONAL": + return FieldDescriptorProto_Label.LABEL_OPTIONAL; + case 2: + case "LABEL_REQUIRED": + return FieldDescriptorProto_Label.LABEL_REQUIRED; + case 3: + case "LABEL_REPEATED": + return FieldDescriptorProto_Label.LABEL_REPEATED; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Label"); + } +} +exports.fieldDescriptorProto_LabelFromJSON = fieldDescriptorProto_LabelFromJSON; +function fieldDescriptorProto_LabelToJSON(object) { + switch (object) { + case FieldDescriptorProto_Label.LABEL_OPTIONAL: + return "LABEL_OPTIONAL"; + case FieldDescriptorProto_Label.LABEL_REQUIRED: + return "LABEL_REQUIRED"; + case FieldDescriptorProto_Label.LABEL_REPEATED: + return "LABEL_REPEATED"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldDescriptorProto_Label"); + } +} +exports.fieldDescriptorProto_LabelToJSON = fieldDescriptorProto_LabelToJSON; +/** Generated classes can be optimized for speed or code size. */ +var FileOptions_OptimizeMode; +(function (FileOptions_OptimizeMode) { + /** SPEED - Generate complete code for parsing, serialization, */ + FileOptions_OptimizeMode[FileOptions_OptimizeMode["SPEED"] = 1] = "SPEED"; + /** CODE_SIZE - etc. */ + FileOptions_OptimizeMode[FileOptions_OptimizeMode["CODE_SIZE"] = 2] = "CODE_SIZE"; + /** LITE_RUNTIME - Generate code using MessageLite and the lite runtime. */ + FileOptions_OptimizeMode[FileOptions_OptimizeMode["LITE_RUNTIME"] = 3] = "LITE_RUNTIME"; +})(FileOptions_OptimizeMode = exports.FileOptions_OptimizeMode || (exports.FileOptions_OptimizeMode = {})); +function fileOptions_OptimizeModeFromJSON(object) { + switch (object) { + case 1: + case "SPEED": + return FileOptions_OptimizeMode.SPEED; + case 2: + case "CODE_SIZE": + return FileOptions_OptimizeMode.CODE_SIZE; + case 3: + case "LITE_RUNTIME": + return FileOptions_OptimizeMode.LITE_RUNTIME; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FileOptions_OptimizeMode"); + } +} +exports.fileOptions_OptimizeModeFromJSON = fileOptions_OptimizeModeFromJSON; +function fileOptions_OptimizeModeToJSON(object) { + switch (object) { + case FileOptions_OptimizeMode.SPEED: + return "SPEED"; + case FileOptions_OptimizeMode.CODE_SIZE: + return "CODE_SIZE"; + case FileOptions_OptimizeMode.LITE_RUNTIME: + return "LITE_RUNTIME"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FileOptions_OptimizeMode"); + } +} +exports.fileOptions_OptimizeModeToJSON = fileOptions_OptimizeModeToJSON; +var FieldOptions_CType; +(function (FieldOptions_CType) { + /** STRING - Default mode. */ + FieldOptions_CType[FieldOptions_CType["STRING"] = 0] = "STRING"; + FieldOptions_CType[FieldOptions_CType["CORD"] = 1] = "CORD"; + FieldOptions_CType[FieldOptions_CType["STRING_PIECE"] = 2] = "STRING_PIECE"; +})(FieldOptions_CType = exports.FieldOptions_CType || (exports.FieldOptions_CType = {})); +function fieldOptions_CTypeFromJSON(object) { + switch (object) { + case 0: + case "STRING": + return FieldOptions_CType.STRING; + case 1: + case "CORD": + return FieldOptions_CType.CORD; + case 2: + case "STRING_PIECE": + return FieldOptions_CType.STRING_PIECE; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_CType"); + } +} +exports.fieldOptions_CTypeFromJSON = fieldOptions_CTypeFromJSON; +function fieldOptions_CTypeToJSON(object) { + switch (object) { + case FieldOptions_CType.STRING: + return "STRING"; + case FieldOptions_CType.CORD: + return "CORD"; + case FieldOptions_CType.STRING_PIECE: + return "STRING_PIECE"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_CType"); + } +} +exports.fieldOptions_CTypeToJSON = fieldOptions_CTypeToJSON; +var FieldOptions_JSType; +(function (FieldOptions_JSType) { + /** JS_NORMAL - Use the default type. */ + FieldOptions_JSType[FieldOptions_JSType["JS_NORMAL"] = 0] = "JS_NORMAL"; + /** JS_STRING - Use JavaScript strings. */ + FieldOptions_JSType[FieldOptions_JSType["JS_STRING"] = 1] = "JS_STRING"; + /** JS_NUMBER - Use JavaScript numbers. */ + FieldOptions_JSType[FieldOptions_JSType["JS_NUMBER"] = 2] = "JS_NUMBER"; +})(FieldOptions_JSType = exports.FieldOptions_JSType || (exports.FieldOptions_JSType = {})); +function fieldOptions_JSTypeFromJSON(object) { + switch (object) { + case 0: + case "JS_NORMAL": + return FieldOptions_JSType.JS_NORMAL; + case 1: + case "JS_STRING": + return FieldOptions_JSType.JS_STRING; + case 2: + case "JS_NUMBER": + return FieldOptions_JSType.JS_NUMBER; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_JSType"); + } +} +exports.fieldOptions_JSTypeFromJSON = fieldOptions_JSTypeFromJSON; +function fieldOptions_JSTypeToJSON(object) { + switch (object) { + case FieldOptions_JSType.JS_NORMAL: + return "JS_NORMAL"; + case FieldOptions_JSType.JS_STRING: + return "JS_STRING"; + case FieldOptions_JSType.JS_NUMBER: + return "JS_NUMBER"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum FieldOptions_JSType"); + } +} +exports.fieldOptions_JSTypeToJSON = fieldOptions_JSTypeToJSON; +/** + * Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + * or neither? HTTP based RPC implementation may choose GET verb for safe + * methods, and PUT verb for idempotent methods instead of the default POST. + */ +var MethodOptions_IdempotencyLevel; +(function (MethodOptions_IdempotencyLevel) { + MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = 0] = "IDEMPOTENCY_UNKNOWN"; + /** NO_SIDE_EFFECTS - implies idempotent */ + MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["NO_SIDE_EFFECTS"] = 1] = "NO_SIDE_EFFECTS"; + /** IDEMPOTENT - idempotent, but may have side effects */ + MethodOptions_IdempotencyLevel[MethodOptions_IdempotencyLevel["IDEMPOTENT"] = 2] = "IDEMPOTENT"; +})(MethodOptions_IdempotencyLevel = exports.MethodOptions_IdempotencyLevel || (exports.MethodOptions_IdempotencyLevel = {})); +function methodOptions_IdempotencyLevelFromJSON(object) { + switch (object) { + case 0: + case "IDEMPOTENCY_UNKNOWN": + return MethodOptions_IdempotencyLevel.IDEMPOTENCY_UNKNOWN; + case 1: + case "NO_SIDE_EFFECTS": + return MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS; + case 2: + case "IDEMPOTENT": + return MethodOptions_IdempotencyLevel.IDEMPOTENT; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum MethodOptions_IdempotencyLevel"); + } +} +exports.methodOptions_IdempotencyLevelFromJSON = methodOptions_IdempotencyLevelFromJSON; +function methodOptions_IdempotencyLevelToJSON(object) { + switch (object) { + case MethodOptions_IdempotencyLevel.IDEMPOTENCY_UNKNOWN: + return "IDEMPOTENCY_UNKNOWN"; + case MethodOptions_IdempotencyLevel.NO_SIDE_EFFECTS: + return "NO_SIDE_EFFECTS"; + case MethodOptions_IdempotencyLevel.IDEMPOTENT: + return "IDEMPOTENT"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum MethodOptions_IdempotencyLevel"); + } +} +exports.methodOptions_IdempotencyLevelToJSON = methodOptions_IdempotencyLevelToJSON; +function createBaseFileDescriptorSet() { + return { file: [] }; +} +exports.FileDescriptorSet = { + fromJSON(object) { + return { file: Array.isArray(object?.file) ? object.file.map((e) => exports.FileDescriptorProto.fromJSON(e)) : [] }; + }, + toJSON(message) { + const obj = {}; + if (message.file) { + obj.file = message.file.map((e) => e ? exports.FileDescriptorProto.toJSON(e) : undefined); + } + else { + obj.file = []; + } + return obj; + }, +}; +function createBaseFileDescriptorProto() { + return { + name: "", + package: "", + dependency: [], + publicDependency: [], + weakDependency: [], + messageType: [], + enumType: [], + service: [], + extension: [], + options: undefined, + sourceCodeInfo: undefined, + syntax: "", + }; +} +exports.FileDescriptorProto = { + fromJSON(object) { + return { + name: isSet(object.name) ? String(object.name) : "", + package: isSet(object.package) ? String(object.package) : "", + dependency: Array.isArray(object?.dependency) ? object.dependency.map((e) => String(e)) : [], + publicDependency: Array.isArray(object?.publicDependency) + ? object.publicDependency.map((e) => Number(e)) + : [], + weakDependency: Array.isArray(object?.weakDependency) ? object.weakDependency.map((e) => Number(e)) : [], + messageType: Array.isArray(object?.messageType) + ? object.messageType.map((e) => exports.DescriptorProto.fromJSON(e)) + : [], + enumType: Array.isArray(object?.enumType) ? object.enumType.map((e) => exports.EnumDescriptorProto.fromJSON(e)) : [], + service: Array.isArray(object?.service) ? object.service.map((e) => exports.ServiceDescriptorProto.fromJSON(e)) : [], + extension: Array.isArray(object?.extension) + ? object.extension.map((e) => exports.FieldDescriptorProto.fromJSON(e)) + : [], + options: isSet(object.options) ? exports.FileOptions.fromJSON(object.options) : undefined, + sourceCodeInfo: isSet(object.sourceCodeInfo) ? exports.SourceCodeInfo.fromJSON(object.sourceCodeInfo) : undefined, + syntax: isSet(object.syntax) ? String(object.syntax) : "", + }; + }, + toJSON(message) { + const obj = {}; + message.name !== undefined && (obj.name = message.name); + message.package !== undefined && (obj.package = message.package); + if (message.dependency) { + obj.dependency = message.dependency.map((e) => e); + } + else { + obj.dependency = []; + } + if (message.publicDependency) { + obj.publicDependency = message.publicDependency.map((e) => Math.round(e)); + } + else { + obj.publicDependency = []; + } + if (message.weakDependency) { + obj.weakDependency = message.weakDependency.map((e) => Math.round(e)); + } + else { + obj.weakDependency = []; + } + if (message.messageType) { + obj.messageType = message.messageType.map((e) => e ? exports.DescriptorProto.toJSON(e) : undefined); + } + else { + obj.messageType = []; + } + if (message.enumType) { + obj.enumType = message.enumType.map((e) => e ? exports.EnumDescriptorProto.toJSON(e) : undefined); + } + else { + obj.enumType = []; + } + if (message.service) { + obj.service = message.service.map((e) => e ? exports.ServiceDescriptorProto.toJSON(e) : undefined); + } + else { + obj.service = []; + } + if (message.extension) { + obj.extension = message.extension.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined); + } + else { + obj.extension = []; + } + message.options !== undefined && (obj.options = message.options ? exports.FileOptions.toJSON(message.options) : undefined); + message.sourceCodeInfo !== undefined && + (obj.sourceCodeInfo = message.sourceCodeInfo ? exports.SourceCodeInfo.toJSON(message.sourceCodeInfo) : undefined); + message.syntax !== undefined && (obj.syntax = message.syntax); + return obj; + }, +}; +function createBaseDescriptorProto() { + return { + name: "", + field: [], + extension: [], + nestedType: [], + enumType: [], + extensionRange: [], + oneofDecl: [], + options: undefined, + reservedRange: [], + reservedName: [], + }; +} +exports.DescriptorProto = { + fromJSON(object) { + return { + name: isSet(object.name) ? String(object.name) : "", + field: Array.isArray(object?.field) ? object.field.map((e) => exports.FieldDescriptorProto.fromJSON(e)) : [], + extension: Array.isArray(object?.extension) + ? object.extension.map((e) => exports.FieldDescriptorProto.fromJSON(e)) + : [], + nestedType: Array.isArray(object?.nestedType) + ? object.nestedType.map((e) => exports.DescriptorProto.fromJSON(e)) + : [], + enumType: Array.isArray(object?.enumType) ? object.enumType.map((e) => exports.EnumDescriptorProto.fromJSON(e)) : [], + extensionRange: Array.isArray(object?.extensionRange) + ? object.extensionRange.map((e) => exports.DescriptorProto_ExtensionRange.fromJSON(e)) + : [], + oneofDecl: Array.isArray(object?.oneofDecl) + ? object.oneofDecl.map((e) => exports.OneofDescriptorProto.fromJSON(e)) + : [], + options: isSet(object.options) ? exports.MessageOptions.fromJSON(object.options) : undefined, + reservedRange: Array.isArray(object?.reservedRange) + ? object.reservedRange.map((e) => exports.DescriptorProto_ReservedRange.fromJSON(e)) + : [], + reservedName: Array.isArray(object?.reservedName) ? object.reservedName.map((e) => String(e)) : [], + }; + }, + toJSON(message) { + const obj = {}; + message.name !== undefined && (obj.name = message.name); + if (message.field) { + obj.field = message.field.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined); + } + else { + obj.field = []; + } + if (message.extension) { + obj.extension = message.extension.map((e) => e ? exports.FieldDescriptorProto.toJSON(e) : undefined); + } + else { + obj.extension = []; + } + if (message.nestedType) { + obj.nestedType = message.nestedType.map((e) => e ? exports.DescriptorProto.toJSON(e) : undefined); + } + else { + obj.nestedType = []; + } + if (message.enumType) { + obj.enumType = message.enumType.map((e) => e ? exports.EnumDescriptorProto.toJSON(e) : undefined); + } + else { + obj.enumType = []; + } + if (message.extensionRange) { + obj.extensionRange = message.extensionRange.map((e) => e ? exports.DescriptorProto_ExtensionRange.toJSON(e) : undefined); + } + else { + obj.extensionRange = []; + } + if (message.oneofDecl) { + obj.oneofDecl = message.oneofDecl.map((e) => e ? exports.OneofDescriptorProto.toJSON(e) : undefined); + } + else { + obj.oneofDecl = []; + } + message.options !== undefined && + (obj.options = message.options ? exports.MessageOptions.toJSON(message.options) : undefined); + if (message.reservedRange) { + obj.reservedRange = message.reservedRange.map((e) => e ? exports.DescriptorProto_ReservedRange.toJSON(e) : undefined); + } + else { + obj.reservedRange = []; + } + if (message.reservedName) { + obj.reservedName = message.reservedName.map((e) => e); + } + else { + obj.reservedName = []; + } + return obj; + }, +}; +function createBaseDescriptorProto_ExtensionRange() { + return { start: 0, end: 0, options: undefined }; +} +exports.DescriptorProto_ExtensionRange = { + fromJSON(object) { + return { + start: isSet(object.start) ? Number(object.start) : 0, + end: isSet(object.end) ? Number(object.end) : 0, + options: isSet(object.options) ? exports.ExtensionRangeOptions.fromJSON(object.options) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.start !== undefined && (obj.start = Math.round(message.start)); + message.end !== undefined && (obj.end = Math.round(message.end)); + message.options !== undefined && + (obj.options = message.options ? exports.ExtensionRangeOptions.toJSON(message.options) : undefined); + return obj; + }, +}; +function createBaseDescriptorProto_ReservedRange() { + return { start: 0, end: 0 }; +} +exports.DescriptorProto_ReservedRange = { + fromJSON(object) { + return { start: isSet(object.start) ? Number(object.start) : 0, end: isSet(object.end) ? Number(object.end) : 0 }; + }, + toJSON(message) { + const obj = {}; + message.start !== undefined && (obj.start = Math.round(message.start)); + message.end !== undefined && (obj.end = Math.round(message.end)); + return obj; + }, +}; +function createBaseExtensionRangeOptions() { + return { uninterpretedOption: [] }; +} +exports.ExtensionRangeOptions = { + fromJSON(object) { + return { + uninterpretedOption: Array.isArray(object?.uninterpretedOption) + ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.uninterpretedOption) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); + } + else { + obj.uninterpretedOption = []; + } + return obj; + }, +}; +function createBaseFieldDescriptorProto() { + return { + name: "", + number: 0, + label: 1, + type: 1, + typeName: "", + extendee: "", + defaultValue: "", + oneofIndex: 0, + jsonName: "", + options: undefined, + proto3Optional: false, + }; +} +exports.FieldDescriptorProto = { + fromJSON(object) { + return { + name: isSet(object.name) ? String(object.name) : "", + number: isSet(object.number) ? Number(object.number) : 0, + label: isSet(object.label) ? fieldDescriptorProto_LabelFromJSON(object.label) : 1, + type: isSet(object.type) ? fieldDescriptorProto_TypeFromJSON(object.type) : 1, + typeName: isSet(object.typeName) ? String(object.typeName) : "", + extendee: isSet(object.extendee) ? String(object.extendee) : "", + defaultValue: isSet(object.defaultValue) ? String(object.defaultValue) : "", + oneofIndex: isSet(object.oneofIndex) ? Number(object.oneofIndex) : 0, + jsonName: isSet(object.jsonName) ? String(object.jsonName) : "", + options: isSet(object.options) ? exports.FieldOptions.fromJSON(object.options) : undefined, + proto3Optional: isSet(object.proto3Optional) ? Boolean(object.proto3Optional) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.name !== undefined && (obj.name = message.name); + message.number !== undefined && (obj.number = Math.round(message.number)); + message.label !== undefined && (obj.label = fieldDescriptorProto_LabelToJSON(message.label)); + message.type !== undefined && (obj.type = fieldDescriptorProto_TypeToJSON(message.type)); + message.typeName !== undefined && (obj.typeName = message.typeName); + message.extendee !== undefined && (obj.extendee = message.extendee); + message.defaultValue !== undefined && (obj.defaultValue = message.defaultValue); + message.oneofIndex !== undefined && (obj.oneofIndex = Math.round(message.oneofIndex)); + message.jsonName !== undefined && (obj.jsonName = message.jsonName); + message.options !== undefined && (obj.options = message.options ? exports.FieldOptions.toJSON(message.options) : undefined); + message.proto3Optional !== undefined && (obj.proto3Optional = message.proto3Optional); + return obj; + }, +}; +function createBaseOneofDescriptorProto() { + return { name: "", options: undefined }; +} +exports.OneofDescriptorProto = { + fromJSON(object) { + return { + name: isSet(object.name) ? String(object.name) : "", + options: isSet(object.options) ? exports.OneofOptions.fromJSON(object.options) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.name !== undefined && (obj.name = message.name); + message.options !== undefined && (obj.options = message.options ? exports.OneofOptions.toJSON(message.options) : undefined); + return obj; + }, +}; +function createBaseEnumDescriptorProto() { + return { name: "", value: [], options: undefined, reservedRange: [], reservedName: [] }; +} +exports.EnumDescriptorProto = { + fromJSON(object) { + return { + name: isSet(object.name) ? String(object.name) : "", + value: Array.isArray(object?.value) ? object.value.map((e) => exports.EnumValueDescriptorProto.fromJSON(e)) : [], + options: isSet(object.options) ? exports.EnumOptions.fromJSON(object.options) : undefined, + reservedRange: Array.isArray(object?.reservedRange) + ? object.reservedRange.map((e) => exports.EnumDescriptorProto_EnumReservedRange.fromJSON(e)) + : [], + reservedName: Array.isArray(object?.reservedName) + ? object.reservedName.map((e) => String(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + message.name !== undefined && (obj.name = message.name); + if (message.value) { + obj.value = message.value.map((e) => e ? exports.EnumValueDescriptorProto.toJSON(e) : undefined); + } + else { + obj.value = []; + } + message.options !== undefined && (obj.options = message.options ? exports.EnumOptions.toJSON(message.options) : undefined); + if (message.reservedRange) { + obj.reservedRange = message.reservedRange.map((e) => e ? exports.EnumDescriptorProto_EnumReservedRange.toJSON(e) : undefined); + } + else { + obj.reservedRange = []; + } + if (message.reservedName) { + obj.reservedName = message.reservedName.map((e) => e); + } + else { + obj.reservedName = []; + } + return obj; + }, +}; +function createBaseEnumDescriptorProto_EnumReservedRange() { + return { start: 0, end: 0 }; +} +exports.EnumDescriptorProto_EnumReservedRange = { + fromJSON(object) { + return { start: isSet(object.start) ? Number(object.start) : 0, end: isSet(object.end) ? Number(object.end) : 0 }; + }, + toJSON(message) { + const obj = {}; + message.start !== undefined && (obj.start = Math.round(message.start)); + message.end !== undefined && (obj.end = Math.round(message.end)); + return obj; + }, +}; +function createBaseEnumValueDescriptorProto() { + return { name: "", number: 0, options: undefined }; +} +exports.EnumValueDescriptorProto = { + fromJSON(object) { + return { + name: isSet(object.name) ? String(object.name) : "", + number: isSet(object.number) ? Number(object.number) : 0, + options: isSet(object.options) ? exports.EnumValueOptions.fromJSON(object.options) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.name !== undefined && (obj.name = message.name); + message.number !== undefined && (obj.number = Math.round(message.number)); + message.options !== undefined && + (obj.options = message.options ? exports.EnumValueOptions.toJSON(message.options) : undefined); + return obj; + }, +}; +function createBaseServiceDescriptorProto() { + return { name: "", method: [], options: undefined }; +} +exports.ServiceDescriptorProto = { + fromJSON(object) { + return { + name: isSet(object.name) ? String(object.name) : "", + method: Array.isArray(object?.method) ? object.method.map((e) => exports.MethodDescriptorProto.fromJSON(e)) : [], + options: isSet(object.options) ? exports.ServiceOptions.fromJSON(object.options) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.name !== undefined && (obj.name = message.name); + if (message.method) { + obj.method = message.method.map((e) => e ? exports.MethodDescriptorProto.toJSON(e) : undefined); + } + else { + obj.method = []; + } + message.options !== undefined && + (obj.options = message.options ? exports.ServiceOptions.toJSON(message.options) : undefined); + return obj; + }, +}; +function createBaseMethodDescriptorProto() { + return { + name: "", + inputType: "", + outputType: "", + options: undefined, + clientStreaming: false, + serverStreaming: false, + }; +} +exports.MethodDescriptorProto = { + fromJSON(object) { + return { + name: isSet(object.name) ? String(object.name) : "", + inputType: isSet(object.inputType) ? String(object.inputType) : "", + outputType: isSet(object.outputType) ? String(object.outputType) : "", + options: isSet(object.options) ? exports.MethodOptions.fromJSON(object.options) : undefined, + clientStreaming: isSet(object.clientStreaming) ? Boolean(object.clientStreaming) : false, + serverStreaming: isSet(object.serverStreaming) ? Boolean(object.serverStreaming) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.name !== undefined && (obj.name = message.name); + message.inputType !== undefined && (obj.inputType = message.inputType); + message.outputType !== undefined && (obj.outputType = message.outputType); + message.options !== undefined && + (obj.options = message.options ? exports.MethodOptions.toJSON(message.options) : undefined); + message.clientStreaming !== undefined && (obj.clientStreaming = message.clientStreaming); + message.serverStreaming !== undefined && (obj.serverStreaming = message.serverStreaming); + return obj; + }, +}; +function createBaseFileOptions() { + return { + javaPackage: "", + javaOuterClassname: "", + javaMultipleFiles: false, + javaGenerateEqualsAndHash: false, + javaStringCheckUtf8: false, + optimizeFor: 1, + goPackage: "", + ccGenericServices: false, + javaGenericServices: false, + pyGenericServices: false, + phpGenericServices: false, + deprecated: false, + ccEnableArenas: false, + objcClassPrefix: "", + csharpNamespace: "", + swiftPrefix: "", + phpClassPrefix: "", + phpNamespace: "", + phpMetadataNamespace: "", + rubyPackage: "", + uninterpretedOption: [], + }; +} +exports.FileOptions = { + fromJSON(object) { + return { + javaPackage: isSet(object.javaPackage) ? String(object.javaPackage) : "", + javaOuterClassname: isSet(object.javaOuterClassname) ? String(object.javaOuterClassname) : "", + javaMultipleFiles: isSet(object.javaMultipleFiles) ? Boolean(object.javaMultipleFiles) : false, + javaGenerateEqualsAndHash: isSet(object.javaGenerateEqualsAndHash) + ? Boolean(object.javaGenerateEqualsAndHash) + : false, + javaStringCheckUtf8: isSet(object.javaStringCheckUtf8) ? Boolean(object.javaStringCheckUtf8) : false, + optimizeFor: isSet(object.optimizeFor) ? fileOptions_OptimizeModeFromJSON(object.optimizeFor) : 1, + goPackage: isSet(object.goPackage) ? String(object.goPackage) : "", + ccGenericServices: isSet(object.ccGenericServices) ? Boolean(object.ccGenericServices) : false, + javaGenericServices: isSet(object.javaGenericServices) ? Boolean(object.javaGenericServices) : false, + pyGenericServices: isSet(object.pyGenericServices) ? Boolean(object.pyGenericServices) : false, + phpGenericServices: isSet(object.phpGenericServices) ? Boolean(object.phpGenericServices) : false, + deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, + ccEnableArenas: isSet(object.ccEnableArenas) ? Boolean(object.ccEnableArenas) : false, + objcClassPrefix: isSet(object.objcClassPrefix) ? String(object.objcClassPrefix) : "", + csharpNamespace: isSet(object.csharpNamespace) ? String(object.csharpNamespace) : "", + swiftPrefix: isSet(object.swiftPrefix) ? String(object.swiftPrefix) : "", + phpClassPrefix: isSet(object.phpClassPrefix) ? String(object.phpClassPrefix) : "", + phpNamespace: isSet(object.phpNamespace) ? String(object.phpNamespace) : "", + phpMetadataNamespace: isSet(object.phpMetadataNamespace) ? String(object.phpMetadataNamespace) : "", + rubyPackage: isSet(object.rubyPackage) ? String(object.rubyPackage) : "", + uninterpretedOption: Array.isArray(object?.uninterpretedOption) + ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + message.javaPackage !== undefined && (obj.javaPackage = message.javaPackage); + message.javaOuterClassname !== undefined && (obj.javaOuterClassname = message.javaOuterClassname); + message.javaMultipleFiles !== undefined && (obj.javaMultipleFiles = message.javaMultipleFiles); + message.javaGenerateEqualsAndHash !== undefined && + (obj.javaGenerateEqualsAndHash = message.javaGenerateEqualsAndHash); + message.javaStringCheckUtf8 !== undefined && (obj.javaStringCheckUtf8 = message.javaStringCheckUtf8); + message.optimizeFor !== undefined && (obj.optimizeFor = fileOptions_OptimizeModeToJSON(message.optimizeFor)); + message.goPackage !== undefined && (obj.goPackage = message.goPackage); + message.ccGenericServices !== undefined && (obj.ccGenericServices = message.ccGenericServices); + message.javaGenericServices !== undefined && (obj.javaGenericServices = message.javaGenericServices); + message.pyGenericServices !== undefined && (obj.pyGenericServices = message.pyGenericServices); + message.phpGenericServices !== undefined && (obj.phpGenericServices = message.phpGenericServices); + message.deprecated !== undefined && (obj.deprecated = message.deprecated); + message.ccEnableArenas !== undefined && (obj.ccEnableArenas = message.ccEnableArenas); + message.objcClassPrefix !== undefined && (obj.objcClassPrefix = message.objcClassPrefix); + message.csharpNamespace !== undefined && (obj.csharpNamespace = message.csharpNamespace); + message.swiftPrefix !== undefined && (obj.swiftPrefix = message.swiftPrefix); + message.phpClassPrefix !== undefined && (obj.phpClassPrefix = message.phpClassPrefix); + message.phpNamespace !== undefined && (obj.phpNamespace = message.phpNamespace); + message.phpMetadataNamespace !== undefined && (obj.phpMetadataNamespace = message.phpMetadataNamespace); + message.rubyPackage !== undefined && (obj.rubyPackage = message.rubyPackage); + if (message.uninterpretedOption) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); + } + else { + obj.uninterpretedOption = []; + } + return obj; + }, +}; +function createBaseMessageOptions() { + return { + messageSetWireFormat: false, + noStandardDescriptorAccessor: false, + deprecated: false, + mapEntry: false, + uninterpretedOption: [], + }; +} +exports.MessageOptions = { + fromJSON(object) { + return { + messageSetWireFormat: isSet(object.messageSetWireFormat) ? Boolean(object.messageSetWireFormat) : false, + noStandardDescriptorAccessor: isSet(object.noStandardDescriptorAccessor) + ? Boolean(object.noStandardDescriptorAccessor) + : false, + deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, + mapEntry: isSet(object.mapEntry) ? Boolean(object.mapEntry) : false, + uninterpretedOption: Array.isArray(object?.uninterpretedOption) + ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + message.messageSetWireFormat !== undefined && (obj.messageSetWireFormat = message.messageSetWireFormat); + message.noStandardDescriptorAccessor !== undefined && + (obj.noStandardDescriptorAccessor = message.noStandardDescriptorAccessor); + message.deprecated !== undefined && (obj.deprecated = message.deprecated); + message.mapEntry !== undefined && (obj.mapEntry = message.mapEntry); + if (message.uninterpretedOption) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); + } + else { + obj.uninterpretedOption = []; + } + return obj; + }, +}; +function createBaseFieldOptions() { + return { + ctype: 0, + packed: false, + jstype: 0, + lazy: false, + unverifiedLazy: false, + deprecated: false, + weak: false, + uninterpretedOption: [], + }; +} +exports.FieldOptions = { + fromJSON(object) { + return { + ctype: isSet(object.ctype) ? fieldOptions_CTypeFromJSON(object.ctype) : 0, + packed: isSet(object.packed) ? Boolean(object.packed) : false, + jstype: isSet(object.jstype) ? fieldOptions_JSTypeFromJSON(object.jstype) : 0, + lazy: isSet(object.lazy) ? Boolean(object.lazy) : false, + unverifiedLazy: isSet(object.unverifiedLazy) ? Boolean(object.unverifiedLazy) : false, + deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, + weak: isSet(object.weak) ? Boolean(object.weak) : false, + uninterpretedOption: Array.isArray(object?.uninterpretedOption) + ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + message.ctype !== undefined && (obj.ctype = fieldOptions_CTypeToJSON(message.ctype)); + message.packed !== undefined && (obj.packed = message.packed); + message.jstype !== undefined && (obj.jstype = fieldOptions_JSTypeToJSON(message.jstype)); + message.lazy !== undefined && (obj.lazy = message.lazy); + message.unverifiedLazy !== undefined && (obj.unverifiedLazy = message.unverifiedLazy); + message.deprecated !== undefined && (obj.deprecated = message.deprecated); + message.weak !== undefined && (obj.weak = message.weak); + if (message.uninterpretedOption) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); + } + else { + obj.uninterpretedOption = []; + } + return obj; + }, +}; +function createBaseOneofOptions() { + return { uninterpretedOption: [] }; +} +exports.OneofOptions = { + fromJSON(object) { + return { + uninterpretedOption: Array.isArray(object?.uninterpretedOption) + ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.uninterpretedOption) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); + } + else { + obj.uninterpretedOption = []; + } + return obj; + }, +}; +function createBaseEnumOptions() { + return { allowAlias: false, deprecated: false, uninterpretedOption: [] }; +} +exports.EnumOptions = { + fromJSON(object) { + return { + allowAlias: isSet(object.allowAlias) ? Boolean(object.allowAlias) : false, + deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, + uninterpretedOption: Array.isArray(object?.uninterpretedOption) + ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + message.allowAlias !== undefined && (obj.allowAlias = message.allowAlias); + message.deprecated !== undefined && (obj.deprecated = message.deprecated); + if (message.uninterpretedOption) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); + } + else { + obj.uninterpretedOption = []; + } + return obj; + }, +}; +function createBaseEnumValueOptions() { + return { deprecated: false, uninterpretedOption: [] }; +} +exports.EnumValueOptions = { + fromJSON(object) { + return { + deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, + uninterpretedOption: Array.isArray(object?.uninterpretedOption) + ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + message.deprecated !== undefined && (obj.deprecated = message.deprecated); + if (message.uninterpretedOption) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); + } + else { + obj.uninterpretedOption = []; + } + return obj; + }, +}; +function createBaseServiceOptions() { + return { deprecated: false, uninterpretedOption: [] }; +} +exports.ServiceOptions = { + fromJSON(object) { + return { + deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, + uninterpretedOption: Array.isArray(object?.uninterpretedOption) + ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + message.deprecated !== undefined && (obj.deprecated = message.deprecated); + if (message.uninterpretedOption) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); + } + else { + obj.uninterpretedOption = []; + } + return obj; + }, +}; +function createBaseMethodOptions() { + return { deprecated: false, idempotencyLevel: 0, uninterpretedOption: [] }; +} +exports.MethodOptions = { + fromJSON(object) { + return { + deprecated: isSet(object.deprecated) ? Boolean(object.deprecated) : false, + idempotencyLevel: isSet(object.idempotencyLevel) + ? methodOptions_IdempotencyLevelFromJSON(object.idempotencyLevel) + : 0, + uninterpretedOption: Array.isArray(object?.uninterpretedOption) + ? object.uninterpretedOption.map((e) => exports.UninterpretedOption.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + message.deprecated !== undefined && (obj.deprecated = message.deprecated); + message.idempotencyLevel !== undefined && + (obj.idempotencyLevel = methodOptions_IdempotencyLevelToJSON(message.idempotencyLevel)); + if (message.uninterpretedOption) { + obj.uninterpretedOption = message.uninterpretedOption.map((e) => e ? exports.UninterpretedOption.toJSON(e) : undefined); + } + else { + obj.uninterpretedOption = []; + } + return obj; + }, +}; +function createBaseUninterpretedOption() { + return { + name: [], + identifierValue: "", + positiveIntValue: "0", + negativeIntValue: "0", + doubleValue: 0, + stringValue: Buffer.alloc(0), + aggregateValue: "", + }; +} +exports.UninterpretedOption = { + fromJSON(object) { + return { + name: Array.isArray(object?.name) ? object.name.map((e) => exports.UninterpretedOption_NamePart.fromJSON(e)) : [], + identifierValue: isSet(object.identifierValue) ? String(object.identifierValue) : "", + positiveIntValue: isSet(object.positiveIntValue) ? String(object.positiveIntValue) : "0", + negativeIntValue: isSet(object.negativeIntValue) ? String(object.negativeIntValue) : "0", + doubleValue: isSet(object.doubleValue) ? Number(object.doubleValue) : 0, + stringValue: isSet(object.stringValue) ? Buffer.from(bytesFromBase64(object.stringValue)) : Buffer.alloc(0), + aggregateValue: isSet(object.aggregateValue) ? String(object.aggregateValue) : "", + }; + }, + toJSON(message) { + const obj = {}; + if (message.name) { + obj.name = message.name.map((e) => e ? exports.UninterpretedOption_NamePart.toJSON(e) : undefined); + } + else { + obj.name = []; + } + message.identifierValue !== undefined && (obj.identifierValue = message.identifierValue); + message.positiveIntValue !== undefined && (obj.positiveIntValue = message.positiveIntValue); + message.negativeIntValue !== undefined && (obj.negativeIntValue = message.negativeIntValue); + message.doubleValue !== undefined && (obj.doubleValue = message.doubleValue); + message.stringValue !== undefined && + (obj.stringValue = base64FromBytes(message.stringValue !== undefined ? message.stringValue : Buffer.alloc(0))); + message.aggregateValue !== undefined && (obj.aggregateValue = message.aggregateValue); + return obj; + }, +}; +function createBaseUninterpretedOption_NamePart() { + return { namePart: "", isExtension: false }; +} +exports.UninterpretedOption_NamePart = { + fromJSON(object) { + return { + namePart: isSet(object.namePart) ? String(object.namePart) : "", + isExtension: isSet(object.isExtension) ? Boolean(object.isExtension) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.namePart !== undefined && (obj.namePart = message.namePart); + message.isExtension !== undefined && (obj.isExtension = message.isExtension); + return obj; + }, +}; +function createBaseSourceCodeInfo() { + return { location: [] }; +} +exports.SourceCodeInfo = { + fromJSON(object) { + return { + location: Array.isArray(object?.location) + ? object.location.map((e) => exports.SourceCodeInfo_Location.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.location) { + obj.location = message.location.map((e) => e ? exports.SourceCodeInfo_Location.toJSON(e) : undefined); + } + else { + obj.location = []; + } + return obj; + }, +}; +function createBaseSourceCodeInfo_Location() { + return { path: [], span: [], leadingComments: "", trailingComments: "", leadingDetachedComments: [] }; +} +exports.SourceCodeInfo_Location = { + fromJSON(object) { + return { + path: Array.isArray(object?.path) ? object.path.map((e) => Number(e)) : [], + span: Array.isArray(object?.span) ? object.span.map((e) => Number(e)) : [], + leadingComments: isSet(object.leadingComments) ? String(object.leadingComments) : "", + trailingComments: isSet(object.trailingComments) ? String(object.trailingComments) : "", + leadingDetachedComments: Array.isArray(object?.leadingDetachedComments) + ? object.leadingDetachedComments.map((e) => String(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.path) { + obj.path = message.path.map((e) => Math.round(e)); + } + else { + obj.path = []; + } + if (message.span) { + obj.span = message.span.map((e) => Math.round(e)); + } + else { + obj.span = []; + } + message.leadingComments !== undefined && (obj.leadingComments = message.leadingComments); + message.trailingComments !== undefined && (obj.trailingComments = message.trailingComments); + if (message.leadingDetachedComments) { + obj.leadingDetachedComments = message.leadingDetachedComments.map((e) => e); + } + else { + obj.leadingDetachedComments = []; + } + return obj; + }, +}; +function createBaseGeneratedCodeInfo() { + return { annotation: [] }; +} +exports.GeneratedCodeInfo = { + fromJSON(object) { + return { + annotation: Array.isArray(object?.annotation) + ? object.annotation.map((e) => exports.GeneratedCodeInfo_Annotation.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.annotation) { + obj.annotation = message.annotation.map((e) => e ? exports.GeneratedCodeInfo_Annotation.toJSON(e) : undefined); + } + else { + obj.annotation = []; + } + return obj; + }, +}; +function createBaseGeneratedCodeInfo_Annotation() { + return { path: [], sourceFile: "", begin: 0, end: 0 }; +} +exports.GeneratedCodeInfo_Annotation = { + fromJSON(object) { + return { + path: Array.isArray(object?.path) ? object.path.map((e) => Number(e)) : [], + sourceFile: isSet(object.sourceFile) ? String(object.sourceFile) : "", + begin: isSet(object.begin) ? Number(object.begin) : 0, + end: isSet(object.end) ? Number(object.end) : 0, + }; + }, + toJSON(message) { + const obj = {}; + if (message.path) { + obj.path = message.path.map((e) => Math.round(e)); + } + else { + obj.path = []; + } + message.sourceFile !== undefined && (obj.sourceFile = message.sourceFile); + message.begin !== undefined && (obj.begin = Math.round(message.begin)); + message.end !== undefined && (obj.end = Math.round(message.end)); + return obj; + }, +}; +var globalThis = (() => { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw "Unable to locate global object"; +})(); +function bytesFromBase64(b64) { + if (globalThis.Buffer) { + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); + } + else { + const bin = globalThis.atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; ++i) { + arr[i] = bin.charCodeAt(i); + } + return arr; + } +} +function base64FromBytes(arr) { + if (globalThis.Buffer) { + return globalThis.Buffer.from(arr).toString("base64"); + } + else { + const bin = []; + arr.forEach((byte) => { + bin.push(String.fromCharCode(byte)); + }); + return globalThis.btoa(bin.join("")); + } +} +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/timestamp.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/timestamp.d.ts new file mode 100644 index 0000000..1ab812b --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/timestamp.d.ts @@ -0,0 +1,110 @@ +/** + * A Timestamp represents a point in time independent of any time zone or local + * calendar, encoded as a count of seconds and fractions of seconds at + * nanosecond resolution. The count is relative to an epoch at UTC midnight on + * January 1, 1970, in the proleptic Gregorian calendar which extends the + * Gregorian calendar backwards to year one. + * + * All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap + * second table is needed for interpretation, using a [24-hour linear + * smear](https://developers.google.com/time/smear). + * + * The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By + * restricting to that range, we ensure that we can convert to and from [RFC + * 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. + * + * # Examples + * + * Example 1: Compute Timestamp from POSIX `time()`. + * + * Timestamp timestamp; + * timestamp.set_seconds(time(NULL)); + * timestamp.set_nanos(0); + * + * Example 2: Compute Timestamp from POSIX `gettimeofday()`. + * + * struct timeval tv; + * gettimeofday(&tv, NULL); + * + * Timestamp timestamp; + * timestamp.set_seconds(tv.tv_sec); + * timestamp.set_nanos(tv.tv_usec * 1000); + * + * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. + * + * FILETIME ft; + * GetSystemTimeAsFileTime(&ft); + * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; + * + * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z + * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. + * Timestamp timestamp; + * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); + * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); + * + * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. + * + * long millis = System.currentTimeMillis(); + * + * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) + * .setNanos((int) ((millis % 1000) * 1000000)).build(); + * + * Example 5: Compute Timestamp from Java `Instant.now()`. + * + * Instant now = Instant.now(); + * + * Timestamp timestamp = + * Timestamp.newBuilder().setSeconds(now.getEpochSecond()) + * .setNanos(now.getNano()).build(); + * + * Example 6: Compute Timestamp from current time in Python. + * + * timestamp = Timestamp() + * timestamp.GetCurrentTime() + * + * # JSON Mapping + * + * In JSON format, the Timestamp type is encoded as a string in the + * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the + * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" + * where {year} is always expressed using four digits while {month}, {day}, + * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional + * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), + * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone + * is required. A proto3 JSON serializer should always use UTC (as indicated by + * "Z") when printing the Timestamp type and a proto3 JSON parser should be + * able to accept both UTC and other timezones (as indicated by an offset). + * + * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past + * 01:30 UTC on January 15, 2017. + * + * In JavaScript, one can convert a Date object to this format using the + * standard + * [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) + * method. In Python, a standard `datetime.datetime` object can be converted + * to this format using + * [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with + * the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use + * the Joda Time's [`ISODateTimeFormat.dateTime()`]( + * http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D + * ) to obtain a formatter capable of generating timestamps in this format. + */ +export interface Timestamp { + /** + * Represents seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + */ + seconds: string; + /** + * Non-negative fractions of a second at nanosecond resolution. Negative + * second values with fractions must still have non-negative nanos values + * that count forward in time. Must be from 0 to 999,999,999 + * inclusive. + */ + nanos: number; +} +export declare const Timestamp: { + fromJSON(object: any): Timestamp; + toJSON(message: Timestamp): unknown; +}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/timestamp.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/timestamp.js new file mode 100644 index 0000000..159135f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/google/protobuf/timestamp.js @@ -0,0 +1,24 @@ +"use strict"; +/* eslint-disable */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Timestamp = void 0; +function createBaseTimestamp() { + return { seconds: "0", nanos: 0 }; +} +exports.Timestamp = { + fromJSON(object) { + return { + seconds: isSet(object.seconds) ? String(object.seconds) : "0", + nanos: isSet(object.nanos) ? Number(object.nanos) : 0, + }; + }, + toJSON(message) { + const obj = {}; + message.seconds !== undefined && (obj.seconds = message.seconds); + message.nanos !== undefined && (obj.nanos = Math.round(message.nanos)); + return obj; + }, +}; +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_bundle.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_bundle.d.ts new file mode 100644 index 0000000..51f748f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_bundle.d.ts @@ -0,0 +1,72 @@ +import { Envelope } from "./envelope"; +import { MessageSignature, PublicKeyIdentifier, RFC3161SignedTimestamp, X509CertificateChain } from "./sigstore_common"; +import { TransparencyLogEntry } from "./sigstore_rekor"; +/** + * Various timestamped counter signatures over the artifacts signature. + * Currently only RFC3161 signatures are provided. More formats may be added + * in the future. + */ +export interface TimestampVerificationData { + /** + * A list of RFC3161 signed timestamps provided by the user. + * This can be used when the entry has not been stored on a + * transparency log, or in conjunction for a stronger trust model. + * Clients MUST verify the hashed message in the message imprint + * against the signature in the bundle. + */ + rfc3161Timestamps: RFC3161SignedTimestamp[]; +} +/** + * VerificationMaterial captures details on the materials used to verify + * signatures. + */ +export interface VerificationMaterial { + content?: { + $case: "publicKey"; + publicKey: PublicKeyIdentifier; + } | { + $case: "x509CertificateChain"; + x509CertificateChain: X509CertificateChain; + }; + /** + * This is the inclusion promise and/or proof, where + * the timestamp is coming from the transparency log. + */ + tlogEntries: TransparencyLogEntry[]; + /** Timestamp verification data, over the artifact's signature. */ + timestampVerificationData: TimestampVerificationData | undefined; +} +export interface Bundle { + /** + * MUST be application/vnd.dev.sigstore.bundle+json;version=0.1 + * when encoded as JSON. + */ + mediaType: string; + /** + * When a signer is identified by a X.509 certificate, a verifier MUST + * verify that the signature was computed at the time the certificate + * was valid as described in the Sigstore client spec: "Verification + * using a Bundle". + * + */ + verificationMaterial: VerificationMaterial | undefined; + content?: { + $case: "messageSignature"; + messageSignature: MessageSignature; + } | { + $case: "dsseEnvelope"; + dsseEnvelope: Envelope; + }; +} +export declare const TimestampVerificationData: { + fromJSON(object: any): TimestampVerificationData; + toJSON(message: TimestampVerificationData): unknown; +}; +export declare const VerificationMaterial: { + fromJSON(object: any): VerificationMaterial; + toJSON(message: VerificationMaterial): unknown; +}; +export declare const Bundle: { + fromJSON(object: any): Bundle; + toJSON(message: Bundle): unknown; +}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_bundle.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_bundle.js new file mode 100644 index 0000000..1ef3e1b --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_bundle.js @@ -0,0 +1,106 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Bundle = exports.VerificationMaterial = exports.TimestampVerificationData = void 0; +/* eslint-disable */ +const envelope_1 = require("./envelope"); +const sigstore_common_1 = require("./sigstore_common"); +const sigstore_rekor_1 = require("./sigstore_rekor"); +function createBaseTimestampVerificationData() { + return { rfc3161Timestamps: [] }; +} +exports.TimestampVerificationData = { + fromJSON(object) { + return { + rfc3161Timestamps: Array.isArray(object?.rfc3161Timestamps) + ? object.rfc3161Timestamps.map((e) => sigstore_common_1.RFC3161SignedTimestamp.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.rfc3161Timestamps) { + obj.rfc3161Timestamps = message.rfc3161Timestamps.map((e) => e ? sigstore_common_1.RFC3161SignedTimestamp.toJSON(e) : undefined); + } + else { + obj.rfc3161Timestamps = []; + } + return obj; + }, +}; +function createBaseVerificationMaterial() { + return { content: undefined, tlogEntries: [], timestampVerificationData: undefined }; +} +exports.VerificationMaterial = { + fromJSON(object) { + return { + content: isSet(object.publicKey) + ? { $case: "publicKey", publicKey: sigstore_common_1.PublicKeyIdentifier.fromJSON(object.publicKey) } + : isSet(object.x509CertificateChain) + ? { + $case: "x509CertificateChain", + x509CertificateChain: sigstore_common_1.X509CertificateChain.fromJSON(object.x509CertificateChain), + } + : undefined, + tlogEntries: Array.isArray(object?.tlogEntries) + ? object.tlogEntries.map((e) => sigstore_rekor_1.TransparencyLogEntry.fromJSON(e)) + : [], + timestampVerificationData: isSet(object.timestampVerificationData) + ? exports.TimestampVerificationData.fromJSON(object.timestampVerificationData) + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.content?.$case === "publicKey" && + (obj.publicKey = message.content?.publicKey ? sigstore_common_1.PublicKeyIdentifier.toJSON(message.content?.publicKey) : undefined); + message.content?.$case === "x509CertificateChain" && + (obj.x509CertificateChain = message.content?.x509CertificateChain + ? sigstore_common_1.X509CertificateChain.toJSON(message.content?.x509CertificateChain) + : undefined); + if (message.tlogEntries) { + obj.tlogEntries = message.tlogEntries.map((e) => e ? sigstore_rekor_1.TransparencyLogEntry.toJSON(e) : undefined); + } + else { + obj.tlogEntries = []; + } + message.timestampVerificationData !== undefined && + (obj.timestampVerificationData = message.timestampVerificationData + ? exports.TimestampVerificationData.toJSON(message.timestampVerificationData) + : undefined); + return obj; + }, +}; +function createBaseBundle() { + return { mediaType: "", verificationMaterial: undefined, content: undefined }; +} +exports.Bundle = { + fromJSON(object) { + return { + mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", + verificationMaterial: isSet(object.verificationMaterial) + ? exports.VerificationMaterial.fromJSON(object.verificationMaterial) + : undefined, + content: isSet(object.messageSignature) + ? { $case: "messageSignature", messageSignature: sigstore_common_1.MessageSignature.fromJSON(object.messageSignature) } + : isSet(object.dsseEnvelope) + ? { $case: "dsseEnvelope", dsseEnvelope: envelope_1.Envelope.fromJSON(object.dsseEnvelope) } + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.mediaType !== undefined && (obj.mediaType = message.mediaType); + message.verificationMaterial !== undefined && (obj.verificationMaterial = message.verificationMaterial + ? exports.VerificationMaterial.toJSON(message.verificationMaterial) + : undefined); + message.content?.$case === "messageSignature" && (obj.messageSignature = message.content?.messageSignature + ? sigstore_common_1.MessageSignature.toJSON(message.content?.messageSignature) + : undefined); + message.content?.$case === "dsseEnvelope" && + (obj.dsseEnvelope = message.content?.dsseEnvelope ? envelope_1.Envelope.toJSON(message.content?.dsseEnvelope) : undefined); + return obj; + }, +}; +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_common.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_common.d.ts new file mode 100644 index 0000000..0d8c2d5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_common.d.ts @@ -0,0 +1,228 @@ +/// +/** + * Only a subset of the secure hash standard algorithms are supported. + * See for more + * details. + * UNSPECIFIED SHOULD not be used, primary reason for inclusion is to force + * any proto JSON serialization to emit the used hash algorithm, as default + * option is to *omit* the default value of an enum (which is the first + * value, represented by '0'. + */ +export declare enum HashAlgorithm { + HASH_ALGORITHM_UNSPECIFIED = 0, + SHA2_256 = 1 +} +export declare function hashAlgorithmFromJSON(object: any): HashAlgorithm; +export declare function hashAlgorithmToJSON(object: HashAlgorithm): string; +/** + * Details of a specific public key, capturing the the key encoding method, + * and signature algorithm. + * To avoid the possibility of contradicting formats such as PKCS1 with + * ED25519 the valid permutations are listed as a linear set instead of a + * cartesian set (i.e one combined variable instead of two, one for encoding + * and one for the signature algorithm). + */ +export declare enum PublicKeyDetails { + PUBLIC_KEY_DETAILS_UNSPECIFIED = 0, + /** PKCS1_RSA_PKCS1V5 - RSA */ + PKCS1_RSA_PKCS1V5 = 1, + /** PKCS1_RSA_PSS - See RFC8017 */ + PKCS1_RSA_PSS = 2, + PKIX_RSA_PKCS1V5 = 3, + PKIX_RSA_PSS = 4, + /** PKIX_ECDSA_P256_SHA_256 - ECDSA */ + PKIX_ECDSA_P256_SHA_256 = 5, + /** PKIX_ECDSA_P256_HMAC_SHA_256 - See RFC6979 */ + PKIX_ECDSA_P256_HMAC_SHA_256 = 6, + /** PKIX_ED25519 - Ed 25519 */ + PKIX_ED25519 = 7 +} +export declare function publicKeyDetailsFromJSON(object: any): PublicKeyDetails; +export declare function publicKeyDetailsToJSON(object: PublicKeyDetails): string; +export declare enum SubjectAlternativeNameType { + SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED = 0, + EMAIL = 1, + URI = 2, + /** + * OTHER_NAME - OID 1.3.6.1.4.1.57264.1.7 + * See https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#1361415726417--othername-san + * for more details. + */ + OTHER_NAME = 3 +} +export declare function subjectAlternativeNameTypeFromJSON(object: any): SubjectAlternativeNameType; +export declare function subjectAlternativeNameTypeToJSON(object: SubjectAlternativeNameType): string; +/** + * HashOutput captures a digest of a 'message' (generic octet sequence) + * and the corresponding hash algorithm used. + */ +export interface HashOutput { + algorithm: HashAlgorithm; + /** + * This is the raw octets of the message digest as computed by + * the hash algorithm. + */ + digest: Buffer; +} +/** MessageSignature stores the computed signature over a message. */ +export interface MessageSignature { + /** Message digest can be used to identify the artifact. */ + messageDigest: HashOutput | undefined; + /** + * The raw bytes as returned from the signature algorithm. + * The signature algorithm (and so the format of the signature bytes) + * are determined by the contents of the 'verification_material', + * either a key-pair or a certificate. If using a certificate, the + * certificate contains the required information on the signature + * algorithm. + * When using a key pair, the algorithm MUST be part of the public + * key, which MUST be communicated out-of-band. + */ + signature: Buffer; +} +/** LogId captures the identity of a transparency log. */ +export interface LogId { + /** + * The unique id of the log, represented as the SHA-256 hash + * of the log's public key, computed over the DER encoding. + * + */ + keyId: Buffer; +} +/** This message holds a RFC 3161 timestamp. */ +export interface RFC3161SignedTimestamp { + /** + * Signed timestamp is the DER encoded TimeStampResponse. + * See https://www.rfc-editor.org/rfc/rfc3161.html#section-2.4.2 + */ + signedTimestamp: Buffer; +} +export interface PublicKey { + /** + * DER-encoded public key, encoding method is specified by the + * key_details attribute. + */ + rawBytes?: Buffer | undefined; + /** Key encoding and signature algorithm to use for this key. */ + keyDetails: PublicKeyDetails; + /** Optional validity period for this key. */ + validFor?: TimeRange | undefined; +} +/** + * PublicKeyIdentifier can be used to identify an (out of band) delivered + * key, to verify a signature. + */ +export interface PublicKeyIdentifier { + /** + * Optional unauthenticated hint on which key to use. + * The format of the hint must be agreed upon out of band by the + * signer and the verifiers, and so is not subject to this + * specification. + * Example use-case is to specify the public key to use, from a + * trusted key-ring. + * Implementors are RECOMMENDED to derive the value from the public + * key as described in RFC 6962. + * See: + */ + hint: string; +} +/** An ASN.1 OBJECT IDENTIFIER */ +export interface ObjectIdentifier { + id: number[]; +} +/** An OID and the corresponding (byte) value. */ +export interface ObjectIdentifierValuePair { + oid: ObjectIdentifier | undefined; + value: Buffer; +} +export interface DistinguishedName { + organization: string; + commonName: string; +} +export interface X509Certificate { + /** DER-encoded X.509 certificate. */ + rawBytes: Buffer; +} +export interface SubjectAlternativeName { + type: SubjectAlternativeNameType; + identity?: { + $case: "regexp"; + regexp: string; + } | { + $case: "value"; + value: string; + }; +} +/** A chain of X.509 certificates. */ +export interface X509CertificateChain { + /** + * The chain of certificates, with indices 0 to n. + * The first certificate in the array must be the leaf + * certificate used for signing. Any intermediate certificates + * must be stored as offset 1 to n-1, and the root certificate at + * position n. + */ + certificates: X509Certificate[]; +} +/** + * The time range is half-open and does not include the end timestamp, + * i.e [start, end). + * End is optional to be able to capture a period that has started but + * has no known end. + */ +export interface TimeRange { + start: Date | undefined; + end?: Date | undefined; +} +export declare const HashOutput: { + fromJSON(object: any): HashOutput; + toJSON(message: HashOutput): unknown; +}; +export declare const MessageSignature: { + fromJSON(object: any): MessageSignature; + toJSON(message: MessageSignature): unknown; +}; +export declare const LogId: { + fromJSON(object: any): LogId; + toJSON(message: LogId): unknown; +}; +export declare const RFC3161SignedTimestamp: { + fromJSON(object: any): RFC3161SignedTimestamp; + toJSON(message: RFC3161SignedTimestamp): unknown; +}; +export declare const PublicKey: { + fromJSON(object: any): PublicKey; + toJSON(message: PublicKey): unknown; +}; +export declare const PublicKeyIdentifier: { + fromJSON(object: any): PublicKeyIdentifier; + toJSON(message: PublicKeyIdentifier): unknown; +}; +export declare const ObjectIdentifier: { + fromJSON(object: any): ObjectIdentifier; + toJSON(message: ObjectIdentifier): unknown; +}; +export declare const ObjectIdentifierValuePair: { + fromJSON(object: any): ObjectIdentifierValuePair; + toJSON(message: ObjectIdentifierValuePair): unknown; +}; +export declare const DistinguishedName: { + fromJSON(object: any): DistinguishedName; + toJSON(message: DistinguishedName): unknown; +}; +export declare const X509Certificate: { + fromJSON(object: any): X509Certificate; + toJSON(message: X509Certificate): unknown; +}; +export declare const SubjectAlternativeName: { + fromJSON(object: any): SubjectAlternativeName; + toJSON(message: SubjectAlternativeName): unknown; +}; +export declare const X509CertificateChain: { + fromJSON(object: any): X509CertificateChain; + toJSON(message: X509CertificateChain): unknown; +}; +export declare const TimeRange: { + fromJSON(object: any): TimeRange; + toJSON(message: TimeRange): unknown; +}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_common.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_common.js new file mode 100644 index 0000000..63ace8d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_common.js @@ -0,0 +1,457 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TimeRange = exports.X509CertificateChain = exports.SubjectAlternativeName = exports.X509Certificate = exports.DistinguishedName = exports.ObjectIdentifierValuePair = exports.ObjectIdentifier = exports.PublicKeyIdentifier = exports.PublicKey = exports.RFC3161SignedTimestamp = exports.LogId = exports.MessageSignature = exports.HashOutput = exports.subjectAlternativeNameTypeToJSON = exports.subjectAlternativeNameTypeFromJSON = exports.SubjectAlternativeNameType = exports.publicKeyDetailsToJSON = exports.publicKeyDetailsFromJSON = exports.PublicKeyDetails = exports.hashAlgorithmToJSON = exports.hashAlgorithmFromJSON = exports.HashAlgorithm = void 0; +/* eslint-disable */ +const timestamp_1 = require("./google/protobuf/timestamp"); +/** + * Only a subset of the secure hash standard algorithms are supported. + * See for more + * details. + * UNSPECIFIED SHOULD not be used, primary reason for inclusion is to force + * any proto JSON serialization to emit the used hash algorithm, as default + * option is to *omit* the default value of an enum (which is the first + * value, represented by '0'. + */ +var HashAlgorithm; +(function (HashAlgorithm) { + HashAlgorithm[HashAlgorithm["HASH_ALGORITHM_UNSPECIFIED"] = 0] = "HASH_ALGORITHM_UNSPECIFIED"; + HashAlgorithm[HashAlgorithm["SHA2_256"] = 1] = "SHA2_256"; +})(HashAlgorithm = exports.HashAlgorithm || (exports.HashAlgorithm = {})); +function hashAlgorithmFromJSON(object) { + switch (object) { + case 0: + case "HASH_ALGORITHM_UNSPECIFIED": + return HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED; + case 1: + case "SHA2_256": + return HashAlgorithm.SHA2_256; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); + } +} +exports.hashAlgorithmFromJSON = hashAlgorithmFromJSON; +function hashAlgorithmToJSON(object) { + switch (object) { + case HashAlgorithm.HASH_ALGORITHM_UNSPECIFIED: + return "HASH_ALGORITHM_UNSPECIFIED"; + case HashAlgorithm.SHA2_256: + return "SHA2_256"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum HashAlgorithm"); + } +} +exports.hashAlgorithmToJSON = hashAlgorithmToJSON; +/** + * Details of a specific public key, capturing the the key encoding method, + * and signature algorithm. + * To avoid the possibility of contradicting formats such as PKCS1 with + * ED25519 the valid permutations are listed as a linear set instead of a + * cartesian set (i.e one combined variable instead of two, one for encoding + * and one for the signature algorithm). + */ +var PublicKeyDetails; +(function (PublicKeyDetails) { + PublicKeyDetails[PublicKeyDetails["PUBLIC_KEY_DETAILS_UNSPECIFIED"] = 0] = "PUBLIC_KEY_DETAILS_UNSPECIFIED"; + /** PKCS1_RSA_PKCS1V5 - RSA */ + PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PKCS1V5"] = 1] = "PKCS1_RSA_PKCS1V5"; + /** PKCS1_RSA_PSS - See RFC8017 */ + PublicKeyDetails[PublicKeyDetails["PKCS1_RSA_PSS"] = 2] = "PKCS1_RSA_PSS"; + PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PKCS1V5"] = 3] = "PKIX_RSA_PKCS1V5"; + PublicKeyDetails[PublicKeyDetails["PKIX_RSA_PSS"] = 4] = "PKIX_RSA_PSS"; + /** PKIX_ECDSA_P256_SHA_256 - ECDSA */ + PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_SHA_256"] = 5] = "PKIX_ECDSA_P256_SHA_256"; + /** PKIX_ECDSA_P256_HMAC_SHA_256 - See RFC6979 */ + PublicKeyDetails[PublicKeyDetails["PKIX_ECDSA_P256_HMAC_SHA_256"] = 6] = "PKIX_ECDSA_P256_HMAC_SHA_256"; + /** PKIX_ED25519 - Ed 25519 */ + PublicKeyDetails[PublicKeyDetails["PKIX_ED25519"] = 7] = "PKIX_ED25519"; +})(PublicKeyDetails = exports.PublicKeyDetails || (exports.PublicKeyDetails = {})); +function publicKeyDetailsFromJSON(object) { + switch (object) { + case 0: + case "PUBLIC_KEY_DETAILS_UNSPECIFIED": + return PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED; + case 1: + case "PKCS1_RSA_PKCS1V5": + return PublicKeyDetails.PKCS1_RSA_PKCS1V5; + case 2: + case "PKCS1_RSA_PSS": + return PublicKeyDetails.PKCS1_RSA_PSS; + case 3: + case "PKIX_RSA_PKCS1V5": + return PublicKeyDetails.PKIX_RSA_PKCS1V5; + case 4: + case "PKIX_RSA_PSS": + return PublicKeyDetails.PKIX_RSA_PSS; + case 5: + case "PKIX_ECDSA_P256_SHA_256": + return PublicKeyDetails.PKIX_ECDSA_P256_SHA_256; + case 6: + case "PKIX_ECDSA_P256_HMAC_SHA_256": + return PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256; + case 7: + case "PKIX_ED25519": + return PublicKeyDetails.PKIX_ED25519; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); + } +} +exports.publicKeyDetailsFromJSON = publicKeyDetailsFromJSON; +function publicKeyDetailsToJSON(object) { + switch (object) { + case PublicKeyDetails.PUBLIC_KEY_DETAILS_UNSPECIFIED: + return "PUBLIC_KEY_DETAILS_UNSPECIFIED"; + case PublicKeyDetails.PKCS1_RSA_PKCS1V5: + return "PKCS1_RSA_PKCS1V5"; + case PublicKeyDetails.PKCS1_RSA_PSS: + return "PKCS1_RSA_PSS"; + case PublicKeyDetails.PKIX_RSA_PKCS1V5: + return "PKIX_RSA_PKCS1V5"; + case PublicKeyDetails.PKIX_RSA_PSS: + return "PKIX_RSA_PSS"; + case PublicKeyDetails.PKIX_ECDSA_P256_SHA_256: + return "PKIX_ECDSA_P256_SHA_256"; + case PublicKeyDetails.PKIX_ECDSA_P256_HMAC_SHA_256: + return "PKIX_ECDSA_P256_HMAC_SHA_256"; + case PublicKeyDetails.PKIX_ED25519: + return "PKIX_ED25519"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum PublicKeyDetails"); + } +} +exports.publicKeyDetailsToJSON = publicKeyDetailsToJSON; +var SubjectAlternativeNameType; +(function (SubjectAlternativeNameType) { + SubjectAlternativeNameType[SubjectAlternativeNameType["SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"] = 0] = "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; + SubjectAlternativeNameType[SubjectAlternativeNameType["EMAIL"] = 1] = "EMAIL"; + SubjectAlternativeNameType[SubjectAlternativeNameType["URI"] = 2] = "URI"; + /** + * OTHER_NAME - OID 1.3.6.1.4.1.57264.1.7 + * See https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#1361415726417--othername-san + * for more details. + */ + SubjectAlternativeNameType[SubjectAlternativeNameType["OTHER_NAME"] = 3] = "OTHER_NAME"; +})(SubjectAlternativeNameType = exports.SubjectAlternativeNameType || (exports.SubjectAlternativeNameType = {})); +function subjectAlternativeNameTypeFromJSON(object) { + switch (object) { + case 0: + case "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED": + return SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED; + case 1: + case "EMAIL": + return SubjectAlternativeNameType.EMAIL; + case 2: + case "URI": + return SubjectAlternativeNameType.URI; + case 3: + case "OTHER_NAME": + return SubjectAlternativeNameType.OTHER_NAME; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); + } +} +exports.subjectAlternativeNameTypeFromJSON = subjectAlternativeNameTypeFromJSON; +function subjectAlternativeNameTypeToJSON(object) { + switch (object) { + case SubjectAlternativeNameType.SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED: + return "SUBJECT_ALTERNATIVE_NAME_TYPE_UNSPECIFIED"; + case SubjectAlternativeNameType.EMAIL: + return "EMAIL"; + case SubjectAlternativeNameType.URI: + return "URI"; + case SubjectAlternativeNameType.OTHER_NAME: + return "OTHER_NAME"; + default: + throw new globalThis.Error("Unrecognized enum value " + object + " for enum SubjectAlternativeNameType"); + } +} +exports.subjectAlternativeNameTypeToJSON = subjectAlternativeNameTypeToJSON; +function createBaseHashOutput() { + return { algorithm: 0, digest: Buffer.alloc(0) }; +} +exports.HashOutput = { + fromJSON(object) { + return { + algorithm: isSet(object.algorithm) ? hashAlgorithmFromJSON(object.algorithm) : 0, + digest: isSet(object.digest) ? Buffer.from(bytesFromBase64(object.digest)) : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.algorithm !== undefined && (obj.algorithm = hashAlgorithmToJSON(message.algorithm)); + message.digest !== undefined && + (obj.digest = base64FromBytes(message.digest !== undefined ? message.digest : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseMessageSignature() { + return { messageDigest: undefined, signature: Buffer.alloc(0) }; +} +exports.MessageSignature = { + fromJSON(object) { + return { + messageDigest: isSet(object.messageDigest) ? exports.HashOutput.fromJSON(object.messageDigest) : undefined, + signature: isSet(object.signature) ? Buffer.from(bytesFromBase64(object.signature)) : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.messageDigest !== undefined && + (obj.messageDigest = message.messageDigest ? exports.HashOutput.toJSON(message.messageDigest) : undefined); + message.signature !== undefined && + (obj.signature = base64FromBytes(message.signature !== undefined ? message.signature : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseLogId() { + return { keyId: Buffer.alloc(0) }; +} +exports.LogId = { + fromJSON(object) { + return { keyId: isSet(object.keyId) ? Buffer.from(bytesFromBase64(object.keyId)) : Buffer.alloc(0) }; + }, + toJSON(message) { + const obj = {}; + message.keyId !== undefined && + (obj.keyId = base64FromBytes(message.keyId !== undefined ? message.keyId : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseRFC3161SignedTimestamp() { + return { signedTimestamp: Buffer.alloc(0) }; +} +exports.RFC3161SignedTimestamp = { + fromJSON(object) { + return { + signedTimestamp: isSet(object.signedTimestamp) + ? Buffer.from(bytesFromBase64(object.signedTimestamp)) + : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.signedTimestamp !== undefined && + (obj.signedTimestamp = base64FromBytes(message.signedTimestamp !== undefined ? message.signedTimestamp : Buffer.alloc(0))); + return obj; + }, +}; +function createBasePublicKey() { + return { rawBytes: undefined, keyDetails: 0, validFor: undefined }; +} +exports.PublicKey = { + fromJSON(object) { + return { + rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : undefined, + keyDetails: isSet(object.keyDetails) ? publicKeyDetailsFromJSON(object.keyDetails) : 0, + validFor: isSet(object.validFor) ? exports.TimeRange.fromJSON(object.validFor) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.rawBytes !== undefined && + (obj.rawBytes = message.rawBytes !== undefined ? base64FromBytes(message.rawBytes) : undefined); + message.keyDetails !== undefined && (obj.keyDetails = publicKeyDetailsToJSON(message.keyDetails)); + message.validFor !== undefined && + (obj.validFor = message.validFor ? exports.TimeRange.toJSON(message.validFor) : undefined); + return obj; + }, +}; +function createBasePublicKeyIdentifier() { + return { hint: "" }; +} +exports.PublicKeyIdentifier = { + fromJSON(object) { + return { hint: isSet(object.hint) ? String(object.hint) : "" }; + }, + toJSON(message) { + const obj = {}; + message.hint !== undefined && (obj.hint = message.hint); + return obj; + }, +}; +function createBaseObjectIdentifier() { + return { id: [] }; +} +exports.ObjectIdentifier = { + fromJSON(object) { + return { id: Array.isArray(object?.id) ? object.id.map((e) => Number(e)) : [] }; + }, + toJSON(message) { + const obj = {}; + if (message.id) { + obj.id = message.id.map((e) => Math.round(e)); + } + else { + obj.id = []; + } + return obj; + }, +}; +function createBaseObjectIdentifierValuePair() { + return { oid: undefined, value: Buffer.alloc(0) }; +} +exports.ObjectIdentifierValuePair = { + fromJSON(object) { + return { + oid: isSet(object.oid) ? exports.ObjectIdentifier.fromJSON(object.oid) : undefined, + value: isSet(object.value) ? Buffer.from(bytesFromBase64(object.value)) : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.oid !== undefined && (obj.oid = message.oid ? exports.ObjectIdentifier.toJSON(message.oid) : undefined); + message.value !== undefined && + (obj.value = base64FromBytes(message.value !== undefined ? message.value : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseDistinguishedName() { + return { organization: "", commonName: "" }; +} +exports.DistinguishedName = { + fromJSON(object) { + return { + organization: isSet(object.organization) ? String(object.organization) : "", + commonName: isSet(object.commonName) ? String(object.commonName) : "", + }; + }, + toJSON(message) { + const obj = {}; + message.organization !== undefined && (obj.organization = message.organization); + message.commonName !== undefined && (obj.commonName = message.commonName); + return obj; + }, +}; +function createBaseX509Certificate() { + return { rawBytes: Buffer.alloc(0) }; +} +exports.X509Certificate = { + fromJSON(object) { + return { rawBytes: isSet(object.rawBytes) ? Buffer.from(bytesFromBase64(object.rawBytes)) : Buffer.alloc(0) }; + }, + toJSON(message) { + const obj = {}; + message.rawBytes !== undefined && + (obj.rawBytes = base64FromBytes(message.rawBytes !== undefined ? message.rawBytes : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseSubjectAlternativeName() { + return { type: 0, identity: undefined }; +} +exports.SubjectAlternativeName = { + fromJSON(object) { + return { + type: isSet(object.type) ? subjectAlternativeNameTypeFromJSON(object.type) : 0, + identity: isSet(object.regexp) + ? { $case: "regexp", regexp: String(object.regexp) } + : isSet(object.value) + ? { $case: "value", value: String(object.value) } + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.type !== undefined && (obj.type = subjectAlternativeNameTypeToJSON(message.type)); + message.identity?.$case === "regexp" && (obj.regexp = message.identity?.regexp); + message.identity?.$case === "value" && (obj.value = message.identity?.value); + return obj; + }, +}; +function createBaseX509CertificateChain() { + return { certificates: [] }; +} +exports.X509CertificateChain = { + fromJSON(object) { + return { + certificates: Array.isArray(object?.certificates) + ? object.certificates.map((e) => exports.X509Certificate.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.certificates) { + obj.certificates = message.certificates.map((e) => e ? exports.X509Certificate.toJSON(e) : undefined); + } + else { + obj.certificates = []; + } + return obj; + }, +}; +function createBaseTimeRange() { + return { start: undefined, end: undefined }; +} +exports.TimeRange = { + fromJSON(object) { + return { + start: isSet(object.start) ? fromJsonTimestamp(object.start) : undefined, + end: isSet(object.end) ? fromJsonTimestamp(object.end) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.start !== undefined && (obj.start = message.start.toISOString()); + message.end !== undefined && (obj.end = message.end.toISOString()); + return obj; + }, +}; +var globalThis = (() => { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw "Unable to locate global object"; +})(); +function bytesFromBase64(b64) { + if (globalThis.Buffer) { + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); + } + else { + const bin = globalThis.atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; ++i) { + arr[i] = bin.charCodeAt(i); + } + return arr; + } +} +function base64FromBytes(arr) { + if (globalThis.Buffer) { + return globalThis.Buffer.from(arr).toString("base64"); + } + else { + const bin = []; + arr.forEach((byte) => { + bin.push(String.fromCharCode(byte)); + }); + return globalThis.btoa(bin.join("")); + } +} +function fromTimestamp(t) { + let millis = Number(t.seconds) * 1000; + millis += t.nanos / 1000000; + return new Date(millis); +} +function fromJsonTimestamp(o) { + if (o instanceof Date) { + return o; + } + else if (typeof o === "string") { + return new Date(o); + } + else { + return fromTimestamp(timestamp_1.Timestamp.fromJSON(o)); + } +} +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_rekor.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_rekor.d.ts new file mode 100644 index 0000000..9e33bb8 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_rekor.d.ts @@ -0,0 +1,129 @@ +/// +import { LogId } from "./sigstore_common"; +/** KindVersion contains the entry's kind and api version. */ +export interface KindVersion { + /** + * Kind is the type of entry being stored in the log. + * See here for a list: https://github.com/sigstore/rekor/tree/main/pkg/types + */ + kind: string; + /** The specific api version of the type. */ + version: string; +} +/** + * The checkpoint contains a signature of the tree head (root hash), + * size of the tree, the transparency log's unique identifier (log ID), + * hostname and the current time. + * The result is a string, the format is described here + * https://github.com/transparency-dev/formats/blob/main/log/README.md + * The details are here https://github.com/sigstore/rekor/blob/a6e58f72b6b18cc06cefe61808efd562b9726330/pkg/util/signed_note.go#L114 + * The signature has the same format as + * InclusionPromise.signed_entry_timestamp. See below for more details. + */ +export interface Checkpoint { + envelope: string; +} +/** + * InclusionProof is the proof returned from the transparency log. Can + * be used for on line verification against the log. + */ +export interface InclusionProof { + /** The index of the entry in the log. */ + logIndex: string; + /** + * The hash digest stored at the root of the merkle tree at the time + * the proof was generated. + */ + rootHash: Buffer; + /** The size of the merkle tree at the time the proof was generated. */ + treeSize: string; + /** + * A list of hashes required to compute the inclusion proof, sorted + * in order from leaf to root. + * Not that leaf and root hashes are not included. + * The root has is available separately in this message, and the + * leaf hash should be calculated by the client. + */ + hashes: Buffer[]; + /** + * Signature of the tree head, as of the time of this proof was + * generated. See above info on 'Checkpoint' for more details. + */ + checkpoint: Checkpoint | undefined; +} +/** + * The inclusion promise is calculated by Rekor. It's calculated as a + * signature over a canonical JSON serialization of the persisted entry, the + * log ID, log index and the integration timestamp. + * See https://github.com/sigstore/rekor/blob/a6e58f72b6b18cc06cefe61808efd562b9726330/pkg/api/entries.go#L54 + * The format of the signature depends on the transparency log's public key. + * If the signature algorithm requires a hash function and/or a signature + * scheme (e.g. RSA) those has to be retrieved out-of-band from the log's + * operators, together with the public key. + * This is used to verify the integration timestamp's value and that the log + * has promised to include the entry. + */ +export interface InclusionPromise { + signedEntryTimestamp: Buffer; +} +/** + * TransparencyLogEntry captures all the details required from Rekor to + * reconstruct an entry, given that the payload is provided via other means. + * This type can easily be created from the existing response from Rekor. + * Future iterations could rely on Rekor returning the minimal set of + * attributes (excluding the payload) that are required for verifying the + * inclusion promise. The inclusion promise (called SignedEntryTimestamp in + * the response from Rekor) is similar to a Signed Certificate Timestamp + * as described here https://www.rfc-editor.org/rfc/rfc9162#name-signed-certificate-timestam. + */ +export interface TransparencyLogEntry { + /** The index of the entry in the log. */ + logIndex: string; + /** The unique identifier of the log. */ + logId: LogId | undefined; + /** + * The kind (type) and version of the object associated with this + * entry. These values are required to construct the entry during + * verification. + */ + kindVersion: KindVersion | undefined; + /** The UNIX timestamp from the log when the entry was persisted. */ + integratedTime: string; + /** The inclusion promise/signed entry timestamp from the log. */ + inclusionPromise: InclusionPromise | undefined; + /** + * The inclusion proof can be used for online verification that the + * entry was appended to the log, and that the log has not been + * altered. + */ + inclusionProof: InclusionProof | undefined; + /** + * The canonicalized Rekor entry body, used for SET verification. This + * is the same as the body returned by Rekor. It's included here for + * cases where the client cannot deterministically reconstruct the + * bundle from the other fields. Clients MUST verify that the signature + * referenced in the canonicalized_body matches the signature provided + * in the bundle content. + */ + canonicalizedBody: Buffer; +} +export declare const KindVersion: { + fromJSON(object: any): KindVersion; + toJSON(message: KindVersion): unknown; +}; +export declare const Checkpoint: { + fromJSON(object: any): Checkpoint; + toJSON(message: Checkpoint): unknown; +}; +export declare const InclusionProof: { + fromJSON(object: any): InclusionProof; + toJSON(message: InclusionProof): unknown; +}; +export declare const InclusionPromise: { + fromJSON(object: any): InclusionPromise; + toJSON(message: InclusionPromise): unknown; +}; +export declare const TransparencyLogEntry: { + fromJSON(object: any): TransparencyLogEntry; + toJSON(message: TransparencyLogEntry): unknown; +}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_rekor.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_rekor.js new file mode 100644 index 0000000..bffc770 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_rekor.js @@ -0,0 +1,167 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TransparencyLogEntry = exports.InclusionPromise = exports.InclusionProof = exports.Checkpoint = exports.KindVersion = void 0; +/* eslint-disable */ +const sigstore_common_1 = require("./sigstore_common"); +function createBaseKindVersion() { + return { kind: "", version: "" }; +} +exports.KindVersion = { + fromJSON(object) { + return { + kind: isSet(object.kind) ? String(object.kind) : "", + version: isSet(object.version) ? String(object.version) : "", + }; + }, + toJSON(message) { + const obj = {}; + message.kind !== undefined && (obj.kind = message.kind); + message.version !== undefined && (obj.version = message.version); + return obj; + }, +}; +function createBaseCheckpoint() { + return { envelope: "" }; +} +exports.Checkpoint = { + fromJSON(object) { + return { envelope: isSet(object.envelope) ? String(object.envelope) : "" }; + }, + toJSON(message) { + const obj = {}; + message.envelope !== undefined && (obj.envelope = message.envelope); + return obj; + }, +}; +function createBaseInclusionProof() { + return { logIndex: "0", rootHash: Buffer.alloc(0), treeSize: "0", hashes: [], checkpoint: undefined }; +} +exports.InclusionProof = { + fromJSON(object) { + return { + logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0", + rootHash: isSet(object.rootHash) ? Buffer.from(bytesFromBase64(object.rootHash)) : Buffer.alloc(0), + treeSize: isSet(object.treeSize) ? String(object.treeSize) : "0", + hashes: Array.isArray(object?.hashes) ? object.hashes.map((e) => Buffer.from(bytesFromBase64(e))) : [], + checkpoint: isSet(object.checkpoint) ? exports.Checkpoint.fromJSON(object.checkpoint) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.logIndex !== undefined && (obj.logIndex = message.logIndex); + message.rootHash !== undefined && + (obj.rootHash = base64FromBytes(message.rootHash !== undefined ? message.rootHash : Buffer.alloc(0))); + message.treeSize !== undefined && (obj.treeSize = message.treeSize); + if (message.hashes) { + obj.hashes = message.hashes.map((e) => base64FromBytes(e !== undefined ? e : Buffer.alloc(0))); + } + else { + obj.hashes = []; + } + message.checkpoint !== undefined && + (obj.checkpoint = message.checkpoint ? exports.Checkpoint.toJSON(message.checkpoint) : undefined); + return obj; + }, +}; +function createBaseInclusionPromise() { + return { signedEntryTimestamp: Buffer.alloc(0) }; +} +exports.InclusionPromise = { + fromJSON(object) { + return { + signedEntryTimestamp: isSet(object.signedEntryTimestamp) + ? Buffer.from(bytesFromBase64(object.signedEntryTimestamp)) + : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.signedEntryTimestamp !== undefined && + (obj.signedEntryTimestamp = base64FromBytes(message.signedEntryTimestamp !== undefined ? message.signedEntryTimestamp : Buffer.alloc(0))); + return obj; + }, +}; +function createBaseTransparencyLogEntry() { + return { + logIndex: "0", + logId: undefined, + kindVersion: undefined, + integratedTime: "0", + inclusionPromise: undefined, + inclusionProof: undefined, + canonicalizedBody: Buffer.alloc(0), + }; +} +exports.TransparencyLogEntry = { + fromJSON(object) { + return { + logIndex: isSet(object.logIndex) ? String(object.logIndex) : "0", + logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined, + kindVersion: isSet(object.kindVersion) ? exports.KindVersion.fromJSON(object.kindVersion) : undefined, + integratedTime: isSet(object.integratedTime) ? String(object.integratedTime) : "0", + inclusionPromise: isSet(object.inclusionPromise) ? exports.InclusionPromise.fromJSON(object.inclusionPromise) : undefined, + inclusionProof: isSet(object.inclusionProof) ? exports.InclusionProof.fromJSON(object.inclusionProof) : undefined, + canonicalizedBody: isSet(object.canonicalizedBody) + ? Buffer.from(bytesFromBase64(object.canonicalizedBody)) + : Buffer.alloc(0), + }; + }, + toJSON(message) { + const obj = {}; + message.logIndex !== undefined && (obj.logIndex = message.logIndex); + message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined); + message.kindVersion !== undefined && + (obj.kindVersion = message.kindVersion ? exports.KindVersion.toJSON(message.kindVersion) : undefined); + message.integratedTime !== undefined && (obj.integratedTime = message.integratedTime); + message.inclusionPromise !== undefined && + (obj.inclusionPromise = message.inclusionPromise ? exports.InclusionPromise.toJSON(message.inclusionPromise) : undefined); + message.inclusionProof !== undefined && + (obj.inclusionProof = message.inclusionProof ? exports.InclusionProof.toJSON(message.inclusionProof) : undefined); + message.canonicalizedBody !== undefined && + (obj.canonicalizedBody = base64FromBytes(message.canonicalizedBody !== undefined ? message.canonicalizedBody : Buffer.alloc(0))); + return obj; + }, +}; +var globalThis = (() => { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw "Unable to locate global object"; +})(); +function bytesFromBase64(b64) { + if (globalThis.Buffer) { + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); + } + else { + const bin = globalThis.atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; ++i) { + arr[i] = bin.charCodeAt(i); + } + return arr; + } +} +function base64FromBytes(arr) { + if (globalThis.Buffer) { + return globalThis.Buffer.from(arr).toString("base64"); + } + else { + const bin = []; + arr.forEach((byte) => { + bin.push(String.fromCharCode(byte)); + }); + return globalThis.btoa(bin.join("")); + } +} +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_trustroot.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_trustroot.d.ts new file mode 100644 index 0000000..152d08f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_trustroot.d.ts @@ -0,0 +1,89 @@ +import { DistinguishedName, HashAlgorithm, LogId, PublicKey, TimeRange, X509CertificateChain } from "./sigstore_common"; +/** + * TransparencyLogInstance describes the immutable parameters from a + * transparency log. + * See https://www.rfc-editor.org/rfc/rfc9162.html#name-log-parameters + * for more details. + * The incluced parameters are the minimal set required to identify a log, + * and verify an inclusion promise. + */ +export interface TransparencyLogInstance { + /** The base URL at which can be used to URLs for the client. */ + baseUrl: string; + /** The hash algorithm used for the Merkle Tree. */ + hashAlgorithm: HashAlgorithm; + /** + * The public key used to verify signatures generated by the log. + * This attribute contains the signature algorithm used by the log. + */ + publicKey: PublicKey | undefined; + /** The unique identifier for this transparency log. */ + logId: LogId | undefined; +} +/** + * CertificateAuthority enlists the information required to identify which + * CA to use and perform signature verification. + */ +export interface CertificateAuthority { + /** + * The root certificate MUST be self-signed, and so the subject and + * issuer are the same. + */ + subject: DistinguishedName | undefined; + /** The URI at which the CA can be accessed. */ + uri: string; + /** The certificate chain for this CA. */ + certChain: X509CertificateChain | undefined; + /** + * The time the *entire* chain was valid. This is at max the + * longest interval when *all* certificates in the chain were valid, + * but it MAY be shorter. + */ + validFor: TimeRange | undefined; +} +/** + * TrustedRoot describes the client's complete set of trusted entities. + * How the TrustedRoot is populated is not specified, but can be a + * combination of many sources such as TUF repositories, files on disk etc. + * + * The TrustedRoot is not meant to be used for any artifact verification, only + * to capture the complete/global set of trusted verification materials. + * When verifying an artifact, based on the artifact and policies, a selection + * of keys/authorities are expected to be extracted and provided to the + * verification function. This way the set of keys/authorities kan be kept to + * a minimal set by the policy to gain better control over what signatures + * that are allowed. + */ +export interface TrustedRoot { + /** MUST be application/vnd.dev.sigstore.trustedroot+json;version=0.1 */ + mediaType: string; + /** A set of trusted Rekor servers. */ + tlogs: TransparencyLogInstance[]; + /** + * A set of trusted certificate authorites (e.g Fulcio), and any + * intermediate certificates they provide. + * If a CA is issuing multiple intermediate certificate, each + * combination shall be represented as separate chain. I.e, a single + * root cert may appear in multiple chains but with different + * intermediate and/or leaf certificates. + * The certificates are intended to be used for verifying artifact + * signatures. + */ + certificateAuthorities: CertificateAuthority[]; + /** A set of trusted certificate transparency logs. */ + ctlogs: TransparencyLogInstance[]; + /** A set of trusted timestamping authorities. */ + timestampAuthorities: CertificateAuthority[]; +} +export declare const TransparencyLogInstance: { + fromJSON(object: any): TransparencyLogInstance; + toJSON(message: TransparencyLogInstance): unknown; +}; +export declare const CertificateAuthority: { + fromJSON(object: any): CertificateAuthority; + toJSON(message: CertificateAuthority): unknown; +}; +export declare const TrustedRoot: { + fromJSON(object: any): TrustedRoot; + toJSON(message: TrustedRoot): unknown; +}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_trustroot.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_trustroot.js new file mode 100644 index 0000000..05e5667 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_trustroot.js @@ -0,0 +1,103 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TrustedRoot = exports.CertificateAuthority = exports.TransparencyLogInstance = void 0; +/* eslint-disable */ +const sigstore_common_1 = require("./sigstore_common"); +function createBaseTransparencyLogInstance() { + return { baseUrl: "", hashAlgorithm: 0, publicKey: undefined, logId: undefined }; +} +exports.TransparencyLogInstance = { + fromJSON(object) { + return { + baseUrl: isSet(object.baseUrl) ? String(object.baseUrl) : "", + hashAlgorithm: isSet(object.hashAlgorithm) ? (0, sigstore_common_1.hashAlgorithmFromJSON)(object.hashAlgorithm) : 0, + publicKey: isSet(object.publicKey) ? sigstore_common_1.PublicKey.fromJSON(object.publicKey) : undefined, + logId: isSet(object.logId) ? sigstore_common_1.LogId.fromJSON(object.logId) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.baseUrl !== undefined && (obj.baseUrl = message.baseUrl); + message.hashAlgorithm !== undefined && (obj.hashAlgorithm = (0, sigstore_common_1.hashAlgorithmToJSON)(message.hashAlgorithm)); + message.publicKey !== undefined && + (obj.publicKey = message.publicKey ? sigstore_common_1.PublicKey.toJSON(message.publicKey) : undefined); + message.logId !== undefined && (obj.logId = message.logId ? sigstore_common_1.LogId.toJSON(message.logId) : undefined); + return obj; + }, +}; +function createBaseCertificateAuthority() { + return { subject: undefined, uri: "", certChain: undefined, validFor: undefined }; +} +exports.CertificateAuthority = { + fromJSON(object) { + return { + subject: isSet(object.subject) ? sigstore_common_1.DistinguishedName.fromJSON(object.subject) : undefined, + uri: isSet(object.uri) ? String(object.uri) : "", + certChain: isSet(object.certChain) ? sigstore_common_1.X509CertificateChain.fromJSON(object.certChain) : undefined, + validFor: isSet(object.validFor) ? sigstore_common_1.TimeRange.fromJSON(object.validFor) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.subject !== undefined && + (obj.subject = message.subject ? sigstore_common_1.DistinguishedName.toJSON(message.subject) : undefined); + message.uri !== undefined && (obj.uri = message.uri); + message.certChain !== undefined && + (obj.certChain = message.certChain ? sigstore_common_1.X509CertificateChain.toJSON(message.certChain) : undefined); + message.validFor !== undefined && + (obj.validFor = message.validFor ? sigstore_common_1.TimeRange.toJSON(message.validFor) : undefined); + return obj; + }, +}; +function createBaseTrustedRoot() { + return { mediaType: "", tlogs: [], certificateAuthorities: [], ctlogs: [], timestampAuthorities: [] }; +} +exports.TrustedRoot = { + fromJSON(object) { + return { + mediaType: isSet(object.mediaType) ? String(object.mediaType) : "", + tlogs: Array.isArray(object?.tlogs) ? object.tlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) : [], + certificateAuthorities: Array.isArray(object?.certificateAuthorities) + ? object.certificateAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) + : [], + ctlogs: Array.isArray(object?.ctlogs) + ? object.ctlogs.map((e) => exports.TransparencyLogInstance.fromJSON(e)) + : [], + timestampAuthorities: Array.isArray(object?.timestampAuthorities) + ? object.timestampAuthorities.map((e) => exports.CertificateAuthority.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + message.mediaType !== undefined && (obj.mediaType = message.mediaType); + if (message.tlogs) { + obj.tlogs = message.tlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); + } + else { + obj.tlogs = []; + } + if (message.certificateAuthorities) { + obj.certificateAuthorities = message.certificateAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); + } + else { + obj.certificateAuthorities = []; + } + if (message.ctlogs) { + obj.ctlogs = message.ctlogs.map((e) => e ? exports.TransparencyLogInstance.toJSON(e) : undefined); + } + else { + obj.ctlogs = []; + } + if (message.timestampAuthorities) { + obj.timestampAuthorities = message.timestampAuthorities.map((e) => e ? exports.CertificateAuthority.toJSON(e) : undefined); + } + else { + obj.timestampAuthorities = []; + } + return obj; + }, +}; +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_verification.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_verification.d.ts new file mode 100644 index 0000000..8ee32d8 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_verification.d.ts @@ -0,0 +1,156 @@ +/// +import { Bundle } from "./sigstore_bundle"; +import { ObjectIdentifierValuePair, PublicKey, SubjectAlternativeName } from "./sigstore_common"; +import { TrustedRoot } from "./sigstore_trustroot"; +/** The identity of a X.509 Certificate signer. */ +export interface CertificateIdentity { + /** The X.509v3 issuer extension (OID 1.3.6.1.4.1.57264.1.1) */ + issuer: string; + san: SubjectAlternativeName | undefined; + /** + * An unordered list of OIDs that must be verified. + * All OID/values provided in this list MUST exactly match against + * the values in the certificate for verification to be successful. + */ + oids: ObjectIdentifierValuePair[]; +} +export interface CertificateIdentities { + identities: CertificateIdentity[]; +} +export interface PublicKeyIdentities { + publicKeys: PublicKey[]; +} +/** + * A light-weight set of options/policies for identifying trusted signers, + * used during verification of a single artifact. + */ +export interface ArtifactVerificationOptions { + signers?: { + $case: "certificateIdentities"; + certificateIdentities: CertificateIdentities; + } | { + $case: "publicKeys"; + publicKeys: PublicKeyIdentities; + }; + /** + * Optional options for artifact transparency log verification. + * If none is provided, the default verification options are: + * Threshold: 1 + * Online verification: false + * Disable: false + */ + tlogOptions?: ArtifactVerificationOptions_TlogOptions | undefined; + /** + * Optional options for certificate transparency log verification. + * If none is provided, the default verification options are: + * Threshold: 1 + * Detached SCT: false + * Disable: false + */ + ctlogOptions?: ArtifactVerificationOptions_CtlogOptions | undefined; + /** + * Optional options for certificate signed timestamp verification. + * If none is provided, the default verification options are: + * Threshold: 1 + * Disable: false + */ + tsaOptions?: ArtifactVerificationOptions_TimestampAuthorityOptions | undefined; +} +export interface ArtifactVerificationOptions_TlogOptions { + /** Number of transparency logs the entry must appear on. */ + threshold: number; + /** Perform an online inclusion proof. */ + performOnlineVerification: boolean; + /** Disable verification for transparency logs. */ + disable: boolean; +} +export interface ArtifactVerificationOptions_CtlogOptions { + /** + * The number of ct transparency logs the certificate must + * appear on. + */ + threshold: number; + /** + * Expect detached SCTs. + * This is not supported right now as we can't capture an + * detached SCT in the bundle. + */ + detachedSct: boolean; + /** Disable ct transparency log verification */ + disable: boolean; +} +export interface ArtifactVerificationOptions_TimestampAuthorityOptions { + /** The number of signed timestamps that are expected. */ + threshold: number; + /** Disable signed timestamp verification. */ + disable: boolean; +} +export interface Artifact { + data?: { + $case: "artifactUri"; + artifactUri: string; + } | { + $case: "artifact"; + artifact: Buffer; + }; +} +/** + * Input captures all that is needed to call the bundle verification method, + * to verify a single artifact referenced by the bundle. + */ +export interface Input { + /** + * The verification materials provided during a bundle verification. + * The running process is usually preloaded with a "global" + * dev.sisgtore.trustroot.TrustedRoot.v1 instance. Prior to + * verifying an artifact (i.e a bundle), and/or based on current + * policy, some selection is expected to happen, to filter out the + * exact certificate authority to use, which transparency logs are + * relevant etc. The result should b ecaptured in the + * `artifact_trust_root`. + */ + artifactTrustRoot: TrustedRoot | undefined; + artifactVerificationOptions: ArtifactVerificationOptions | undefined; + bundle: Bundle | undefined; + /** + * If the bundle contains a message signature, the artifact must be + * provided. + */ + artifact?: Artifact | undefined; +} +export declare const CertificateIdentity: { + fromJSON(object: any): CertificateIdentity; + toJSON(message: CertificateIdentity): unknown; +}; +export declare const CertificateIdentities: { + fromJSON(object: any): CertificateIdentities; + toJSON(message: CertificateIdentities): unknown; +}; +export declare const PublicKeyIdentities: { + fromJSON(object: any): PublicKeyIdentities; + toJSON(message: PublicKeyIdentities): unknown; +}; +export declare const ArtifactVerificationOptions: { + fromJSON(object: any): ArtifactVerificationOptions; + toJSON(message: ArtifactVerificationOptions): unknown; +}; +export declare const ArtifactVerificationOptions_TlogOptions: { + fromJSON(object: any): ArtifactVerificationOptions_TlogOptions; + toJSON(message: ArtifactVerificationOptions_TlogOptions): unknown; +}; +export declare const ArtifactVerificationOptions_CtlogOptions: { + fromJSON(object: any): ArtifactVerificationOptions_CtlogOptions; + toJSON(message: ArtifactVerificationOptions_CtlogOptions): unknown; +}; +export declare const ArtifactVerificationOptions_TimestampAuthorityOptions: { + fromJSON(object: any): ArtifactVerificationOptions_TimestampAuthorityOptions; + toJSON(message: ArtifactVerificationOptions_TimestampAuthorityOptions): unknown; +}; +export declare const Artifact: { + fromJSON(object: any): Artifact; + toJSON(message: Artifact): unknown; +}; +export declare const Input: { + fromJSON(object: any): Input; + toJSON(message: Input): unknown; +}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_verification.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_verification.js new file mode 100644 index 0000000..b99a305 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/__generated__/sigstore_verification.js @@ -0,0 +1,273 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Input = exports.Artifact = exports.ArtifactVerificationOptions_TimestampAuthorityOptions = exports.ArtifactVerificationOptions_CtlogOptions = exports.ArtifactVerificationOptions_TlogOptions = exports.ArtifactVerificationOptions = exports.PublicKeyIdentities = exports.CertificateIdentities = exports.CertificateIdentity = void 0; +/* eslint-disable */ +const sigstore_bundle_1 = require("./sigstore_bundle"); +const sigstore_common_1 = require("./sigstore_common"); +const sigstore_trustroot_1 = require("./sigstore_trustroot"); +function createBaseCertificateIdentity() { + return { issuer: "", san: undefined, oids: [] }; +} +exports.CertificateIdentity = { + fromJSON(object) { + return { + issuer: isSet(object.issuer) ? String(object.issuer) : "", + san: isSet(object.san) ? sigstore_common_1.SubjectAlternativeName.fromJSON(object.san) : undefined, + oids: Array.isArray(object?.oids) ? object.oids.map((e) => sigstore_common_1.ObjectIdentifierValuePair.fromJSON(e)) : [], + }; + }, + toJSON(message) { + const obj = {}; + message.issuer !== undefined && (obj.issuer = message.issuer); + message.san !== undefined && (obj.san = message.san ? sigstore_common_1.SubjectAlternativeName.toJSON(message.san) : undefined); + if (message.oids) { + obj.oids = message.oids.map((e) => e ? sigstore_common_1.ObjectIdentifierValuePair.toJSON(e) : undefined); + } + else { + obj.oids = []; + } + return obj; + }, +}; +function createBaseCertificateIdentities() { + return { identities: [] }; +} +exports.CertificateIdentities = { + fromJSON(object) { + return { + identities: Array.isArray(object?.identities) + ? object.identities.map((e) => exports.CertificateIdentity.fromJSON(e)) + : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.identities) { + obj.identities = message.identities.map((e) => e ? exports.CertificateIdentity.toJSON(e) : undefined); + } + else { + obj.identities = []; + } + return obj; + }, +}; +function createBasePublicKeyIdentities() { + return { publicKeys: [] }; +} +exports.PublicKeyIdentities = { + fromJSON(object) { + return { + publicKeys: Array.isArray(object?.publicKeys) ? object.publicKeys.map((e) => sigstore_common_1.PublicKey.fromJSON(e)) : [], + }; + }, + toJSON(message) { + const obj = {}; + if (message.publicKeys) { + obj.publicKeys = message.publicKeys.map((e) => e ? sigstore_common_1.PublicKey.toJSON(e) : undefined); + } + else { + obj.publicKeys = []; + } + return obj; + }, +}; +function createBaseArtifactVerificationOptions() { + return { signers: undefined, tlogOptions: undefined, ctlogOptions: undefined, tsaOptions: undefined }; +} +exports.ArtifactVerificationOptions = { + fromJSON(object) { + return { + signers: isSet(object.certificateIdentities) + ? { + $case: "certificateIdentities", + certificateIdentities: exports.CertificateIdentities.fromJSON(object.certificateIdentities), + } + : isSet(object.publicKeys) + ? { $case: "publicKeys", publicKeys: exports.PublicKeyIdentities.fromJSON(object.publicKeys) } + : undefined, + tlogOptions: isSet(object.tlogOptions) + ? exports.ArtifactVerificationOptions_TlogOptions.fromJSON(object.tlogOptions) + : undefined, + ctlogOptions: isSet(object.ctlogOptions) + ? exports.ArtifactVerificationOptions_CtlogOptions.fromJSON(object.ctlogOptions) + : undefined, + tsaOptions: isSet(object.tsaOptions) + ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.fromJSON(object.tsaOptions) + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.signers?.$case === "certificateIdentities" && + (obj.certificateIdentities = message.signers?.certificateIdentities + ? exports.CertificateIdentities.toJSON(message.signers?.certificateIdentities) + : undefined); + message.signers?.$case === "publicKeys" && (obj.publicKeys = message.signers?.publicKeys + ? exports.PublicKeyIdentities.toJSON(message.signers?.publicKeys) + : undefined); + message.tlogOptions !== undefined && (obj.tlogOptions = message.tlogOptions + ? exports.ArtifactVerificationOptions_TlogOptions.toJSON(message.tlogOptions) + : undefined); + message.ctlogOptions !== undefined && (obj.ctlogOptions = message.ctlogOptions + ? exports.ArtifactVerificationOptions_CtlogOptions.toJSON(message.ctlogOptions) + : undefined); + message.tsaOptions !== undefined && (obj.tsaOptions = message.tsaOptions + ? exports.ArtifactVerificationOptions_TimestampAuthorityOptions.toJSON(message.tsaOptions) + : undefined); + return obj; + }, +}; +function createBaseArtifactVerificationOptions_TlogOptions() { + return { threshold: 0, performOnlineVerification: false, disable: false }; +} +exports.ArtifactVerificationOptions_TlogOptions = { + fromJSON(object) { + return { + threshold: isSet(object.threshold) ? Number(object.threshold) : 0, + performOnlineVerification: isSet(object.performOnlineVerification) + ? Boolean(object.performOnlineVerification) + : false, + disable: isSet(object.disable) ? Boolean(object.disable) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); + message.performOnlineVerification !== undefined && + (obj.performOnlineVerification = message.performOnlineVerification); + message.disable !== undefined && (obj.disable = message.disable); + return obj; + }, +}; +function createBaseArtifactVerificationOptions_CtlogOptions() { + return { threshold: 0, detachedSct: false, disable: false }; +} +exports.ArtifactVerificationOptions_CtlogOptions = { + fromJSON(object) { + return { + threshold: isSet(object.threshold) ? Number(object.threshold) : 0, + detachedSct: isSet(object.detachedSct) ? Boolean(object.detachedSct) : false, + disable: isSet(object.disable) ? Boolean(object.disable) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); + message.detachedSct !== undefined && (obj.detachedSct = message.detachedSct); + message.disable !== undefined && (obj.disable = message.disable); + return obj; + }, +}; +function createBaseArtifactVerificationOptions_TimestampAuthorityOptions() { + return { threshold: 0, disable: false }; +} +exports.ArtifactVerificationOptions_TimestampAuthorityOptions = { + fromJSON(object) { + return { + threshold: isSet(object.threshold) ? Number(object.threshold) : 0, + disable: isSet(object.disable) ? Boolean(object.disable) : false, + }; + }, + toJSON(message) { + const obj = {}; + message.threshold !== undefined && (obj.threshold = Math.round(message.threshold)); + message.disable !== undefined && (obj.disable = message.disable); + return obj; + }, +}; +function createBaseArtifact() { + return { data: undefined }; +} +exports.Artifact = { + fromJSON(object) { + return { + data: isSet(object.artifactUri) + ? { $case: "artifactUri", artifactUri: String(object.artifactUri) } + : isSet(object.artifact) + ? { $case: "artifact", artifact: Buffer.from(bytesFromBase64(object.artifact)) } + : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.data?.$case === "artifactUri" && (obj.artifactUri = message.data?.artifactUri); + message.data?.$case === "artifact" && + (obj.artifact = message.data?.artifact !== undefined ? base64FromBytes(message.data?.artifact) : undefined); + return obj; + }, +}; +function createBaseInput() { + return { + artifactTrustRoot: undefined, + artifactVerificationOptions: undefined, + bundle: undefined, + artifact: undefined, + }; +} +exports.Input = { + fromJSON(object) { + return { + artifactTrustRoot: isSet(object.artifactTrustRoot) ? sigstore_trustroot_1.TrustedRoot.fromJSON(object.artifactTrustRoot) : undefined, + artifactVerificationOptions: isSet(object.artifactVerificationOptions) + ? exports.ArtifactVerificationOptions.fromJSON(object.artifactVerificationOptions) + : undefined, + bundle: isSet(object.bundle) ? sigstore_bundle_1.Bundle.fromJSON(object.bundle) : undefined, + artifact: isSet(object.artifact) ? exports.Artifact.fromJSON(object.artifact) : undefined, + }; + }, + toJSON(message) { + const obj = {}; + message.artifactTrustRoot !== undefined && + (obj.artifactTrustRoot = message.artifactTrustRoot ? sigstore_trustroot_1.TrustedRoot.toJSON(message.artifactTrustRoot) : undefined); + message.artifactVerificationOptions !== undefined && + (obj.artifactVerificationOptions = message.artifactVerificationOptions + ? exports.ArtifactVerificationOptions.toJSON(message.artifactVerificationOptions) + : undefined); + message.bundle !== undefined && (obj.bundle = message.bundle ? sigstore_bundle_1.Bundle.toJSON(message.bundle) : undefined); + message.artifact !== undefined && (obj.artifact = message.artifact ? exports.Artifact.toJSON(message.artifact) : undefined); + return obj; + }, +}; +var globalThis = (() => { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw "Unable to locate global object"; +})(); +function bytesFromBase64(b64) { + if (globalThis.Buffer) { + return Uint8Array.from(globalThis.Buffer.from(b64, "base64")); + } + else { + const bin = globalThis.atob(b64); + const arr = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; ++i) { + arr[i] = bin.charCodeAt(i); + } + return arr; + } +} +function base64FromBytes(arr) { + if (globalThis.Buffer) { + return globalThis.Buffer.from(arr).toString("base64"); + } + else { + const bin = []; + arr.forEach((byte) => { + bin.push(String.fromCharCode(byte)); + }); + return globalThis.btoa(bin.join("")); + } +} +function isSet(value) { + return value !== null && value !== undefined; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/index.d.ts new file mode 100644 index 0000000..26dd215 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/index.d.ts @@ -0,0 +1,46 @@ +/// +import { Entry } from '../../tlog'; +import { x509Certificate } from '../../x509/cert'; +import { SignatureMaterial } from '../signature'; +import { WithRequired } from '../utility'; +import { ValidBundle } from './validate'; +import { Envelope } from './__generated__/envelope'; +import { Bundle, VerificationMaterial } from './__generated__/sigstore_bundle'; +import { TransparencyLogEntry } from './__generated__/sigstore_rekor'; +import { ArtifactVerificationOptions } from './__generated__/sigstore_verification'; +export * from './serialized'; +export * from './validate'; +export * from './__generated__/envelope'; +export * from './__generated__/sigstore_bundle'; +export * from './__generated__/sigstore_common'; +export { TransparencyLogEntry } from './__generated__/sigstore_rekor'; +export * from './__generated__/sigstore_trustroot'; +export * from './__generated__/sigstore_verification'; +export declare const bundleToJSON: (message: Bundle) => unknown; +export declare const bundleFromJSON: (obj: any) => ValidBundle; +export declare const envelopeToJSON: (message: Envelope) => unknown; +export declare const envelopeFromJSON: (object: any) => Envelope; +export type BundleWithVerificationMaterial = WithRequired; +export declare function isBundleWithVerificationMaterial(bundle: Bundle): bundle is BundleWithVerificationMaterial; +export type BundleWithCertificateChain = Bundle & { + verificationMaterial: VerificationMaterial & { + content: Extract; + }; +}; +export declare function isBundleWithCertificateChain(bundle: Bundle): bundle is BundleWithCertificateChain; +export type RequiredArtifactVerificationOptions = WithRequired; +export type CAArtifactVerificationOptions = WithRequired & { + signers?: Extract; +}; +export declare function isCAVerificationOptions(options: ArtifactVerificationOptions): options is CAArtifactVerificationOptions; +export type VerifiableTransparencyLogEntry = WithRequired; +export declare function isVerifiableTransparencyLogEntry(entry: TransparencyLogEntry): entry is VerifiableTransparencyLogEntry; +export declare const bundle: { + toDSSEBundle: (envelope: Envelope, signature: SignatureMaterial, rekorEntry: Entry) => Bundle; + toMessageSignatureBundle: (digest: Buffer, signature: SignatureMaterial, rekorEntry: Entry) => Bundle; +}; +export declare function signingCertificate(bundle: Bundle): x509Certificate | undefined; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/index.js new file mode 100644 index 0000000..df07d6d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/index.js @@ -0,0 +1,144 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.signingCertificate = exports.bundle = exports.isVerifiableTransparencyLogEntry = exports.isCAVerificationOptions = exports.isBundleWithCertificateChain = exports.isBundleWithVerificationMaterial = exports.envelopeFromJSON = exports.envelopeToJSON = exports.bundleFromJSON = exports.bundleToJSON = exports.TransparencyLogEntry = void 0; +const util_1 = require("../../util"); +const cert_1 = require("../../x509/cert"); +const validate_1 = require("./validate"); +const envelope_1 = require("./__generated__/envelope"); +const sigstore_bundle_1 = require("./__generated__/sigstore_bundle"); +const sigstore_common_1 = require("./__generated__/sigstore_common"); +__exportStar(require("./serialized"), exports); +__exportStar(require("./validate"), exports); +__exportStar(require("./__generated__/envelope"), exports); +__exportStar(require("./__generated__/sigstore_bundle"), exports); +__exportStar(require("./__generated__/sigstore_common"), exports); +var sigstore_rekor_1 = require("./__generated__/sigstore_rekor"); +Object.defineProperty(exports, "TransparencyLogEntry", { enumerable: true, get: function () { return sigstore_rekor_1.TransparencyLogEntry; } }); +__exportStar(require("./__generated__/sigstore_trustroot"), exports); +__exportStar(require("./__generated__/sigstore_verification"), exports); +exports.bundleToJSON = sigstore_bundle_1.Bundle.toJSON; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const bundleFromJSON = (obj) => { + const bundle = sigstore_bundle_1.Bundle.fromJSON(obj); + (0, validate_1.assertValidBundle)(bundle); + return bundle; +}; +exports.bundleFromJSON = bundleFromJSON; +exports.envelopeToJSON = envelope_1.Envelope.toJSON; +exports.envelopeFromJSON = envelope_1.Envelope.fromJSON; +const BUNDLE_MEDIA_TYPE = 'application/vnd.dev.sigstore.bundle+json;version=0.1'; +// Type guard for narrowing a Bundle to a BundleWithVerificationMaterial +function isBundleWithVerificationMaterial(bundle) { + return bundle.verificationMaterial !== undefined; +} +exports.isBundleWithVerificationMaterial = isBundleWithVerificationMaterial; +// Type guard for narrowing a Bundle to a BundleWithCertificateChain +function isBundleWithCertificateChain(bundle) { + return (isBundleWithVerificationMaterial(bundle) && + bundle.verificationMaterial.content !== undefined && + bundle.verificationMaterial.content.$case === 'x509CertificateChain'); +} +exports.isBundleWithCertificateChain = isBundleWithCertificateChain; +function isCAVerificationOptions(options) { + return (options.ctlogOptions !== undefined && + (options.signers === undefined || + options.signers.$case === 'certificateIdentities')); +} +exports.isCAVerificationOptions = isCAVerificationOptions; +function isVerifiableTransparencyLogEntry(entry) { + return (entry.logId !== undefined && + entry.inclusionPromise !== undefined && + entry.kindVersion !== undefined); +} +exports.isVerifiableTransparencyLogEntry = isVerifiableTransparencyLogEntry; +exports.bundle = { + toDSSEBundle: (envelope, signature, rekorEntry) => ({ + mediaType: BUNDLE_MEDIA_TYPE, + content: { + $case: 'dsseEnvelope', + dsseEnvelope: envelope, + }, + verificationMaterial: toVerificationMaterial(signature, rekorEntry), + }), + toMessageSignatureBundle: (digest, signature, rekorEntry) => ({ + mediaType: BUNDLE_MEDIA_TYPE, + content: { + $case: 'messageSignature', + messageSignature: { + messageDigest: { + algorithm: sigstore_common_1.HashAlgorithm.SHA2_256, + digest: digest, + }, + signature: signature.signature, + }, + }, + verificationMaterial: toVerificationMaterial(signature, rekorEntry), + }), +}; +function toTransparencyLogEntry(entry) { + const set = Buffer.from(entry.verification.signedEntryTimestamp, 'base64'); + const logID = Buffer.from(entry.logID, 'hex'); + // Parse entry body so we can extract the kind and version. + const bodyJSON = util_1.encoding.base64Decode(entry.body); + const entryBody = JSON.parse(bodyJSON); + return { + inclusionPromise: { + signedEntryTimestamp: set, + }, + logIndex: entry.logIndex.toString(), + logId: { + keyId: logID, + }, + integratedTime: entry.integratedTime.toString(), + kindVersion: { + kind: entryBody.kind, + version: entryBody.apiVersion, + }, + inclusionProof: undefined, + canonicalizedBody: Buffer.from(entry.body, 'base64'), + }; +} +function toVerificationMaterial(signature, entry) { + return { + content: signature.certificates + ? toVerificationMaterialx509CertificateChain(signature.certificates) + : toVerificationMaterialPublicKey(signature.key.id || ''), + tlogEntries: [toTransparencyLogEntry(entry)], + timestampVerificationData: undefined, + }; +} +function toVerificationMaterialx509CertificateChain(certificates) { + return { + $case: 'x509CertificateChain', + x509CertificateChain: { + certificates: certificates.map((c) => ({ + rawBytes: util_1.pem.toDER(c), + })), + }, + }; +} +function toVerificationMaterialPublicKey(hint) { + return { $case: 'publicKey', publicKey: { hint } }; +} +function signingCertificate(bundle) { + if (!isBundleWithCertificateChain(bundle)) { + return undefined; + } + const signingCert = bundle.verificationMaterial.content.x509CertificateChain.certificates[0]; + return cert_1.x509Certificate.parse(signingCert.rawBytes); +} +exports.signingCertificate = signingCertificate; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/serialized.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/serialized.d.ts new file mode 100644 index 0000000..31cb2ce --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/serialized.d.ts @@ -0,0 +1,74 @@ +import { OneOf } from '../utility'; +type SerializedTLogEntry = { + logIndex: string; + logId: { + keyId: string; + }; + kindVersion: { + kind: string; + version: string; + } | undefined; + integratedTime: string; + inclusionPromise: { + signedEntryTimestamp: string; + }; + inclusionProof: { + logIndex: string; + rootHash: string; + treeSize: string; + hashes: string[]; + checkpoint: { + envelope: string; + }; + } | undefined; + canonicalizedBody: string; +}; +type SerializedTimestampVerificationData = { + rfc3161Timestamps: { + signedTimestamp: string; + }[]; +}; +type SerializedMessageSignature = { + messageDigest: { + algorithm: string; + digest: string; + } | undefined; + signature: string; +}; +type SerializedDSSEEnvelope = { + payload: string; + payloadType: string; + signatures: { + sig: string; + keyid: string; + }[]; +}; +export type SerializedBundle = { + mediaType: string; + verificationMaterial: (OneOf<{ + x509CertificateChain: { + certificates: { + rawBytes: string; + }[]; + }; + publicKey: { + hint: string; + }; + }> | undefined) & { + tlogEntries: SerializedTLogEntry[]; + timestampVerificationData: SerializedTimestampVerificationData | undefined; + }; +} & OneOf<{ + dsseEnvelope: SerializedDSSEEnvelope; + messageSignature: SerializedMessageSignature; +}>; +interface SerializedSignature { + sig: string; + keyid: string; +} +export type SerializedEnvelope = { + payload: string; + payloadType: string; + signatures: SerializedSignature[]; +}; +export {}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/serialized.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/serialized.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/serialized.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/validate.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/validate.d.ts new file mode 100644 index 0000000..fd0a354 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/validate.d.ts @@ -0,0 +1,16 @@ +import { WithRequired } from '../utility'; +import { Bundle, VerificationMaterial } from './__generated__/sigstore_bundle'; +import { MessageSignature } from './__generated__/sigstore_common'; +export type ValidBundle = Bundle & { + verificationMaterial: VerificationMaterial & { + content: NonNullable; + }; + content: (Extract & { + messageSignature: WithRequired; + }) | Extract; +}; +export declare function assertValidBundle(b: Bundle): asserts b is ValidBundle; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/validate.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/validate.js new file mode 100644 index 0000000..a19d8ad --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/sigstore/validate.js @@ -0,0 +1,88 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.assertValidBundle = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = require("../../error"); +// Performs basic validation of a Sigstore bundle to ensure that all required +// fields are populated. This is not a complete validation of the bundle, but +// rather a check that the bundle is in a valid state to be processed by the +// rest of the code. +function assertValidBundle(b) { + const invalidValues = []; + // Content-related validation + if (b.content === undefined) { + invalidValues.push('content'); + } + else { + switch (b.content.$case) { + case 'messageSignature': + if (b.content.messageSignature.messageDigest === undefined) { + invalidValues.push('content.messageSignature.messageDigest'); + } + else { + if (b.content.messageSignature.messageDigest.digest.length === 0) { + invalidValues.push('content.messageSignature.messageDigest.digest'); + } + } + if (b.content.messageSignature.signature.length === 0) { + invalidValues.push('content.messageSignature.signature'); + } + break; + case 'dsseEnvelope': + if (b.content.dsseEnvelope.payload.length === 0) { + invalidValues.push('content.dsseEnvelope.payload'); + } + if (b.content.dsseEnvelope.signatures.length !== 1) { + invalidValues.push('content.dsseEnvelope.signatures'); + } + else { + if (b.content.dsseEnvelope.signatures[0].sig.length === 0) { + invalidValues.push('content.dsseEnvelope.signatures[0].sig'); + } + } + break; + } + } + // Verification material-related validation + if (b.verificationMaterial === undefined) { + invalidValues.push('verificationMaterial'); + } + else { + if (b.verificationMaterial.content === undefined) { + invalidValues.push('verificationMaterial.content'); + } + else { + switch (b.verificationMaterial.content.$case) { + case 'x509CertificateChain': + if (b.verificationMaterial.content.x509CertificateChain.certificates + .length === 0) { + invalidValues.push('verificationMaterial.content.x509CertificateChain.certificates'); + } + b.verificationMaterial.content.x509CertificateChain.certificates.forEach((cert, i) => { + if (cert.rawBytes.length === 0) { + invalidValues.push(`verificationMaterial.content.x509CertificateChain.certificates[${i}].rawBytes`); + } + }); + break; + } + } + } + if (invalidValues.length > 0) { + throw new error_1.ValidationError(`invalid/missing bundle values: ${invalidValues.join(', ')}`); + } +} +exports.assertValidBundle = assertValidBundle; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/utility.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/utility.d.ts new file mode 100644 index 0000000..df993d5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/utility.d.ts @@ -0,0 +1,14 @@ +type ValueOf = Obj[keyof Obj]; +type OneOnly = { + [key in Exclude]: undefined; +} & { + [key in K]: Obj[K]; +}; +type OneOfByKey = { + [key in keyof Obj]: OneOnly; +}; +export type OneOf = ValueOf>; +export type WithRequired = T & { + [P in K]-?: NonNullable; +}; +export {}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/types/utility.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/utility.js new file mode 100644 index 0000000..132848c --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/types/utility.js @@ -0,0 +1,18 @@ +"use strict"; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +// https://dev.to/maxime1992/implement-a-generic-oneof-type-with-typescript-22em +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/crypto.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/crypto.d.ts new file mode 100644 index 0000000..a726dd2 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/crypto.d.ts @@ -0,0 +1,10 @@ +/// +/// +/// +import { BinaryLike, KeyLike, KeyPairKeyObjectResult } from 'crypto'; +export declare function generateKeyPair(): KeyPairKeyObjectResult; +export declare function createPublicKey(key: string | Buffer): KeyLike; +export declare function signBlob(data: NodeJS.ArrayBufferView, privateKey: KeyLike): Buffer; +export declare function verifyBlob(data: Buffer, key: KeyLike, signature: Buffer, algorithm?: string): boolean; +export declare function hash(data: BinaryLike): Buffer; +export declare function randomBytes(count: number): Buffer; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/crypto.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/crypto.js new file mode 100644 index 0000000..0b1e0bc --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/crypto.js @@ -0,0 +1,64 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.randomBytes = exports.hash = exports.verifyBlob = exports.signBlob = exports.createPublicKey = exports.generateKeyPair = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const crypto_1 = __importDefault(require("crypto")); +const EC_KEYPAIR_TYPE = 'ec'; +const P256_CURVE = 'P-256'; +const SHA256_ALGORITHM = 'sha256'; +function generateKeyPair() { + return crypto_1.default.generateKeyPairSync(EC_KEYPAIR_TYPE, { + namedCurve: P256_CURVE, + }); +} +exports.generateKeyPair = generateKeyPair; +function createPublicKey(key) { + if (typeof key === 'string') { + return crypto_1.default.createPublicKey(key); + } + else { + return crypto_1.default.createPublicKey({ key, format: 'der', type: 'spki' }); + } +} +exports.createPublicKey = createPublicKey; +function signBlob(data, privateKey) { + return crypto_1.default.sign(null, data, privateKey); +} +exports.signBlob = signBlob; +function verifyBlob(data, key, signature, algorithm) { + // The try/catch is to work around an issue in Node 14.x where verify throws + // an error in some scenarios if the signature is invalid. + try { + return crypto_1.default.verify(algorithm, data, key, signature); + } + catch (e) { + return false; + } +} +exports.verifyBlob = verifyBlob; +function hash(data) { + const hash = crypto_1.default.createHash(SHA256_ALGORITHM); + return hash.update(data).digest(); +} +exports.hash = hash; +function randomBytes(count) { + return crypto_1.default.randomBytes(count); +} +exports.randomBytes = randomBytes; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/dsse.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/dsse.d.ts new file mode 100644 index 0000000..839b9c0 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/dsse.d.ts @@ -0,0 +1,2 @@ +/// +export declare function preAuthEncoding(payloadType: string, payload: Buffer): Buffer; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/dsse.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/dsse.js new file mode 100644 index 0000000..bba7baa --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/dsse.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.preAuthEncoding = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const PAE_PREFIX = 'DSSEv1'; +// DSSE Pre-Authentication Encoding +function preAuthEncoding(payloadType, payload) { + const prefix = Buffer.from(`${PAE_PREFIX} ${payloadType.length} ${payloadType} ${payload.length} `, 'ascii'); + return Buffer.concat([prefix, payload]); +} +exports.preAuthEncoding = preAuthEncoding; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/encoding.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/encoding.d.ts new file mode 100644 index 0000000..f1347c2 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/encoding.d.ts @@ -0,0 +1,6 @@ +export declare function base64Encode(str: string): string; +export declare function base64Decode(str: string): string; +export declare function base64URLEncode(str: string): string; +export declare function base64URLDecode(str: string): string; +export declare function base64URLEscape(str: string): string; +export declare function base64URLUnescape(str: string): string; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/encoding.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/encoding.js new file mode 100644 index 0000000..8674d77 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/encoding.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.base64URLUnescape = exports.base64URLEscape = exports.base64URLDecode = exports.base64URLEncode = exports.base64Decode = exports.base64Encode = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const BASE64_ENCODING = 'base64'; +const UTF8_ENCODING = 'utf-8'; +function base64Encode(str) { + return Buffer.from(str, UTF8_ENCODING).toString(BASE64_ENCODING); +} +exports.base64Encode = base64Encode; +function base64Decode(str) { + return Buffer.from(str, BASE64_ENCODING).toString(UTF8_ENCODING); +} +exports.base64Decode = base64Decode; +function base64URLEncode(str) { + return base64URLEscape(base64Encode(str)); +} +exports.base64URLEncode = base64URLEncode; +function base64URLDecode(str) { + return base64Decode(base64URLUnescape(str)); +} +exports.base64URLDecode = base64URLDecode; +function base64URLEscape(str) { + return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); +} +exports.base64URLEscape = base64URLEscape; +function base64URLUnescape(str) { + // Repad the base64 string if necessary + str += '='.repeat((4 - (str.length % 4)) % 4); + return str.replace(/-/g, '+').replace(/_/g, '/'); +} +exports.base64URLUnescape = base64URLUnescape; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/index.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/index.d.ts new file mode 100644 index 0000000..786a196 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/index.d.ts @@ -0,0 +1,8 @@ +export * as crypto from './crypto'; +export * as dsse from './dsse'; +export * as encoding from './encoding'; +export * as json from './json'; +export * as oidc from './oidc'; +export * as pem from './pem'; +export * as promise from './promise'; +export * as ua from './ua'; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/index.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/index.js new file mode 100644 index 0000000..2c02116 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/index.js @@ -0,0 +1,49 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ua = exports.promise = exports.pem = exports.oidc = exports.json = exports.encoding = exports.dsse = exports.crypto = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +exports.crypto = __importStar(require("./crypto")); +exports.dsse = __importStar(require("./dsse")); +exports.encoding = __importStar(require("./encoding")); +exports.json = __importStar(require("./json")); +exports.oidc = __importStar(require("./oidc")); +exports.pem = __importStar(require("./pem")); +exports.promise = __importStar(require("./promise")); +exports.ua = __importStar(require("./ua")); diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/json.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/json.d.ts new file mode 100644 index 0000000..ed33181 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/json.d.ts @@ -0,0 +1 @@ +export declare function canonicalize(object: any): string; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/json.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/json.js new file mode 100644 index 0000000..69176ad --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/json.js @@ -0,0 +1,61 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.canonicalize = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +// JSON canonicalization per https://github.com/cyberphone/json-canonicalization +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function canonicalize(object) { + let buffer = ''; + if (object === null || typeof object !== 'object' || object.toJSON != null) { + // Primitives or toJSONable objects + buffer += JSON.stringify(object); + } + else if (Array.isArray(object)) { + // Array - maintain element order + buffer += '['; + let first = true; + object.forEach((element) => { + if (!first) { + buffer += ','; + } + first = false; + // recursive call + buffer += canonicalize(element); + }); + buffer += ']'; + } + else { + // Object - Sort properties before serializing + buffer += '{'; + let first = true; + Object.keys(object) + .sort() + .forEach((property) => { + if (!first) { + buffer += ','; + } + first = false; + buffer += JSON.stringify(property); + buffer += ':'; + // recursive call + buffer += canonicalize(object[property]); + }); + buffer += '}'; + } + return buffer; +} +exports.canonicalize = canonicalize; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/oidc.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/oidc.d.ts new file mode 100644 index 0000000..b451389 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/oidc.d.ts @@ -0,0 +1 @@ +export declare function extractJWTSubject(jwt: string): string; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/oidc.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/oidc.js new file mode 100644 index 0000000..05af90d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/oidc.js @@ -0,0 +1,54 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.extractJWTSubject = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const enc = __importStar(require("./encoding")); +function extractJWTSubject(jwt) { + const parts = jwt.split('.', 3); + const payload = JSON.parse(enc.base64Decode(parts[1])); + switch (payload.iss) { + case 'https://accounts.google.com': + case 'https://oauth2.sigstore.dev/auth': + return payload.email; + default: + return payload.sub; + } +} +exports.extractJWTSubject = extractJWTSubject; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/pem.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/pem.d.ts new file mode 100644 index 0000000..cb438c7 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/pem.d.ts @@ -0,0 +1,4 @@ +/// +export declare function split(certificate: string): string[]; +export declare function toDER(certificate: string): Buffer; +export declare function fromDER(certificate: Buffer, type?: string): string; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/pem.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/pem.js new file mode 100644 index 0000000..6bb8eda --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/pem.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fromDER = exports.toDER = exports.split = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const PEM_HEADER = /-----BEGIN (.*)-----/; +const PEM_FOOTER = /-----END (.*)-----/; +// Given a set of PEM-encoded certificates bundled in a single string, returns +// an array of certificates. Standard PEM encoding dictates that each certificate +// should have a trailing newline after the footer. +function split(certificate) { + const certs = []; + let cert = []; + certificate.split('\n').forEach((line) => { + line.includes; + if (line.match(PEM_HEADER)) { + cert = []; + } + if (line.length > 0) { + cert.push(line); + } + if (line.match(PEM_FOOTER)) { + certs.push(cert.join('\n').concat('\n')); + } + }); + return certs; +} +exports.split = split; +function toDER(certificate) { + let der = ''; + certificate.split('\n').forEach((line) => { + if (line.match(PEM_HEADER) || line.match(PEM_FOOTER)) { + return; + } + der += line; + }); + return Buffer.from(der, 'base64'); +} +exports.toDER = toDER; +// Translates a DER-encoded buffer into a PEM-encoded string. Standard PEM +// encoding dictates that each certificate should have a trailing newline after +// the footer. +function fromDER(certificate, type = 'CERTIFICATE') { + // Base64-encode the certificate. + const der = certificate.toString('base64'); + // Split the certificate into lines of 64 characters. + const lines = der.match(/.{1,64}/g) || ''; + return [`-----BEGIN ${type}-----`, ...lines, `-----END ${type}-----`] + .join('\n') + .concat('\n'); +} +exports.fromDER = fromDER; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/promise.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/promise.d.ts new file mode 100644 index 0000000..bbc501a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/promise.d.ts @@ -0,0 +1 @@ +export declare const promiseAny: (values: Iterable>) => Promise; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/promise.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/promise.js new file mode 100644 index 0000000..8101dd4 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/promise.js @@ -0,0 +1,27 @@ +"use strict"; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.promiseAny = void 0; +// Implementation of Promise.any (not available until Node v15). +// We're basically inverting the logic of Promise.all and taking advantage +// of the fact that Promise.all will return early on the first rejection. +// By reversing the resolve/reject logic we can use this to return early +// on the first resolved promise. +const promiseAny = async (values) => { + return Promise.all([...values].map((promise) => new Promise((resolve, reject) => promise.then(reject, resolve)))).then((errors) => Promise.reject(errors), (value) => Promise.resolve(value)); +}; +exports.promiseAny = promiseAny; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/stream.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/stream.d.ts new file mode 100644 index 0000000..4d50956 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/stream.d.ts @@ -0,0 +1,24 @@ +/// +export declare class StreamError extends Error { +} +export declare class ByteStream { + private static BLOCK_SIZE; + private buf; + private view; + private start; + constructor(buffer?: ArrayBuffer); + get buffer(): Buffer; + get length(): number; + get position(): number; + seek(position: number): void; + slice(start: number, len: number): Buffer; + appendChar(char: number): void; + appendUint16(num: number): void; + appendUint24(num: number): void; + appendView(view: Uint8Array): void; + getBlock(size: number): Buffer; + getUint8(): number; + getUint16(): number; + private ensureCapacity; + private realloc; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/stream.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/stream.js new file mode 100644 index 0000000..b5c881b --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/stream.js @@ -0,0 +1,116 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ByteStream = exports.StreamError = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +class StreamError extends Error { +} +exports.StreamError = StreamError; +class ByteStream { + constructor(buffer) { + this.start = 0; + if (buffer) { + this.buf = buffer; + this.view = Buffer.from(buffer); + } + else { + this.buf = new ArrayBuffer(0); + this.view = Buffer.from(this.buf); + } + } + get buffer() { + return this.view.subarray(0, this.start); + } + get length() { + return this.view.byteLength; + } + get position() { + return this.start; + } + seek(position) { + this.start = position; + } + // Returns a Buffer containing the specified number of bytes starting at the + // given start position. + slice(start, len) { + const end = start + len; + if (end > this.length) { + throw new StreamError('request past end of buffer'); + } + return this.view.subarray(start, end); + } + appendChar(char) { + this.ensureCapacity(1); + this.view[this.start] = char; + this.start += 1; + } + appendUint16(num) { + this.ensureCapacity(2); + const value = new Uint16Array([num]); + const view = new Uint8Array(value.buffer); + this.view[this.start] = view[1]; + this.view[this.start + 1] = view[0]; + this.start += 2; + } + appendUint24(num) { + this.ensureCapacity(3); + const value = new Uint32Array([num]); + const view = new Uint8Array(value.buffer); + this.view[this.start] = view[2]; + this.view[this.start + 1] = view[1]; + this.view[this.start + 2] = view[0]; + this.start += 3; + } + appendView(view) { + this.ensureCapacity(view.length); + this.view.set(view, this.start); + this.start += view.length; + } + getBlock(size) { + if (size <= 0) { + return Buffer.alloc(0); + } + if (this.start + size > this.view.length) { + throw new Error('request past end of buffer'); + } + const result = this.view.subarray(this.start, this.start + size); + this.start += size; + return result; + } + getUint8() { + return this.getBlock(1)[0]; + } + getUint16() { + const block = this.getBlock(2); + return (block[0] << 8) | block[1]; + } + ensureCapacity(size) { + if (this.start + size > this.view.byteLength) { + const blockSize = ByteStream.BLOCK_SIZE + (size > ByteStream.BLOCK_SIZE ? size : 0); + this.realloc(this.view.byteLength + blockSize); + } + } + realloc(size) { + const newArray = new ArrayBuffer(size); + const newView = Buffer.from(newArray); + // Copy the old buffer into the new one + newView.set(this.view); + this.buf = newArray; + this.view = newView; + } +} +exports.ByteStream = ByteStream; +ByteStream.BLOCK_SIZE = 1024; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/ua.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/ua.d.ts new file mode 100644 index 0000000..b60e2e9 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/ua.d.ts @@ -0,0 +1 @@ +export declare const getUserAgent: () => string; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/util/ua.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/ua.js new file mode 100644 index 0000000..6db6b5a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/util/ua.js @@ -0,0 +1,33 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getUserAgent = void 0; +/* +Copyright 2022 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const os_1 = __importDefault(require("os")); +// Format User-Agent: / () +// source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent +const getUserAgent = () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const packageVersion = require('../../package.json').version; + const nodeVersion = process.version; + const platformName = os_1.default.platform(); + const archName = os_1.default.arch(); + return `sigstore-js/${packageVersion} (Node ${nodeVersion}) (${platformName}/${archName})`; +}; +exports.getUserAgent = getUserAgent; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/verify.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/verify.d.ts new file mode 100644 index 0000000..819d0da --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/verify.d.ts @@ -0,0 +1,13 @@ +/// +import * as sigstore from './types/sigstore'; +export type KeySelector = (hint: string) => string | Buffer | undefined; +export declare class Verifier { + private trustedRoot; + private keySelector; + constructor(trustedRoot: sigstore.TrustedRoot, keySelector?: KeySelector); + verify(bundle: sigstore.ValidBundle, options: sigstore.RequiredArtifactVerificationOptions, data?: Buffer): void; + private verifyArtifactSignature; + private verifySigningCertificate; + private verifyTLogEntries; + private getPublicKey; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/verify.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/verify.js new file mode 100644 index 0000000..1bcef03 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/verify.js @@ -0,0 +1,142 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Verifier = void 0; +const ca = __importStar(require("./ca/verify")); +const error_1 = require("./error"); +const tlog = __importStar(require("./tlog/verify")); +const sigstore = __importStar(require("./types/sigstore")); +const util_1 = require("./util"); +class Verifier { + constructor(trustedRoot, keySelector) { + this.trustedRoot = trustedRoot; + this.keySelector = keySelector || (() => undefined); + } + // Verifies the bundle signature, the bundle's certificate chain (if present) + // and the bundle's transparency log entries. + verify(bundle, options, data) { + this.verifyArtifactSignature(bundle, options, data); + if (sigstore.isBundleWithCertificateChain(bundle)) { + this.verifySigningCertificate(bundle, options); + } + this.verifyTLogEntries(bundle, options); + } + // Performs bundle signature verification. Determines the type of the bundle + // content and delegates to the appropriate signature verification function. + verifyArtifactSignature(bundle, options, data) { + const publicKey = this.getPublicKey(bundle, options); + switch (bundle.content?.$case) { + case 'messageSignature': + if (!data) { + throw new error_1.VerificationError('no data provided for message signature verification'); + } + verifyMessageSignature(data, bundle.content.messageSignature, publicKey); + break; + case 'dsseEnvelope': + verifyDSSESignature(bundle.content.dsseEnvelope, publicKey); + break; + } + } + // Performs verification of the bundle's certificate chain. The bundle must + // contain a certificate chain and the options must contain the required + // options for CA verification. + // TODO: We've temporarily removed the requirement that the options contain + // the list of trusted signer identities. This will be added back in a future + // release. + verifySigningCertificate(bundle, options) { + if (!sigstore.isCAVerificationOptions(options)) { + throw new error_1.VerificationError('no trusted certificates provided for verification'); + } + ca.verifySigningCertificate(bundle, this.trustedRoot, options); + } + // Performs verification of the bundle's transparency log entries. The bundle + // must contain a list of transparency log entries. + verifyTLogEntries(bundle, options) { + tlog.verifyTLogEntries(bundle, this.trustedRoot, options.tlogOptions); + } + // Returns the public key which will be used to verify the bundle signature. + // The public key is selected based on the verification material in the bundle + // and the options provided. + getPublicKey(bundle, options) { + // Select the key which will be used to verify the signature + switch (bundle.verificationMaterial?.content?.$case) { + // If the bundle contains a certificate chain, the public key is the + // first certificate in the chain (the signing certificate) + case 'x509CertificateChain': + return getPublicKeyFromCertificateChain(bundle.verificationMaterial.content.x509CertificateChain); + // If the bundle contains a public key hint, the public key is selected + // from the list of trusted keys in the options + case 'publicKey': + return getPublicKeyFromHint(bundle.verificationMaterial.content.publicKey, options, this.keySelector); + } + } +} +exports.Verifier = Verifier; +// Retrieves the public key from the first certificate in the certificate chain +function getPublicKeyFromCertificateChain(certificateChain) { + const cert = util_1.pem.fromDER(certificateChain.certificates[0].rawBytes); + return util_1.crypto.createPublicKey(cert); +} +// Retrieves the public key through the key selector callback, passing the +// public key hint from the bundle +function getPublicKeyFromHint(publicKeyID, options, keySelector) { + const key = keySelector(publicKeyID.hint); + if (!key) { + throw new error_1.VerificationError('no public key found for signature verification'); + } + try { + return util_1.crypto.createPublicKey(key); + } + catch (e) { + throw new error_1.VerificationError('invalid public key'); + } +} +// Performs signature verification for bundle containing a message signature. +// Verifies that the digest and signature found in the bundle match the +// provided data. +function verifyMessageSignature(data, messageSignature, publicKey) { + // Extract signature for message + const { signature, messageDigest } = messageSignature; + const calculatedDigest = util_1.crypto.hash(data); + if (!calculatedDigest.equals(messageDigest.digest)) { + throw new error_1.VerificationError('message digest verification failed'); + } + if (!util_1.crypto.verifyBlob(data, publicKey, signature)) { + throw new error_1.VerificationError('artifact signature verification failed'); + } +} +// Performs signature verification for bundle containing a DSSE envelope. +// Calculates the PAE for the DSSE envelope and verifies it against the +// signature in the envelope. +function verifyDSSESignature(envelope, publicKey) { + // Construct payload over which the signature was originally created + const { payloadType, payload } = envelope; + const data = util_1.dsse.preAuthEncoding(payloadType, payload); + // Only support a single signature in DSSE + const signature = envelope.signatures[0].sig; + if (!util_1.crypto.verifyBlob(data, publicKey, signature)) { + throw new error_1.VerificationError('artifact signature verification failed'); + } +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/dump.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/dump.d.ts new file mode 100644 index 0000000..3f192de --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/dump.d.ts @@ -0,0 +1,2 @@ +import { ASN1Obj } from './obj'; +export declare function dump(obj: ASN1Obj, indent?: number): void; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/dump.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/dump.js new file mode 100644 index 0000000..b446054 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/dump.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.dump = void 0; +const tag_1 = require("./tag"); +// Utility function to dump the contents of an ASN1Obj to the console. +function dump(obj, indent = 0) { + let str = ' '.repeat(indent); + str += tagToString(obj.tag) + ' '; + if (obj.tag.isUniversal()) { + switch (obj.tag.number) { + case tag_1.UNIVERSAL_TAG.BOOLEAN: + str += obj.toBoolean(); + break; + case tag_1.UNIVERSAL_TAG.INTEGER: + str += `(${obj.value.length} byte) `; + str += obj.toInteger(); + break; + case tag_1.UNIVERSAL_TAG.BIT_STRING: { + const bits = obj.toBitString(); + str += `(${bits.length} bit) `; + str += truncate(bits.map((bit) => bit.toString()).join('')); + break; + } + case tag_1.UNIVERSAL_TAG.OBJECT_IDENTIFIER: + str += obj.toOID(); + break; + case tag_1.UNIVERSAL_TAG.SEQUENCE: + case tag_1.UNIVERSAL_TAG.SET: + str += `(${obj.subs.length} elem) `; + break; + case tag_1.UNIVERSAL_TAG.PRINTABLE_STRING: + str += obj.value.toString('ascii'); + break; + case tag_1.UNIVERSAL_TAG.UTC_TIME: + case tag_1.UNIVERSAL_TAG.GENERALIZED_TIME: + str += obj.toDate().toUTCString(); + break; + default: + str += `(${obj.value.length} byte) `; + str += isASCII(obj.value) + ? obj.value.toString('ascii') + : truncate(obj.value.toString('hex').toUpperCase()); + } + } + else { + if (obj.tag.constructed) { + str += `(${obj.subs.length} elem) `; + } + else { + str += `(${obj.value.length} byte) `; + str += isASCII(obj.value) + ? obj.value.toString('ascii') + : obj.value.toString('hex').toUpperCase(); + } + } + console.log(str); + // Recursive call for children + obj.subs.forEach((sub) => dump(sub, indent + 2)); +} +exports.dump = dump; +function tagToString(tag) { + if (tag.isContextSpecific()) { + return `[${tag.number.toString(16)}]`; + } + else { + switch (tag.number) { + case tag_1.UNIVERSAL_TAG.BOOLEAN: + return 'BOOLEAN'; + case tag_1.UNIVERSAL_TAG.INTEGER: + return 'INTEGER'; + case tag_1.UNIVERSAL_TAG.BIT_STRING: + return 'BIT STRING'; + case tag_1.UNIVERSAL_TAG.OCTET_STRING: + return 'OCTET STRING'; + case tag_1.UNIVERSAL_TAG.OBJECT_IDENTIFIER: + return 'OBJECT IDENTIFIER'; + case tag_1.UNIVERSAL_TAG.SEQUENCE: + return 'SEQUENCE'; + case tag_1.UNIVERSAL_TAG.SET: + return 'SET'; + case tag_1.UNIVERSAL_TAG.PRINTABLE_STRING: + return 'PrintableString'; + case tag_1.UNIVERSAL_TAG.UTC_TIME: + return 'UTCTime'; + case tag_1.UNIVERSAL_TAG.GENERALIZED_TIME: + return 'GeneralizedTime'; + default: + return tag.number.toString(16); + } + } +} +function isASCII(buf) { + return buf.every((b) => b >= 32 && b <= 126); +} +function truncate(str) { + return str.length > 70 ? str.substring(0, 69) + '...' : str; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/error.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/error.d.ts new file mode 100644 index 0000000..fcd908f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/error.d.ts @@ -0,0 +1,4 @@ +export declare class ASN1ParseError extends Error { +} +export declare class ASN1TypeError extends Error { +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/error.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/error.js new file mode 100644 index 0000000..17d93b0 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/error.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ASN1TypeError = exports.ASN1ParseError = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +class ASN1ParseError extends Error { +} +exports.ASN1ParseError = ASN1ParseError; +class ASN1TypeError extends Error { +} +exports.ASN1TypeError = ASN1TypeError; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/length.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/length.d.ts new file mode 100644 index 0000000..b9c2a2f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/length.d.ts @@ -0,0 +1,4 @@ +/// +import { ByteStream } from '../../util/stream'; +export declare function decodeLength(stream: ByteStream): number; +export declare function encodeLength(len: number): Buffer; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/length.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/length.js new file mode 100644 index 0000000..36fdaf5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/length.js @@ -0,0 +1,63 @@ +"use strict"; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeLength = exports.decodeLength = void 0; +const error_1 = require("./error"); +// Decodes the length of a DER-encoded ANS.1 element from the supplied stream. +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-length-and-value-bytes +function decodeLength(stream) { + const buf = stream.getUint8(); + // If the most significant bit is UNSET the length is just the value of the + // byte. + if ((buf & 0x80) === 0x00) { + return buf; + } + // Otherwise, the lower 7 bits of the first byte indicate the number of bytes + // that follow to encode the length. + const byteCount = buf & 0x7f; + // Ensure the encoded length can safely fit in a JS number. + if (byteCount > 6) { + throw new error_1.ASN1ParseError('length exceeds 6 byte limit'); + } + // Iterate over the bytes that encode the length. + let len = 0; + for (let i = 0; i < byteCount; i++) { + len = len * 256 + stream.getUint8(); + } + // This is a valid ASN.1 length encoding, but we don't support it. + if (len === 0) { + throw new error_1.ASN1ParseError('indefinite length encoding not supported'); + } + return len; +} +exports.decodeLength = decodeLength; +// Translates the supplied value to a DER-encoded length. +function encodeLength(len) { + if (len < 128) { + return Buffer.from([len]); + } + // Bitwise operations on large numbers are not supported in JS, so we need to + // use BigInts. + let val = BigInt(len); + const bytes = []; + while (val > 0n) { + bytes.unshift(Number(val & 255n)); + val = val >> 8n; + } + return Buffer.from([0x80 | bytes.length, ...bytes]); +} +exports.encodeLength = encodeLength; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/obj.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/obj.d.ts new file mode 100644 index 0000000..7f70a0a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/obj.d.ts @@ -0,0 +1,18 @@ +/// +import { ASN1Tag } from './tag'; +export declare class ASN1Obj { + readonly tag: ASN1Tag; + readonly subs: ASN1Obj[]; + private buf; + private headerLength; + constructor(tag: ASN1Tag, headerLength: number, buf: Buffer, subs: ASN1Obj[]); + static parseBuffer(buf: Buffer): ASN1Obj; + get value(): Buffer; + get raw(): Buffer; + toDER(): Buffer; + toBoolean(): boolean; + toInteger(): bigint; + toOID(): string; + toDate(): Date; + toBitString(): number[]; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/obj.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/obj.js new file mode 100644 index 0000000..9e67edc --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/obj.js @@ -0,0 +1,166 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ASN1Obj = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const stream_1 = require("../../util/stream"); +const error_1 = require("./error"); +const length_1 = require("./length"); +const parse_1 = require("./parse"); +const tag_1 = require("./tag"); +class ASN1Obj { + constructor(tag, headerLength, buf, subs) { + this.tag = tag; + this.headerLength = headerLength; + this.buf = buf; + this.subs = subs; + } + // Constructs an ASN.1 object from a Buffer of DER-encoded bytes. + static parseBuffer(buf) { + return parseStream(new stream_1.ByteStream(buf)); + } + // Returns the raw bytes of the ASN.1 object's value. For constructed objects, + // this is the concatenation of the raw bytes of the values of its children. + // For primitive objects, this is the raw bytes of the object's value. + // Use the various to* methods to parse the value into a specific type. + get value() { + return this.buf.subarray(this.headerLength); + } + // Returns the raw bytes of the entire ASN.1 object (including tag, length, + // and value) + get raw() { + return this.buf; + } + toDER() { + const valueStream = new stream_1.ByteStream(); + if (this.subs.length > 0) { + for (const sub of this.subs) { + valueStream.appendView(sub.toDER()); + } + } + else { + valueStream.appendView(this.value); + } + const value = valueStream.buffer; + // Concat tag/length/value + const obj = new stream_1.ByteStream(); + obj.appendChar(this.tag.toDER()); + obj.appendView((0, length_1.encodeLength)(value.length)); + obj.appendView(value); + return obj.buffer; + } + ///////////////////////////////////////////////////////////////////////////// + // Convenience methods for parsing ASN.1 primitives into JS types + // Returns the ASN.1 object's value as a boolean. Throws an error if the + // object is not a boolean. + toBoolean() { + if (!this.tag.isBoolean()) { + throw new error_1.ASN1TypeError('not a boolean'); + } + return (0, parse_1.parseBoolean)(this.value); + } + // Returns the ASN.1 object's value as a BigInt. Throws an error if the + // object is not an integer. + toInteger() { + if (!this.tag.isInteger()) { + throw new error_1.ASN1TypeError('not an integer'); + } + return (0, parse_1.parseInteger)(this.value); + } + // Returns the ASN.1 object's value as an OID string. Throws an error if the + // object is not an OID. + toOID() { + if (!this.tag.isOID()) { + throw new error_1.ASN1TypeError('not an OID'); + } + return (0, parse_1.parseOID)(this.value); + } + // Returns the ASN.1 object's value as a Date. Throws an error if the object + // is not either a UTCTime or a GeneralizedTime. + toDate() { + switch (true) { + case this.tag.isUTCTime(): + return (0, parse_1.parseTime)(this.value, true); + case this.tag.isGeneralizedTime(): + return (0, parse_1.parseTime)(this.value, false); + default: + throw new error_1.ASN1TypeError('not a date'); + } + } + // Returns the ASN.1 object's value as a number[] where each number is the + // value of a bit in the bit string. Throws an error if the object is not a + // bit string. + toBitString() { + if (!this.tag.isBitString()) { + throw new error_1.ASN1TypeError('not a bit string'); + } + return (0, parse_1.parseBitString)(this.value); + } +} +exports.ASN1Obj = ASN1Obj; +///////////////////////////////////////////////////////////////////////////// +// Internal stream parsing functions +function parseStream(stream) { + // Capture current stream position so we know where this object starts + const startPos = stream.position; + // Parse tag and length from stream + const tag = new tag_1.ASN1Tag(stream.getUint8()); + const len = (0, length_1.decodeLength)(stream); + // Calculate length of header (tag + length) + const header = stream.position - startPos; + let subs = []; + // If the object is constructed, parse its children. Sometimes, children + // are embedded in OCTESTRING objects, so we need to check those + // for children as well. + if (tag.constructed) { + subs = collectSubs(stream, len); + } + else if (tag.isOctetString()) { + // Attempt to parse children of OCTETSTRING objects. If anything fails, + // assume the object is not constructed and treat as primitive. + try { + subs = collectSubs(stream, len); + } + catch (e) { + // Fail silently and treat as primitive + } + } + // If there are no children, move stream cursor to the end of the object + if (subs.length === 0) { + stream.seek(startPos + header + len); + } + // Capture the raw bytes of the object (including tag, length, and value) + const buf = stream.slice(startPos, header + len); + return new ASN1Obj(tag, header, buf, subs); +} +function collectSubs(stream, len) { + // Calculate end of object content + const end = stream.position + len; + // Make sure there are enough bytes left in the stream + if (end > stream.length) { + throw new error_1.ASN1ParseError('invalid length'); + } + // Parse all children + const subs = []; + while (stream.position < end) { + subs.push(parseStream(stream)); + } + // When we're done parsing children, we should be at the end of the object + if (stream.position !== end) { + throw new error_1.ASN1ParseError('invalid length'); + } + return subs; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/parse.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/parse.d.ts new file mode 100644 index 0000000..35989d5 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/parse.d.ts @@ -0,0 +1,7 @@ +/// +export declare function parseInteger(buf: Buffer): bigint; +export declare function parseStringASCII(buf: Buffer): string; +export declare function parseTime(buf: Buffer, shortYear: boolean): Date; +export declare function parseOID(buf: Buffer): string; +export declare function parseBoolean(buf: Buffer): boolean; +export declare function parseBitString(buf: Buffer): number[]; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/parse.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/parse.js new file mode 100644 index 0000000..ad50a8f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/parse.js @@ -0,0 +1,125 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseBitString = exports.parseBoolean = exports.parseOID = exports.parseTime = exports.parseStringASCII = exports.parseInteger = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const RE_TIME_SHORT_YEAR = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/; +const RE_TIME_LONG_YEAR = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/; +// Parse a BigInt from the DER-encoded buffer +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-integer +function parseInteger(buf) { + let pos = 0; + const end = buf.length; + let val = buf[pos]; + const neg = val > 0x7f; + // Consume any padding bytes + const pad = neg ? 0xff : 0x00; + while (val == pad && ++pos < end) { + val = buf[pos]; + } + // Calculate remaining bytes to read + const len = end - pos; + if (len === 0) + return BigInt(neg ? -1 : 0); + // Handle two's complement for negative numbers + val = neg ? val - 256 : val; + // Parse remaining bytes + let n = BigInt(val); + for (let i = pos + 1; i < end; ++i) { + n = n * BigInt(256) + BigInt(buf[i]); + } + return n; +} +exports.parseInteger = parseInteger; +// Parse an ASCII string from the DER-encoded buffer +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean +function parseStringASCII(buf) { + return buf.toString('ascii'); +} +exports.parseStringASCII = parseStringASCII; +// Parse a Date from the DER-encoded buffer +// https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5.1 +function parseTime(buf, shortYear) { + const timeStr = parseStringASCII(buf); + // Parse the time string into matches - captured groups start at index 1 + const m = shortYear + ? RE_TIME_SHORT_YEAR.exec(timeStr) + : RE_TIME_LONG_YEAR.exec(timeStr); + if (!m) { + throw new Error('invalid time'); + } + // Translate dates with a 2-digit year to 4 digits per the spec + if (shortYear) { + let year = Number(m[1]); + year += year >= 50 ? 1900 : 2000; + m[1] = year.toString(); + } + // Translate to ISO8601 format and parse + return new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`); +} +exports.parseTime = parseTime; +// Parse an OID from the DER-encoded buffer +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier +function parseOID(buf) { + let pos = 0; + const end = buf.length; + // Consume first byte which encodes the first two OID components + let n = buf[pos++]; + const first = Math.floor(n / 40); + const second = n % 40; + let oid = `${first}.${second}`; + // Consume remaining bytes + let val = 0; + for (; pos < end; ++pos) { + n = buf[pos]; + val = (val << 7) + (n & 0x7f); + // If the left-most bit is NOT set, then this is the last byte in the + // sequence and we can add the value to the OID and reset the accumulator + if ((n & 0x80) === 0) { + oid += `.${val}`; + val = 0; + } + } + return oid; +} +exports.parseOID = parseOID; +// Parse a boolean from the DER-encoded buffer +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-basic-types#boolean +function parseBoolean(buf) { + return buf[0] !== 0; +} +exports.parseBoolean = parseBoolean; +// Parse a bit string from the DER-encoded buffer +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-bit-string +function parseBitString(buf) { + // First byte tell us how many unused bits are in the last byte + const unused = buf[0]; + const start = 1; + const end = buf.length; + const bits = []; + for (let i = start; i < end; ++i) { + const byte = buf[i]; + // The skip value is only used for the last byte + const skip = i === end - 1 ? unused : 0; + // Iterate over each bit in the byte (most significant first) + for (let j = 7; j >= skip; --j) { + // Read the bit and add it to the bit string + bits.push((byte >> j) & 0x01); + } + } + return bits; +} +exports.parseBitString = parseBitString; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/tag.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/tag.d.ts new file mode 100644 index 0000000..cdc9a69 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/tag.d.ts @@ -0,0 +1,28 @@ +export declare const UNIVERSAL_TAG: { + BOOLEAN: number; + INTEGER: number; + BIT_STRING: number; + OCTET_STRING: number; + OBJECT_IDENTIFIER: number; + SEQUENCE: number; + SET: number; + PRINTABLE_STRING: number; + UTC_TIME: number; + GENERALIZED_TIME: number; +}; +export declare class ASN1Tag { + readonly number: number; + readonly constructed: boolean; + readonly class: number; + constructor(enc: number); + isUniversal(): boolean; + isContextSpecific(num?: number): boolean; + isBoolean(): boolean; + isInteger(): boolean; + isBitString(): boolean; + isOctetString(): boolean; + isOID(): boolean; + isUTCTime(): boolean; + isGeneralizedTime(): boolean; + toDER(): number; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/tag.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/tag.js new file mode 100644 index 0000000..ecd4fd0 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/asn1/tag.js @@ -0,0 +1,86 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ASN1Tag = exports.UNIVERSAL_TAG = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = require("./error"); +exports.UNIVERSAL_TAG = { + BOOLEAN: 0x01, + INTEGER: 0x02, + BIT_STRING: 0x03, + OCTET_STRING: 0x04, + OBJECT_IDENTIFIER: 0x06, + SEQUENCE: 0x10, + SET: 0x11, + PRINTABLE_STRING: 0x13, + UTC_TIME: 0x17, + GENERALIZED_TIME: 0x18, +}; +const TAG_CLASS = { + UNIVERSAL: 0x00, + APPLICATION: 0x01, + CONTEXT_SPECIFIC: 0x02, + PRIVATE: 0x03, +}; +// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-tag-bytes +class ASN1Tag { + constructor(enc) { + // Bits 0 through 4 are the tag number + this.number = enc & 0x1f; + // Bit 5 is the constructed bit + this.constructed = (enc & 0x20) === 0x20; + // Bit 6 & 7 are the class + this.class = enc >> 6; + if (this.number === 0x1f) { + throw new error_1.ASN1ParseError('long form tags not supported'); + } + if (this.class === TAG_CLASS.UNIVERSAL && this.number === 0x00) { + throw new error_1.ASN1ParseError('unsupported tag 0x00'); + } + } + isUniversal() { + return this.class === TAG_CLASS.UNIVERSAL; + } + isContextSpecific(num) { + const res = this.class === TAG_CLASS.CONTEXT_SPECIFIC; + return num !== undefined ? res && this.number === num : res; + } + isBoolean() { + return this.isUniversal() && this.number === exports.UNIVERSAL_TAG.BOOLEAN; + } + isInteger() { + return this.isUniversal() && this.number === exports.UNIVERSAL_TAG.INTEGER; + } + isBitString() { + return this.isUniversal() && this.number === exports.UNIVERSAL_TAG.BIT_STRING; + } + isOctetString() { + return this.isUniversal() && this.number === exports.UNIVERSAL_TAG.OCTET_STRING; + } + isOID() { + return (this.isUniversal() && this.number === exports.UNIVERSAL_TAG.OBJECT_IDENTIFIER); + } + isUTCTime() { + return this.isUniversal() && this.number === exports.UNIVERSAL_TAG.UTC_TIME; + } + isGeneralizedTime() { + return this.isUniversal() && this.number === exports.UNIVERSAL_TAG.GENERALIZED_TIME; + } + toDER() { + return this.number | (this.constructed ? 0x20 : 0x00) | (this.class << 6); + } +} +exports.ASN1Tag = ASN1Tag; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/cert.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/cert.d.ts new file mode 100644 index 0000000..6f0f2f3 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/cert.d.ts @@ -0,0 +1,48 @@ +/// +import * as sigstore from '../types/sigstore'; +import { ASN1Obj } from './asn1/obj'; +import { x509AuthorityKeyIDExtension, x509BasicConstraintsExtension, x509Extension, x509KeyUsageExtension, x509SCTExtension, x509SubjectAlternativeNameExtension, x509SubjectKeyIDExtension } from './ext'; +interface SCTVerificationResult { + verified: boolean; + logID: Buffer; +} +export declare class x509Certificate { + root: ASN1Obj; + constructor(asn1: ASN1Obj); + static parse(cert: Buffer | string): x509Certificate; + get tbsCertificate(): ASN1Obj; + get version(): string; + get notBefore(): Date; + get notAfter(): Date; + get issuer(): Buffer; + get subject(): Buffer; + get publicKey(): Buffer; + get signatureAlgorithm(): string; + get signatureValue(): Buffer; + get extensions(): ASN1Obj[]; + get extKeyUsage(): x509KeyUsageExtension | undefined; + get extBasicConstraints(): x509BasicConstraintsExtension | undefined; + get extSubjectAltName(): x509SubjectAlternativeNameExtension | undefined; + get extAuthorityKeyID(): x509AuthorityKeyIDExtension | undefined; + get extSubjectKeyID(): x509SubjectKeyIDExtension | undefined; + get extSCT(): x509SCTExtension | undefined; + get isCA(): boolean; + extension(oid: string): x509Extension | undefined; + verify(issuerCertificate?: x509Certificate): boolean; + validForDate(date: Date): boolean; + equals(other: x509Certificate): boolean; + verifySCTs(issuer: x509Certificate, logs: sigstore.TransparencyLogInstance[]): SCTVerificationResult[]; + private clone; + private findExtension; + private checkRecognizedExtensions; + private get tbsCertificateObj(); + private get signatureAlgorithmObj(); + private get signatureValueObj(); + private get versionObj(); + private get issuerObj(); + private get validityObj(); + private get subjectObj(); + private get subjectPublicKeyInfoObj(); + private get extensionsObj(); +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/cert.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/cert.js new file mode 100644 index 0000000..55cf22f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/cert.js @@ -0,0 +1,241 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.x509Certificate = void 0; +const util_1 = require("../util"); +const stream_1 = require("../util/stream"); +const obj_1 = require("./asn1/obj"); +const ext_1 = require("./ext"); +const EXTENSION_OID_SUBJECT_KEY_ID = '2.5.29.14'; +const EXTENSION_OID_KEY_USAGE = '2.5.29.15'; +const EXTENSION_OID_SUBJECT_ALT_NAME = '2.5.29.17'; +const EXTENSION_OID_BASIC_CONSTRAINTS = '2.5.29.19'; +const EXTENSION_OID_AUTHORITY_KEY_ID = '2.5.29.35'; +const EXTENSION_OID_SCT = '1.3.6.1.4.1.11129.2.4.2'; +// List of recognized critical extensions +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2 +const RECOGNIZED_EXTENSIONS = [ + EXTENSION_OID_KEY_USAGE, + EXTENSION_OID_BASIC_CONSTRAINTS, + EXTENSION_OID_SUBJECT_ALT_NAME, +]; +const ECDSA_SIGNATURE_ALGOS = { + '1.2.840.10045.4.3.1': 'sha224', + '1.2.840.10045.4.3.2': 'sha256', + '1.2.840.10045.4.3.3': 'sha384', + '1.2.840.10045.4.3.4': 'sha512', +}; +class x509Certificate { + constructor(asn1) { + this.root = asn1; + if (!this.checkRecognizedExtensions()) { + throw new Error('Certificate contains unrecognized critical extensions'); + } + } + static parse(cert) { + const der = typeof cert === 'string' ? util_1.pem.toDER(cert) : cert; + const asn1 = obj_1.ASN1Obj.parseBuffer(der); + return new x509Certificate(asn1); + } + get tbsCertificate() { + return this.tbsCertificateObj; + } + get version() { + // version number is the first element of the version context specific tag + const ver = this.versionObj.subs[0].toInteger(); + return `v${(ver + BigInt(1)).toString()}`; + } + get notBefore() { + // notBefore is the first element of the validity sequence + return this.validityObj.subs[0].toDate(); + } + get notAfter() { + // notAfter is the second element of the validity sequence + return this.validityObj.subs[1].toDate(); + } + get issuer() { + return this.issuerObj.value; + } + get subject() { + return this.subjectObj.value; + } + get publicKey() { + return this.subjectPublicKeyInfoObj.raw; + } + get signatureAlgorithm() { + const oid = this.signatureAlgorithmObj.subs[0].toOID(); + return ECDSA_SIGNATURE_ALGOS[oid]; + } + get signatureValue() { + // Signature value is a bit string, so we need to skip the first byte + return this.signatureValueObj.value.subarray(1); + } + get extensions() { + // The extension list is the first (and only) element of the extensions + // context specific tag + const extSeq = this.extensionsObj?.subs[0]; + return extSeq?.subs || []; + } + get extKeyUsage() { + const ext = this.findExtension(EXTENSION_OID_KEY_USAGE); + return ext ? new ext_1.x509KeyUsageExtension(ext) : undefined; + } + get extBasicConstraints() { + const ext = this.findExtension(EXTENSION_OID_BASIC_CONSTRAINTS); + return ext ? new ext_1.x509BasicConstraintsExtension(ext) : undefined; + } + get extSubjectAltName() { + const ext = this.findExtension(EXTENSION_OID_SUBJECT_ALT_NAME); + return ext ? new ext_1.x509SubjectAlternativeNameExtension(ext) : undefined; + } + get extAuthorityKeyID() { + const ext = this.findExtension(EXTENSION_OID_AUTHORITY_KEY_ID); + return ext ? new ext_1.x509AuthorityKeyIDExtension(ext) : undefined; + } + get extSubjectKeyID() { + const ext = this.findExtension(EXTENSION_OID_SUBJECT_KEY_ID); + return ext ? new ext_1.x509SubjectKeyIDExtension(ext) : undefined; + } + get extSCT() { + const ext = this.findExtension(EXTENSION_OID_SCT); + return ext ? new ext_1.x509SCTExtension(ext) : undefined; + } + get isCA() { + const ca = this.extBasicConstraints?.isCA || false; + // If the KeyUsage extension is present, keyCertSign must be set + if (this.extKeyUsage) { + ca && this.extKeyUsage.keyCertSign; + } + return ca; + } + extension(oid) { + const ext = this.findExtension(oid); + return ext ? new ext_1.x509Extension(ext) : undefined; + } + verify(issuerCertificate) { + // Use the issuer's public key if provided, otherwise use the subject's + const publicKey = issuerCertificate?.publicKey || this.publicKey; + const key = util_1.crypto.createPublicKey(publicKey); + return util_1.crypto.verifyBlob(this.tbsCertificate.raw, key, this.signatureValue, this.signatureAlgorithm); + } + validForDate(date) { + return this.notBefore <= date && date <= this.notAfter; + } + equals(other) { + return this.root.raw.equals(other.root.raw); + } + verifySCTs(issuer, logs) { + let extSCT; + // Verifying the SCT requires that we remove the SCT extension and + // re-encode the TBS structure to DER -- this value is part of the data + // over which the signature is calculated. Since this is a destructive action + // we create a copy of the certificate so we can remove the SCT extension + // without affecting the original certificate. + const clone = this.clone(); + // Intentionally not using the findExtension method here because we want to + // remove the the SCT extension from the certificate before calculating the + // PreCert structure + for (let i = 0; i < clone.extensions.length; i++) { + const ext = clone.extensions[i]; + if (ext.subs[0].toOID() === EXTENSION_OID_SCT) { + extSCT = new ext_1.x509SCTExtension(ext); + // Remove the extension from the certificate + clone.extensions.splice(i, 1); + break; + } + } + if (!extSCT) { + throw new Error('Certificate does not contain SCT extension'); + } + if (extSCT?.signedCertificateTimestamps?.length === 0) { + throw new Error('Certificate does not contain any SCTs'); + } + // Construct the PreCert structure + // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 + const preCert = new stream_1.ByteStream(); + // Calculate hash of the issuer's public key + const issuerId = util_1.crypto.hash(issuer.publicKey); + preCert.appendView(issuerId); + // Re-encodes the certificate to DER after removing the SCT extension + const tbs = clone.tbsCertificate.toDER(); + preCert.appendUint24(tbs.length); + preCert.appendView(tbs); + // Calculate and return the verification results for each SCT + return extSCT.signedCertificateTimestamps.map((sct) => ({ + logID: sct.logID, + verified: sct.verify(preCert.buffer, logs), + })); + } + // Creates a copy of the certificate with a new buffer + clone() { + const clone = Buffer.alloc(this.root.raw.length); + this.root.raw.copy(clone); + return x509Certificate.parse(clone); + } + findExtension(oid) { + // Find the extension with the given OID. The OID will always be the first + // element of the extension sequence + return this.extensions.find((ext) => ext.subs[0].toOID() === oid); + } + // A certificate should be considered invalid if it contains critical + // extensions that are not recognized + checkRecognizedExtensions() { + // The extension list is the first (and only) element of the extensions + // context specific tag + const extSeq = this.extensionsObj?.subs[0]; + const exts = extSeq?.subs.map((ext) => new ext_1.x509Extension(ext)); + // Check for unrecognized critical extensions + return (!exts || + exts.every((ext) => !ext.critical || RECOGNIZED_EXTENSIONS.includes(ext.oid))); + } + ///////////////////////////////////////////////////////////////////////////// + // The following properties use the documented x509 structure to locate the + // desired ASN.1 object + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1 + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.1 + get tbsCertificateObj() { + // tbsCertificate is the first element of the certificate sequence + return this.root.subs[0]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.2 + get signatureAlgorithmObj() { + // signatureAlgorithm is the second element of the certificate sequence + return this.root.subs[1]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.1.3 + get signatureValueObj() { + // signatureValue is the third element of the certificate sequence + return this.root.subs[2]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.1 + get versionObj() { + // version is the first element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[0]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.4 + get issuerObj() { + // issuer is the fourth element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[3]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.5 + get validityObj() { + // version is the fifth element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[4]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.6 + get subjectObj() { + // subject is the sixth element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[5]; + } + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.7 + get subjectPublicKeyInfoObj() { + // subjectPublicKeyInfo is the seventh element of the tbsCertificate sequence + return this.tbsCertificateObj.subs[6]; + } + // Extensions can't be located by index because their position varies. Instead, + // we need to find the extensions context specific tag + // https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.9 + get extensionsObj() { + return this.tbsCertificateObj.subs.find((sub) => sub.tag.isContextSpecific(0x03)); + } +} +exports.x509Certificate = x509Certificate; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/ext.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/ext.d.ts new file mode 100644 index 0000000..04e5460 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/ext.d.ts @@ -0,0 +1,41 @@ +/// +import { ASN1Obj } from './asn1/obj'; +import { SignedCertificateTimestamp } from './sct'; +export declare class x509Extension { + protected root: ASN1Obj; + constructor(asn1: ASN1Obj); + get oid(): string; + get critical(): boolean; + get value(): Buffer; + protected get extnValueObj(): ASN1Obj; +} +export declare class x509BasicConstraintsExtension extends x509Extension { + get isCA(): boolean; + get pathLenConstraint(): bigint | undefined; + private get sequence(); +} +export declare class x509KeyUsageExtension extends x509Extension { + get digitalSignature(): boolean; + get keyCertSign(): boolean; + get crlSign(): boolean; + private get bitString(); +} +export declare class x509SubjectAlternativeNameExtension extends x509Extension { + get rfc822Name(): string | undefined; + get uri(): string | undefined; + otherName(oid: string): string | undefined; + private findGeneralName; + private get generalNames(); +} +export declare class x509AuthorityKeyIDExtension extends x509Extension { + get keyIdentifier(): Buffer | undefined; + private findSequenceMember; + private get sequence(); +} +export declare class x509SubjectKeyIDExtension extends x509Extension { + get keyIdentifier(): Buffer; +} +export declare class x509SCTExtension extends x509Extension { + constructor(asn1: ASN1Obj); + get signedCertificateTimestamps(): SignedCertificateTimestamp[]; +} diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/ext.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/ext.js new file mode 100644 index 0000000..caed592 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/ext.js @@ -0,0 +1,157 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.x509SCTExtension = exports.x509SubjectKeyIDExtension = exports.x509AuthorityKeyIDExtension = exports.x509SubjectAlternativeNameExtension = exports.x509KeyUsageExtension = exports.x509BasicConstraintsExtension = exports.x509Extension = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const stream_1 = require("../util/stream"); +const sct_1 = require("./sct"); +// https://www.rfc-editor.org/rfc/rfc5280#section-4.1 +class x509Extension { + constructor(asn1) { + this.root = asn1; + } + get oid() { + return this.root.subs[0].toOID(); + } + get critical() { + // The critical field is optional and will be the second element of the + // extension sequence if present. Default to false if not present. + return this.root.subs.length === 3 ? this.root.subs[1].toBoolean() : false; + } + get value() { + return this.extnValueObj.value; + } + get extnValueObj() { + // The extnValue field will be the last element of the extension sequence + return this.root.subs[this.root.subs.length - 1]; + } +} +exports.x509Extension = x509Extension; +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9 +class x509BasicConstraintsExtension extends x509Extension { + get isCA() { + return this.sequence.subs[0].toBoolean(); + } + get pathLenConstraint() { + return this.sequence.subs.length > 1 + ? this.sequence.subs[1].toInteger() + : undefined; + } + // The extnValue field contains a single sequence wrapping the isCA and + // pathLenConstraint. + get sequence() { + return this.extnValueObj.subs[0]; + } +} +exports.x509BasicConstraintsExtension = x509BasicConstraintsExtension; +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.3 +class x509KeyUsageExtension extends x509Extension { + get digitalSignature() { + return this.bitString[0] === 1; + } + get keyCertSign() { + return this.bitString[5] === 1; + } + get crlSign() { + return this.bitString[6] === 1; + } + // The extnValue field contains a single bit string which is a bit mask + // indicating which key usages are enabled. + get bitString() { + return this.extnValueObj.subs[0].toBitString(); + } +} +exports.x509KeyUsageExtension = x509KeyUsageExtension; +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.6 +class x509SubjectAlternativeNameExtension extends x509Extension { + get rfc822Name() { + return this.findGeneralName(0x01)?.value.toString('ascii'); + } + get uri() { + return this.findGeneralName(0x06)?.value.toString('ascii'); + } + // Retrieve the value of an otherName with the given OID. + otherName(oid) { + const otherName = this.findGeneralName(0x00); + if (otherName === undefined) { + return undefined; + } + // The otherName is a sequence containing an OID and a value. + // Need to check that the OID matches the one we're looking for. + const otherNameOID = otherName.subs[0].toOID(); + if (otherNameOID !== oid) { + return undefined; + } + // The otherNameValue is a sequence containing the actual value. + const otherNameValue = otherName.subs[1]; + return otherNameValue.subs[0].value.toString('ascii'); + } + findGeneralName(tag) { + return this.generalNames.find((gn) => gn.tag.isContextSpecific(tag)); + } + // The extnValue field contains a sequence of GeneralNames. + get generalNames() { + return this.extnValueObj.subs[0].subs; + } +} +exports.x509SubjectAlternativeNameExtension = x509SubjectAlternativeNameExtension; +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.1 +class x509AuthorityKeyIDExtension extends x509Extension { + get keyIdentifier() { + return this.findSequenceMember(0x00)?.value; + } + findSequenceMember(tag) { + return this.sequence.subs.find((el) => el.tag.isContextSpecific(tag)); + } + // The extnValue field contains a single sequence wrapping the keyIdentifier + get sequence() { + return this.extnValueObj.subs[0]; + } +} +exports.x509AuthorityKeyIDExtension = x509AuthorityKeyIDExtension; +// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.2 +class x509SubjectKeyIDExtension extends x509Extension { + get keyIdentifier() { + return this.extnValueObj.subs[0].value; + } +} +exports.x509SubjectKeyIDExtension = x509SubjectKeyIDExtension; +// https://www.rfc-editor.org/rfc/rfc6962#section-3.3 +class x509SCTExtension extends x509Extension { + constructor(asn1) { + super(asn1); + } + get signedCertificateTimestamps() { + const buf = this.extnValueObj.subs[0].value; + const stream = new stream_1.ByteStream(buf); + // The overall list length is encoded in the first two bytes -- note this + // is the length of the list in bytes, NOT the number of SCTs in the list + const end = stream.getUint16() + 2; + const sctList = []; + while (stream.position < end) { + // Read the length of the next SCT + const sctLength = stream.getUint16(); + // Slice out the bytes for the next SCT and parse it + const sct = stream.getBlock(sctLength); + sctList.push(sct_1.SignedCertificateTimestamp.parse(sct)); + } + if (stream.position !== end) { + throw new Error('SCT list length does not match actual length'); + } + return sctList; + } +} +exports.x509SCTExtension = x509SCTExtension; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/sct.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/sct.d.ts new file mode 100644 index 0000000..076a532 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/sct.d.ts @@ -0,0 +1,26 @@ +/// +import * as sigstore from '../types/sigstore'; +interface SCTOptions { + version: number; + logID: Buffer; + timestamp: Buffer; + extensions: Buffer; + hashAlgorithm: number; + signatureAlgorithm: number; + signature: Buffer; +} +export declare class SignedCertificateTimestamp { + readonly version: number; + readonly logID: Buffer; + readonly timestamp: Buffer; + readonly extensions: Buffer; + readonly hashAlgorithm: number; + readonly signatureAlgorithm: number; + readonly signature: Buffer; + constructor(options: SCTOptions); + get datetime(): Date; + get algorithm(): string; + verify(preCert: Buffer, logs: sigstore.TransparencyLogInstance[]): boolean; + static parse(buf: Buffer): SignedCertificateTimestamp; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/sct.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/sct.js new file mode 100644 index 0000000..72528dd --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/sct.js @@ -0,0 +1,101 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SignedCertificateTimestamp = void 0; +const util_1 = require("../util"); +const stream_1 = require("../util/stream"); +class SignedCertificateTimestamp { + constructor(options) { + this.version = options.version; + this.logID = options.logID; + this.timestamp = options.timestamp; + this.extensions = options.extensions; + this.hashAlgorithm = options.hashAlgorithm; + this.signatureAlgorithm = options.signatureAlgorithm; + this.signature = options.signature; + } + get datetime() { + return new Date(Number(this.timestamp.readBigInt64BE())); + } + // Returns the hash algorithm used to generate the SCT's signature. + // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1 + get algorithm() { + switch (this.hashAlgorithm) { + case 0: + return 'none'; + case 1: + return 'md5'; + case 2: + return 'sha1'; + case 3: + return 'sha224'; + case 4: + return 'sha256'; + case 5: + return 'sha384'; + case 6: + return 'sha512'; + default: + return 'unknown'; + } + } + verify(preCert, logs) { + // Find key for the log reponsible for this signature + const log = logs.find((log) => log.logId?.keyId.equals(this.logID)); + if (!log?.publicKey?.rawBytes) { + throw new Error(`No key found for log: ${this.logID.toString('base64')}`); + } + const publicKey = util_1.crypto.createPublicKey(log.publicKey.rawBytes); + // Assemble the digitally-signed struct (the data over which the signature + // was generated). + // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 + const stream = new stream_1.ByteStream(); + stream.appendChar(this.version); + stream.appendChar(0x00); // SignatureType = certificate_timestamp(0) + stream.appendView(this.timestamp); + stream.appendUint16(0x01); // LogEntryType = precert_entry(1) + stream.appendView(preCert); + stream.appendUint16(this.extensions.byteLength); + if (this.extensions.byteLength > 0) { + stream.appendView(this.extensions); + } + return util_1.crypto.verifyBlob(stream.buffer, publicKey, this.signature, this.algorithm); + } + // Parses a SignedCertificateTimestamp from a buffer. SCTs are encoded using + // TLS encoding which means the fields and lengths of most fields are + // specified as part of the SCT and TLS specs. + // https://www.rfc-editor.org/rfc/rfc6962#section-3.2 + // https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.4.1 + static parse(buf) { + const stream = new stream_1.ByteStream(buf); + // Version - enum { v1(0), (255) } + const version = stream.getUint8(); + // Log ID - struct { opaque key_id[32]; } + const logID = stream.getBlock(32); + // Timestamp - uint64 + const timestamp = stream.getBlock(8); + // Extensions - opaque extensions<0..2^16-1>; + const extenstionLength = stream.getUint16(); + const extensions = stream.getBlock(extenstionLength); + // Hash algo - enum { sha256(4), . . . (255) } + const hashAlgorithm = stream.getUint8(); + // Signature algo - enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) } + const signatureAlgorithm = stream.getUint8(); + // Signature - opaque signature<0..2^16-1>; + const sigLength = stream.getUint16(); + const signature = stream.getBlock(sigLength); + // Check that we read the entire buffer + if (stream.position !== buf.length) { + throw new Error('SCT buffer length mismatch'); + } + return new SignedCertificateTimestamp({ + version, + logID, + timestamp, + extensions, + hashAlgorithm, + signatureAlgorithm, + signature, + }); + } +} +exports.SignedCertificateTimestamp = SignedCertificateTimestamp; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/verify.d.ts b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/verify.d.ts new file mode 100644 index 0000000..04c324d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/verify.d.ts @@ -0,0 +1,8 @@ +import { x509Certificate } from './cert'; +interface VerifyCertificateChainOptions { + trustedCerts: x509Certificate[]; + certs: x509Certificate[]; + validAt?: Date; +} +export declare function verifyCertificateChain(opts: VerifyCertificateChainOptions): x509Certificate[]; +export {}; diff --git a/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/verify.js b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/verify.js new file mode 100644 index 0000000..cc34a9e --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/sigstore/dist/x509/verify.js @@ -0,0 +1,159 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifyCertificateChain = void 0; +/* +Copyright 2023 The Sigstore Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +const error_1 = require("../error"); +function verifyCertificateChain(opts) { + const verifier = new CertificateChainVerifier(opts); + return verifier.verify(); +} +exports.verifyCertificateChain = verifyCertificateChain; +class CertificateChainVerifier { + constructor(opts) { + this.certs = opts.certs; + this.trustedCerts = opts.trustedCerts; + this.localCerts = dedupeCertificates([...opts.trustedCerts, ...opts.certs]); + this.validAt = opts.validAt || new Date(); + } + verify() { + if (this.certs.length === 0) { + throw new error_1.VerificationError('No certificates provided'); + } + // Construct certificate path from leaf to root + const certificatePath = this.sort(); + // Perform validation checks on each certificate in the path + this.checkPath(certificatePath); + // Return verified certificate path + return certificatePath; + } + sort() { + const leafCert = this.localCerts[this.localCerts.length - 1]; + // Construct all possible paths from the leaf + let paths = this.buildPaths(leafCert); + // Filter for paths which contain a trusted certificate + paths = paths.filter((path) => path.some((cert) => this.trustedCerts.includes(cert))); + if (paths.length === 0) { + throw new error_1.VerificationError('No trusted certificate path found'); + } + // Find the shortest of possible paths + const path = paths.reduce((prev, curr) => prev.length < curr.length ? prev : curr); + // Construct chain from shortest path + return [leafCert, ...path]; + } + // Recursively build all possible paths from the leaf to the root + buildPaths(certificate) { + const paths = []; + const issuers = this.findIssuer(certificate); + if (issuers.length === 0) { + throw new error_1.VerificationError('No valid certificate path found'); + } + for (let i = 0; i < issuers.length; i++) { + const issuer = issuers[i]; + // Base case - issuer is self + if (issuer.equals(certificate)) { + paths.push([certificate]); + continue; + } + // Recursively build path for the issuer + const subPaths = this.buildPaths(issuer); + // Construct paths by appending the issuer to each subpath + for (let j = 0; j < subPaths.length; j++) { + paths.push([issuer, ...subPaths[j]]); + } + } + return paths; + } + // Return all possible issuers for the given certificate + findIssuer(certificate) { + let issuers = []; + let keyIdentifier; + // Exit early if the certificate is self-signed + if (certificate.subject.equals(certificate.issuer)) { + if (certificate.verify()) { + return [certificate]; + } + } + // If the certificate has an authority key identifier, use that + // to find the issuer + if (certificate.extAuthorityKeyID) { + keyIdentifier = certificate.extAuthorityKeyID.keyIdentifier; + // TODO: Add support for authorityCertIssuer/authorityCertSerialNumber + // though Fulcio doesn't appear to use these + } + // Find possible issuers by comparing the authorityKeyID/subjectKeyID + // or issuer/subject. Potential issuers are added to the result array. + this.localCerts.forEach((possibleIssuer) => { + if (keyIdentifier) { + if (possibleIssuer.extSubjectKeyID) { + if (possibleIssuer.extSubjectKeyID.keyIdentifier.equals(keyIdentifier)) { + issuers.push(possibleIssuer); + } + return; + } + } + // Fallback to comparing certificate issuer and subject if + // subjectKey/authorityKey extensions are not present + if (possibleIssuer.subject.equals(certificate.issuer)) { + issuers.push(possibleIssuer); + } + }); + // Remove any issuers which fail to verify the certificate + issuers = issuers.filter((issuer) => { + try { + return certificate.verify(issuer); + } + catch (ex) { + return false; + } + }); + return issuers; + } + checkPath(path) { + if (path.length < 2) { + throw new error_1.VerificationError('Certificate chain must contain at least two certificates'); + } + // Check that all certificates are valid at the check date + const validForDate = path.every((cert) => cert.validForDate(this.validAt)); + if (!validForDate) { + throw new error_1.VerificationError('Certificate is not valid or expired at the specified date'); + } + // Ensure that all certificates beyond the leaf are CAs + const validCAs = path.slice(1).every((cert) => cert.isCA); + if (!validCAs) { + throw new error_1.VerificationError('Intermediate certificate is not a CA'); + } + // Certificate's issuer must match the subject of the next certificate + // in the chain + for (let i = path.length - 2; i >= 0; i--) { + if (!path[i].issuer.equals(path[i + 1].subject)) { + throw new error_1.VerificationError('Incorrect certificate name chaining'); + } + } + } +} +// Remove duplicate certificates from the array +function dedupeCertificates(certs) { + for (let i = 0; i < certs.length; i++) { + for (let j = i + 1; j < certs.length; j++) { + if (certs[i].equals(certs[j])) { + certs.splice(j, 1); + j--; + } + } + } + return certs; +} diff --git a/software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.d.ts b/software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.d.ts new file mode 100644 index 0000000..4de33b1 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.d.ts @@ -0,0 +1,33 @@ +/// +import { SocksProxy } from 'socks'; +import { Agent, ClientRequest, RequestOptions } from 'agent-base'; +import { AgentOptions } from 'agent-base'; +import { Url } from 'url'; +import net from 'net'; +import tls from 'tls'; +interface BaseSocksProxyAgentOptions { + host?: string | null; + port?: string | number | null; + username?: string | null; + tls?: tls.ConnectionOptions | null; +} +interface SocksProxyAgentOptionsExtra { + timeout?: number; +} +export interface SocksProxyAgentOptions extends AgentOptions, BaseSocksProxyAgentOptions, Partial> { +} +export declare class SocksProxyAgent extends Agent { + private readonly shouldLookup; + private readonly proxy; + private readonly tlsConnectionOptions; + timeout: number | null; + constructor(input: string | SocksProxyAgentOptions, options?: SocksProxyAgentOptionsExtra); + /** + * Initiates a SOCKS connection to the specified SOCKS proxy server, + * which in turn connects to the specified remote host and port. + * + * @api protected + */ + callback(req: ClientRequest, opts: RequestOptions): Promise; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.js b/software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.js new file mode 100644 index 0000000..55b598b --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.js @@ -0,0 +1,197 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SocksProxyAgent = void 0; +const socks_1 = require("socks"); +const agent_base_1 = require("agent-base"); +const debug_1 = __importDefault(require("debug")); +const dns_1 = __importDefault(require("dns")); +const tls_1 = __importDefault(require("tls")); +const debug = (0, debug_1.default)('socks-proxy-agent'); +function parseSocksProxy(opts) { + var _a; + let port = 0; + let lookup = false; + let type = 5; + const host = opts.hostname; + if (host == null) { + throw new TypeError('No "host"'); + } + if (typeof opts.port === 'number') { + port = opts.port; + } + else if (typeof opts.port === 'string') { + port = parseInt(opts.port, 10); + } + // From RFC 1928, Section 3: https://tools.ietf.org/html/rfc1928#section-3 + // "The SOCKS service is conventionally located on TCP port 1080" + if (port == null) { + port = 1080; + } + // figure out if we want socks v4 or v5, based on the "protocol" used. + // Defaults to 5. + if (opts.protocol != null) { + switch (opts.protocol.replace(':', '')) { + case 'socks4': + lookup = true; + // pass through + case 'socks4a': + type = 4; + break; + case 'socks5': + lookup = true; + // pass through + case 'socks': // no version specified, default to 5h + case 'socks5h': + type = 5; + break; + default: + throw new TypeError(`A "socks" protocol must be specified! Got: ${String(opts.protocol)}`); + } + } + if (typeof opts.type !== 'undefined') { + if (opts.type === 4 || opts.type === 5) { + type = opts.type; + } + else { + throw new TypeError(`"type" must be 4 or 5, got: ${String(opts.type)}`); + } + } + const proxy = { + host, + port, + type + }; + let userId = (_a = opts.userId) !== null && _a !== void 0 ? _a : opts.username; + let password = opts.password; + if (opts.auth != null) { + const auth = opts.auth.split(':'); + userId = auth[0]; + password = auth[1]; + } + if (userId != null) { + Object.defineProperty(proxy, 'userId', { + value: userId, + enumerable: false + }); + } + if (password != null) { + Object.defineProperty(proxy, 'password', { + value: password, + enumerable: false + }); + } + return { lookup, proxy }; +} +const normalizeProxyOptions = (input) => { + let proxyOptions; + if (typeof input === 'string') { + proxyOptions = new URL(input); + } + else { + proxyOptions = input; + } + if (proxyOptions == null) { + throw new TypeError('a SOCKS proxy server `host` and `port` must be specified!'); + } + return proxyOptions; +}; +class SocksProxyAgent extends agent_base_1.Agent { + constructor(input, options) { + var _a; + const proxyOptions = normalizeProxyOptions(input); + super(proxyOptions); + const parsedProxy = parseSocksProxy(proxyOptions); + this.shouldLookup = parsedProxy.lookup; + this.proxy = parsedProxy.proxy; + this.tlsConnectionOptions = proxyOptions.tls != null ? proxyOptions.tls : {}; + this.timeout = (_a = options === null || options === void 0 ? void 0 : options.timeout) !== null && _a !== void 0 ? _a : null; + } + /** + * Initiates a SOCKS connection to the specified SOCKS proxy server, + * which in turn connects to the specified remote host and port. + * + * @api protected + */ + callback(req, opts) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const { shouldLookup, proxy, timeout } = this; + let { host, port, lookup: lookupCallback } = opts; + if (host == null) { + throw new Error('No `host` defined!'); + } + if (shouldLookup) { + // Client-side DNS resolution for "4" and "5" socks proxy versions. + host = yield new Promise((resolve, reject) => { + // Use the request's custom lookup, if one was configured: + const lookupFn = lookupCallback !== null && lookupCallback !== void 0 ? lookupCallback : dns_1.default.lookup; + lookupFn(host, {}, (err, res) => { + if (err) { + reject(err); + } + else { + resolve(res); + } + }); + }); + } + const socksOpts = { + proxy, + destination: { host, port }, + command: 'connect', + timeout: timeout !== null && timeout !== void 0 ? timeout : undefined + }; + const cleanup = (tlsSocket) => { + req.destroy(); + socket.destroy(); + if (tlsSocket) + tlsSocket.destroy(); + }; + debug('Creating socks proxy connection: %o', socksOpts); + const { socket } = yield socks_1.SocksClient.createConnection(socksOpts); + debug('Successfully created socks proxy connection'); + if (timeout !== null) { + socket.setTimeout(timeout); + socket.on('timeout', () => cleanup()); + } + if (opts.secureEndpoint) { + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + const servername = (_a = opts.servername) !== null && _a !== void 0 ? _a : opts.host; + const tlsSocket = tls_1.default.connect(Object.assign(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername }), this.tlsConnectionOptions)); + tlsSocket.once('error', (error) => { + debug('socket TLS error', error.message); + cleanup(tlsSocket); + }); + return tlsSocket; + } + return socket; + }); + } +} +exports.SocksProxyAgent = SocksProxyAgent; +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.js.map b/software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.js.map new file mode 100644 index 0000000..e183e8e --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/socks-proxy-agent/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,iCAAmE;AACnE,2CAAiE;AAEjE,kDAA+B;AAE/B,8CAAqB;AAErB,8CAAqB;AAarB,MAAM,KAAK,GAAG,IAAA,eAAW,EAAC,mBAAmB,CAAC,CAAA;AAE9C,SAAS,eAAe,CAAE,IAA4B;;IACpD,IAAI,IAAI,GAAG,CAAC,CAAA;IACZ,IAAI,MAAM,GAAG,KAAK,CAAA;IAClB,IAAI,IAAI,GAAuB,CAAC,CAAA;IAEhC,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAA;IAE1B,IAAI,IAAI,IAAI,IAAI,EAAE;QAChB,MAAM,IAAI,SAAS,CAAC,WAAW,CAAC,CAAA;KACjC;IAED,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE;QACjC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAA;KACjB;SAAM,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE;QACxC,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,CA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G,GAAG,EAAgD,CAAA;IAC5D,IAAI,GAAqB,CAAA;IACzB,KAAK,GAAG,IAAI,GAAG,EAAE;QACf,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;YACvB,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAA;SACpB;KACF;IACD,OAAO,GAAG,CAAA;AACZ,CAAC"} \ No newline at end of file diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/error.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/error.d.ts new file mode 100644 index 0000000..130e49a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/error.d.ts @@ -0,0 +1,30 @@ +export declare class ValueError extends Error { +} +export declare class RuntimeError extends Error { +} +export declare class PersistError extends Error { +} +export declare class RepositoryError extends Error { +} +export declare class UnsignedMetadataError extends RepositoryError { +} +export declare class BadVersionError extends RepositoryError { +} +export declare class EqualVersionError extends BadVersionError { +} +export declare class ExpiredMetadataError extends RepositoryError { +} +export declare class LengthOrHashMismatchError extends RepositoryError { +} +export declare class CryptoError extends Error { +} +export declare class UnsupportedAlgorithmError extends CryptoError { +} +export declare class DownloadError extends Error { +} +export declare class DownloadLengthMismatchError extends DownloadError { +} +export declare class DownloadHTTPError extends DownloadError { + statusCode: number; + constructor(message: string, statusCode: number); +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/error.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/error.js new file mode 100644 index 0000000..ce7ca5e --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/error.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DownloadHTTPError = exports.DownloadLengthMismatchError = exports.DownloadError = exports.UnsupportedAlgorithmError = exports.CryptoError = exports.LengthOrHashMismatchError = exports.ExpiredMetadataError = exports.EqualVersionError = exports.BadVersionError = exports.UnsignedMetadataError = exports.RepositoryError = exports.PersistError = exports.RuntimeError = exports.ValueError = void 0; +// An error about insufficient values +class ValueError extends Error { +} +exports.ValueError = ValueError; +class RuntimeError extends Error { +} +exports.RuntimeError = RuntimeError; +class PersistError extends Error { +} +exports.PersistError = PersistError; +// An error with a repository's state, such as a missing file. +// It covers all exceptions that come from the repository side when +// looking from the perspective of users of metadata API or ngclient. +class RepositoryError extends Error { +} +exports.RepositoryError = RepositoryError; +// An error about metadata object with insufficient threshold of signatures. +class UnsignedMetadataError extends RepositoryError { +} +exports.UnsignedMetadataError = UnsignedMetadataError; +// An error for metadata that contains an invalid version number. +class BadVersionError extends RepositoryError { +} +exports.BadVersionError = BadVersionError; +// An error for metadata containing a previously verified version number. +class EqualVersionError extends BadVersionError { +} +exports.EqualVersionError = EqualVersionError; +// Indicate that a TUF Metadata file has expired. +class ExpiredMetadataError extends RepositoryError { +} +exports.ExpiredMetadataError = ExpiredMetadataError; +// An error while checking the length and hash values of an object. +class LengthOrHashMismatchError extends RepositoryError { +} +exports.LengthOrHashMismatchError = LengthOrHashMismatchError; +class CryptoError extends Error { +} +exports.CryptoError = CryptoError; +class UnsupportedAlgorithmError extends CryptoError { +} +exports.UnsupportedAlgorithmError = UnsupportedAlgorithmError; +//----- Download Errors ------------------------------------------------------- +// An error occurred while attempting to download a file. +class DownloadError extends Error { +} +exports.DownloadError = DownloadError; +// Indicate that a mismatch of lengths was seen while downloading a file +class DownloadLengthMismatchError extends DownloadError { +} +exports.DownloadLengthMismatchError = DownloadLengthMismatchError; +// Returned by FetcherInterface implementations for HTTP errors. +class DownloadHTTPError extends DownloadError { + constructor(message, statusCode) { + super(message); + this.statusCode = statusCode; + } +} +exports.DownloadHTTPError = DownloadHTTPError; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/fetcher.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/fetcher.d.ts new file mode 100644 index 0000000..2b52cbe --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/fetcher.d.ts @@ -0,0 +1,19 @@ +/// +/// +type DownloadFileHandler = (file: string) => Promise; +export declare abstract class BaseFetcher { + abstract fetch(url: string): Promise; + downloadFile(url: string, maxLength: number, handler: DownloadFileHandler): Promise; + downloadBytes(url: string, maxLength: number): Promise; +} +interface FetcherOptions { + timeout?: number; + retries?: number; +} +export declare class Fetcher extends BaseFetcher { + private timeout?; + private retries?; + constructor(options?: FetcherOptions); + fetch(url: string): Promise; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/fetcher.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/fetcher.js new file mode 100644 index 0000000..cb42ab2 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/fetcher.js @@ -0,0 +1,81 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Fetcher = exports.BaseFetcher = void 0; +const fs_1 = __importDefault(require("fs")); +const make_fetch_happen_1 = __importDefault(require("make-fetch-happen")); +const util_1 = __importDefault(require("util")); +const error_1 = require("./error"); +const tmpfile_1 = require("./utils/tmpfile"); +class BaseFetcher { + // Download file from given URL. The file is downloaded to a temporary + // location and then passed to the given handler. The handler is responsible + // for moving the file to its final location. The temporary file is deleted + // after the handler returns. + async downloadFile(url, maxLength, handler) { + return (0, tmpfile_1.withTempFile)(async (tmpFile) => { + const reader = await this.fetch(url); + let numberOfBytesReceived = 0; + const fileStream = fs_1.default.createWriteStream(tmpFile); + // Read the stream a chunk at a time so that we can check + // the length of the file as we go + try { + for await (const chunk of reader) { + const bufferChunk = Buffer.from(chunk); + numberOfBytesReceived += bufferChunk.length; + if (numberOfBytesReceived > maxLength) { + throw new error_1.DownloadLengthMismatchError('Max length reached'); + } + await writeBufferToStream(fileStream, bufferChunk); + } + } + finally { + // Make sure we always close the stream + await util_1.default.promisify(fileStream.close).bind(fileStream)(); + } + return handler(tmpFile); + }); + } + // Download bytes from given URL. + async downloadBytes(url, maxLength) { + return this.downloadFile(url, maxLength, async (file) => { + const stream = fs_1.default.createReadStream(file); + const chunks = []; + for await (const chunk of stream) { + chunks.push(chunk); + } + return Buffer.concat(chunks); + }); + } +} +exports.BaseFetcher = BaseFetcher; +class Fetcher extends BaseFetcher { + constructor(options = {}) { + super(); + this.timeout = options.timeout; + this.retries = options.retries; + } + async fetch(url) { + const response = await (0, make_fetch_happen_1.default)(url, { + timeout: this.timeout, + retry: this.retries, + }); + if (!response.ok || !response?.body) { + throw new error_1.DownloadHTTPError('Failed to download', response.status); + } + return response.body; + } +} +exports.Fetcher = Fetcher; +const writeBufferToStream = async (stream, buffer) => { + return new Promise((resolve, reject) => { + stream.write(buffer, (err) => { + if (err) { + reject(err); + } + resolve(true); + }); + }); +}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/index.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/index.d.ts new file mode 100644 index 0000000..bfe3adc --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/index.d.ts @@ -0,0 +1,3 @@ +export { BaseFetcher } from './fetcher'; +export { TargetFile } from './models/file'; +export { Updater } from './updater'; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/index.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/index.js new file mode 100644 index 0000000..6245d17 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/index.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Updater = exports.TargetFile = exports.BaseFetcher = void 0; +var fetcher_1 = require("./fetcher"); +Object.defineProperty(exports, "BaseFetcher", { enumerable: true, get: function () { return fetcher_1.BaseFetcher; } }); +var file_1 = require("./models/file"); +Object.defineProperty(exports, "TargetFile", { enumerable: true, get: function () { return file_1.TargetFile; } }); +var updater_1 = require("./updater"); +Object.defineProperty(exports, "Updater", { enumerable: true, get: function () { return updater_1.Updater; } }); diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/base.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/base.d.ts new file mode 100644 index 0000000..4c5e0aa --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/base.d.ts @@ -0,0 +1,30 @@ +import { JSONObject, JSONValue } from '../utils/types'; +import { Signature } from './signature'; +export interface Signable { + signatures: Record; + signed: Signed; +} +export interface SignedOptions { + version?: number; + specVersion?: string; + expires?: string; + unrecognizedFields?: Record; +} +/*** + * A base class for the signed part of TUF metadata. + * + * Objects with base class Signed are usually included in a ``Metadata`` object + * on the signed attribute. This class provides attributes and methods that + * are common for all TUF metadata types (roles). + */ +export declare abstract class Signed { + readonly specVersion: string; + readonly expires: string; + readonly version: number; + readonly unrecognizedFields: Record; + constructor(options: SignedOptions); + equals(other: Signed): boolean; + isExpired(referenceTime?: Date): boolean; + static commonFieldsFromJSON(data: JSONObject): SignedOptions; + abstract toJSON(): JSONObject; +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/base.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/base.js new file mode 100644 index 0000000..7658567 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/base.js @@ -0,0 +1,71 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Signed = void 0; +const util_1 = __importDefault(require("util")); +const error_1 = require("../error"); +const utils_1 = require("../utils"); +const SPECIFICATION_VERSION = ['1', '0', '31']; +/*** + * A base class for the signed part of TUF metadata. + * + * Objects with base class Signed are usually included in a ``Metadata`` object + * on the signed attribute. This class provides attributes and methods that + * are common for all TUF metadata types (roles). + */ +class Signed { + constructor(options) { + this.specVersion = options.specVersion || SPECIFICATION_VERSION.join('.'); + const specList = this.specVersion.split('.'); + if (!(specList.length === 2 || specList.length === 3) || + !specList.every((item) => isNumeric(item))) { + throw new error_1.ValueError('Failed to parse specVersion'); + } + // major version must match + if (specList[0] != SPECIFICATION_VERSION[0]) { + throw new error_1.ValueError('Unsupported specVersion'); + } + this.expires = options.expires || new Date().toISOString(); + this.version = options.version || 1; + this.unrecognizedFields = options.unrecognizedFields || {}; + } + equals(other) { + if (!(other instanceof Signed)) { + return false; + } + return (this.specVersion === other.specVersion && + this.expires === other.expires && + this.version === other.version && + util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); + } + isExpired(referenceTime) { + if (!referenceTime) { + referenceTime = new Date(); + } + return referenceTime >= new Date(this.expires); + } + static commonFieldsFromJSON(data) { + const { spec_version, expires, version, ...rest } = data; + if (utils_1.guard.isDefined(spec_version) && !(typeof spec_version === 'string')) { + throw new TypeError('spec_version must be a string'); + } + if (utils_1.guard.isDefined(expires) && !(typeof expires === 'string')) { + throw new TypeError('expires must be a string'); + } + if (utils_1.guard.isDefined(version) && !(typeof version === 'number')) { + throw new TypeError('version must be a number'); + } + return { + specVersion: spec_version, + expires, + version, + unrecognizedFields: rest, + }; + } +} +exports.Signed = Signed; +function isNumeric(str) { + return !isNaN(Number(str)); +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/delegations.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/delegations.d.ts new file mode 100644 index 0000000..b53862a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/delegations.d.ts @@ -0,0 +1,32 @@ +import { JSONObject, JSONValue } from '../utils/types'; +import { Key } from './key'; +import { DelegatedRole, SuccinctRoles } from './role'; +type DelegatedRoleMap = Record; +type KeyMap = Record; +interface DelegationsOptions { + keys: KeyMap; + roles?: DelegatedRoleMap; + succinctRoles?: SuccinctRoles; + unrecognizedFields?: Record; +} +/** + * A container object storing information about all delegations. + * + * Targets roles that are trusted to provide signed metadata files + * describing targets with designated pathnames and/or further delegations. + */ +export declare class Delegations { + readonly keys: KeyMap; + readonly roles?: DelegatedRoleMap; + readonly unrecognizedFields?: Record; + readonly succinctRoles?: SuccinctRoles; + constructor(options: DelegationsOptions); + equals(other: Delegations): boolean; + rolesForTarget(targetPath: string): Generator<{ + role: string; + terminating: boolean; + }>; + toJSON(): JSONObject; + static fromJSON(data: JSONObject): Delegations; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/delegations.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/delegations.js new file mode 100644 index 0000000..302bd52 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/delegations.js @@ -0,0 +1,115 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Delegations = void 0; +const util_1 = __importDefault(require("util")); +const error_1 = require("../error"); +const guard_1 = require("../utils/guard"); +const key_1 = require("./key"); +const role_1 = require("./role"); +/** + * A container object storing information about all delegations. + * + * Targets roles that are trusted to provide signed metadata files + * describing targets with designated pathnames and/or further delegations. + */ +class Delegations { + constructor(options) { + this.keys = options.keys; + this.unrecognizedFields = options.unrecognizedFields || {}; + if (options.roles) { + if (Object.keys(options.roles).some((roleName) => role_1.TOP_LEVEL_ROLE_NAMES.includes(roleName))) { + throw new error_1.ValueError('Delegated role name conflicts with top-level role name'); + } + } + this.succinctRoles = options.succinctRoles; + this.roles = options.roles; + } + equals(other) { + if (!(other instanceof Delegations)) { + return false; + } + return (util_1.default.isDeepStrictEqual(this.keys, other.keys) && + util_1.default.isDeepStrictEqual(this.roles, other.roles) && + util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields) && + util_1.default.isDeepStrictEqual(this.succinctRoles, other.succinctRoles)); + } + *rolesForTarget(targetPath) { + if (this.roles) { + for (const role of Object.values(this.roles)) { + if (role.isDelegatedPath(targetPath)) { + yield { role: role.name, terminating: role.terminating }; + } + } + } + else if (this.succinctRoles) { + yield { + role: this.succinctRoles.getRoleForTarget(targetPath), + terminating: true, + }; + } + } + toJSON() { + const json = { + keys: keysToJSON(this.keys), + ...this.unrecognizedFields, + }; + if (this.roles) { + json.roles = rolesToJSON(this.roles); + } + else if (this.succinctRoles) { + json.succinct_roles = this.succinctRoles.toJSON(); + } + return json; + } + static fromJSON(data) { + const { keys, roles, succinct_roles, ...unrecognizedFields } = data; + let succinctRoles; + if ((0, guard_1.isObject)(succinct_roles)) { + succinctRoles = role_1.SuccinctRoles.fromJSON(succinct_roles); + } + return new Delegations({ + keys: keysFromJSON(keys), + roles: rolesFromJSON(roles), + unrecognizedFields, + succinctRoles, + }); + } +} +exports.Delegations = Delegations; +function keysToJSON(keys) { + return Object.entries(keys).reduce((acc, [keyId, key]) => ({ + ...acc, + [keyId]: key.toJSON(), + }), {}); +} +function rolesToJSON(roles) { + return Object.values(roles).map((role) => role.toJSON()); +} +function keysFromJSON(data) { + if (!(0, guard_1.isObjectRecord)(data)) { + throw new TypeError('keys is malformed'); + } + return Object.entries(data).reduce((acc, [keyID, keyData]) => ({ + ...acc, + [keyID]: key_1.Key.fromJSON(keyID, keyData), + }), {}); +} +function rolesFromJSON(data) { + let roleMap; + if ((0, guard_1.isDefined)(data)) { + if (!(0, guard_1.isObjectArray)(data)) { + throw new TypeError('roles is malformed'); + } + roleMap = data.reduce((acc, role) => { + const delegatedRole = role_1.DelegatedRole.fromJSON(role); + return { + ...acc, + [delegatedRole.name]: delegatedRole, + }; + }, {}); + } + return roleMap; +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/file.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/file.d.ts new file mode 100644 index 0000000..9678cf1 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/file.d.ts @@ -0,0 +1,40 @@ +/// +/// +import { Readable } from 'stream'; +import { JSONObject, JSONValue } from '../utils/types'; +interface MetaFileOptions { + version: number; + length?: number; + hashes?: Record; + unrecognizedFields?: Record; +} +export declare class MetaFile { + readonly version: number; + readonly length?: number; + readonly hashes?: Record; + readonly unrecognizedFields?: Record; + constructor(opts: MetaFileOptions); + equals(other: MetaFile): boolean; + verify(data: Buffer): void; + toJSON(): JSONObject; + static fromJSON(data: JSONObject): MetaFile; +} +interface TargetFileOptions { + length: number; + path: string; + hashes: Record; + unrecognizedFields?: Record; +} +export declare class TargetFile { + readonly length: number; + readonly path: string; + readonly hashes: Record; + readonly unrecognizedFields: Record; + constructor(opts: TargetFileOptions); + get custom(): Record; + equals(other: TargetFile): boolean; + verify(stream: Readable): Promise; + toJSON(): JSONObject; + static fromJSON(path: string, data: JSONObject): TargetFile; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/file.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/file.js new file mode 100644 index 0000000..d6d535f --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/file.js @@ -0,0 +1,183 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TargetFile = exports.MetaFile = void 0; +const crypto_1 = __importDefault(require("crypto")); +const util_1 = __importDefault(require("util")); +const error_1 = require("../error"); +const guard_1 = require("../utils/guard"); +// A container with information about a particular metadata file. +// +// This class is used for Timestamp and Snapshot metadata. +class MetaFile { + constructor(opts) { + if (opts.version <= 0) { + throw new error_1.ValueError('Metafile version must be at least 1'); + } + if (opts.length !== undefined) { + validateLength(opts.length); + } + this.version = opts.version; + this.length = opts.length; + this.hashes = opts.hashes; + this.unrecognizedFields = opts.unrecognizedFields || {}; + } + equals(other) { + if (!(other instanceof MetaFile)) { + return false; + } + return (this.version === other.version && + this.length === other.length && + util_1.default.isDeepStrictEqual(this.hashes, other.hashes) && + util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); + } + verify(data) { + // Verifies that the given data matches the expected length. + if (this.length !== undefined) { + if (data.length !== this.length) { + throw new error_1.LengthOrHashMismatchError(`Expected length ${this.length} but got ${data.length}`); + } + } + // Verifies that the given data matches the supplied hashes. + if (this.hashes) { + Object.entries(this.hashes).forEach(([key, value]) => { + let hash; + try { + hash = crypto_1.default.createHash(key); + } + catch (e) { + throw new error_1.LengthOrHashMismatchError(`Hash algorithm ${key} not supported`); + } + const observedHash = hash.update(data).digest('hex'); + if (observedHash !== value) { + throw new error_1.LengthOrHashMismatchError(`Expected hash ${value} but got ${observedHash}`); + } + }); + } + } + toJSON() { + const json = { + version: this.version, + ...this.unrecognizedFields, + }; + if (this.length !== undefined) { + json.length = this.length; + } + if (this.hashes) { + json.hashes = this.hashes; + } + return json; + } + static fromJSON(data) { + const { version, length, hashes, ...rest } = data; + if (typeof version !== 'number') { + throw new TypeError('version must be a number'); + } + if ((0, guard_1.isDefined)(length) && typeof length !== 'number') { + throw new TypeError('length must be a number'); + } + if ((0, guard_1.isDefined)(hashes) && !(0, guard_1.isStringRecord)(hashes)) { + throw new TypeError('hashes must be string keys and values'); + } + return new MetaFile({ + version, + length, + hashes, + unrecognizedFields: rest, + }); + } +} +exports.MetaFile = MetaFile; +// Container for info about a particular target file. +// +// This class is used for Target metadata. +class TargetFile { + constructor(opts) { + validateLength(opts.length); + this.length = opts.length; + this.path = opts.path; + this.hashes = opts.hashes; + this.unrecognizedFields = opts.unrecognizedFields || {}; + } + get custom() { + const custom = this.unrecognizedFields['custom']; + if (!custom || Array.isArray(custom) || !(typeof custom === 'object')) { + return {}; + } + return custom; + } + equals(other) { + if (!(other instanceof TargetFile)) { + return false; + } + return (this.length === other.length && + this.path === other.path && + util_1.default.isDeepStrictEqual(this.hashes, other.hashes) && + util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); + } + async verify(stream) { + let observedLength = 0; + // Create a digest for each hash algorithm + const digests = Object.keys(this.hashes).reduce((acc, key) => { + try { + acc[key] = crypto_1.default.createHash(key); + } + catch (e) { + throw new error_1.LengthOrHashMismatchError(`Hash algorithm ${key} not supported`); + } + return acc; + }, {}); + // Read stream chunk by chunk + for await (const chunk of stream) { + // Keep running tally of stream length + observedLength += chunk.length; + // Append chunk to each digest + Object.values(digests).forEach((digest) => { + digest.update(chunk); + }); + } + // Verify length matches expected value + if (observedLength !== this.length) { + throw new error_1.LengthOrHashMismatchError(`Expected length ${this.length} but got ${observedLength}`); + } + // Verify each digest matches expected value + Object.entries(digests).forEach(([key, value]) => { + const expected = this.hashes[key]; + const actual = value.digest('hex'); + if (actual !== expected) { + throw new error_1.LengthOrHashMismatchError(`Expected hash ${expected} but got ${actual}`); + } + }); + } + toJSON() { + return { + length: this.length, + hashes: this.hashes, + ...this.unrecognizedFields, + }; + } + static fromJSON(path, data) { + const { length, hashes, ...rest } = data; + if (typeof length !== 'number') { + throw new TypeError('length must be a number'); + } + if (!(0, guard_1.isStringRecord)(hashes)) { + throw new TypeError('hashes must have string keys and values'); + } + return new TargetFile({ + length, + path, + hashes, + unrecognizedFields: rest, + }); + } +} +exports.TargetFile = TargetFile; +// Check that supplied length if valid +function validateLength(length) { + if (length < 0) { + throw new error_1.ValueError('Length must be at least 0'); + } +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/index.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/index.d.ts new file mode 100644 index 0000000..58d7791 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/index.d.ts @@ -0,0 +1,5 @@ +export { Metadata } from './metadata'; +export { Root } from './root'; +export { Snapshot } from './snapshot'; +export { Targets } from './targets'; +export { Timestamp } from './timestamp'; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/index.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/index.js new file mode 100644 index 0000000..aa3d828 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/index.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Timestamp = exports.Targets = exports.Snapshot = exports.Root = exports.Metadata = void 0; +var metadata_1 = require("./metadata"); +Object.defineProperty(exports, "Metadata", { enumerable: true, get: function () { return metadata_1.Metadata; } }); +var root_1 = require("./root"); +Object.defineProperty(exports, "Root", { enumerable: true, get: function () { return root_1.Root; } }); +var snapshot_1 = require("./snapshot"); +Object.defineProperty(exports, "Snapshot", { enumerable: true, get: function () { return snapshot_1.Snapshot; } }); +var targets_1 = require("./targets"); +Object.defineProperty(exports, "Targets", { enumerable: true, get: function () { return targets_1.Targets; } }); +var timestamp_1 = require("./timestamp"); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return timestamp_1.Timestamp; } }); diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/key.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/key.d.ts new file mode 100644 index 0000000..160407a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/key.d.ts @@ -0,0 +1,21 @@ +import { JSONObject, JSONValue } from '../utils/types'; +import { Signable } from './base'; +export interface KeyOptions { + keyID: string; + keyType: string; + scheme: string; + keyVal: Record; + unrecognizedFields?: Record; +} +export declare class Key { + readonly keyID: string; + readonly keyType: string; + readonly scheme: string; + readonly keyVal: Record; + readonly unrecognizedFields?: Record; + constructor(options: KeyOptions); + verifySignature(metadata: Signable): void; + equals(other: Key): boolean; + toJSON(): JSONObject; + static fromJSON(keyID: string, data: JSONObject): Key; +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/key.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/key.js new file mode 100644 index 0000000..33ff514 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/key.js @@ -0,0 +1,109 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Key = void 0; +const util_1 = __importDefault(require("util")); +const error_1 = require("../error"); +const guard_1 = require("../utils/guard"); +const key_1 = require("../utils/key"); +const signer = __importStar(require("../utils/signer")); +// A container class representing the public portion of a Key. +class Key { + constructor(options) { + const { keyID, keyType, scheme, keyVal, unrecognizedFields } = options; + this.keyID = keyID; + this.keyType = keyType; + this.scheme = scheme; + this.keyVal = keyVal; + this.unrecognizedFields = unrecognizedFields || {}; + } + // Verifies the that the metadata.signatures contains a signature made with + // this key and is correctly signed. + verifySignature(metadata) { + const signature = metadata.signatures[this.keyID]; + if (!signature) + throw new error_1.UnsignedMetadataError('no signature for key found in metadata'); + if (!this.keyVal.public) + throw new error_1.UnsignedMetadataError('no public key found'); + const publicKey = (0, key_1.getPublicKey)({ + keyType: this.keyType, + scheme: this.scheme, + keyVal: this.keyVal.public, + }); + const signedData = metadata.signed.toJSON(); + try { + if (!signer.verifySignature(signedData, publicKey, signature.sig)) { + throw new error_1.UnsignedMetadataError(`failed to verify ${this.keyID} signature`); + } + } + catch (error) { + if (error instanceof error_1.UnsignedMetadataError) { + throw error; + } + throw new error_1.UnsignedMetadataError(`failed to verify ${this.keyID} signature`); + } + } + equals(other) { + if (!(other instanceof Key)) { + return false; + } + return (this.keyID === other.keyID && + this.keyType === other.keyType && + this.scheme === other.scheme && + util_1.default.isDeepStrictEqual(this.keyVal, other.keyVal) && + util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); + } + toJSON() { + return { + keytype: this.keyType, + scheme: this.scheme, + keyval: this.keyVal, + ...this.unrecognizedFields, + }; + } + static fromJSON(keyID, data) { + const { keytype, scheme, keyval, ...rest } = data; + if (typeof keytype !== 'string') { + throw new TypeError('keytype must be a string'); + } + if (typeof scheme !== 'string') { + throw new TypeError('scheme must be a string'); + } + if (!(0, guard_1.isStringRecord)(keyval)) { + throw new TypeError('keyval must be a string record'); + } + return new Key({ + keyID, + keyType: keytype, + scheme, + keyVal: keyval, + unrecognizedFields: rest, + }); + } +} +exports.Key = Key; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/metadata.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/metadata.d.ts new file mode 100644 index 0000000..39abf03 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/metadata.d.ts @@ -0,0 +1,45 @@ +import { JSONObject, JSONValue, MetadataKind } from '../utils/types'; +import { Signable } from './base'; +import { Root } from './root'; +import { Signature } from './signature'; +import { Snapshot } from './snapshot'; +import { Targets } from './targets'; +import { Timestamp } from './timestamp'; +type MetadataType = Root | Timestamp | Snapshot | Targets; +/*** + * A container for signed TUF metadata. + * + * Provides methods to convert to and from json, read and write to and + * from JSON and to create and verify metadata signatures. + * + * ``Metadata[T]`` is a generic container type where T can be any one type of + * [``Root``, ``Timestamp``, ``Snapshot``, ``Targets``]. The purpose of this + * is to allow static type checking of the signed attribute in code using + * Metadata:: + * + * root_md = Metadata[Root].fromJSON("root.json") + * # root_md type is now Metadata[Root]. This means signed and its + * # attributes like consistent_snapshot are now statically typed and the + * # types can be verified by static type checkers and shown by IDEs + * + * Using a type constraint is not required but not doing so means T is not a + * specific type so static typing cannot happen. Note that the type constraint + * ``[Root]`` is not validated at runtime (as pure annotations are not available + * then). + * + * Apart from ``expires`` all of the arguments to the inner constructors have + * reasonable default values for new metadata. + */ +export declare class Metadata implements Signable { + signed: T; + signatures: Record; + unrecognizedFields: Record; + constructor(signed: T, signatures?: Record, unrecognizedFields?: Record); + verifyDelegate(delegatedRole: string, delegatedMetadata: Metadata): void; + equals(other: T): boolean; + static fromJSON(type: MetadataKind.Root, data: JSONObject): Metadata; + static fromJSON(type: MetadataKind.Timestamp, data: JSONObject): Metadata; + static fromJSON(type: MetadataKind.Snapshot, data: JSONObject): Metadata; + static fromJSON(type: MetadataKind.Targets, data: JSONObject): Metadata; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/metadata.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/metadata.js new file mode 100644 index 0000000..11c3c54 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/metadata.js @@ -0,0 +1,139 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Metadata = void 0; +const util_1 = __importDefault(require("util")); +const error_1 = require("../error"); +const guard_1 = require("../utils/guard"); +const types_1 = require("../utils/types"); +const root_1 = require("./root"); +const signature_1 = require("./signature"); +const snapshot_1 = require("./snapshot"); +const targets_1 = require("./targets"); +const timestamp_1 = require("./timestamp"); +/*** + * A container for signed TUF metadata. + * + * Provides methods to convert to and from json, read and write to and + * from JSON and to create and verify metadata signatures. + * + * ``Metadata[T]`` is a generic container type where T can be any one type of + * [``Root``, ``Timestamp``, ``Snapshot``, ``Targets``]. The purpose of this + * is to allow static type checking of the signed attribute in code using + * Metadata:: + * + * root_md = Metadata[Root].fromJSON("root.json") + * # root_md type is now Metadata[Root]. This means signed and its + * # attributes like consistent_snapshot are now statically typed and the + * # types can be verified by static type checkers and shown by IDEs + * + * Using a type constraint is not required but not doing so means T is not a + * specific type so static typing cannot happen. Note that the type constraint + * ``[Root]`` is not validated at runtime (as pure annotations are not available + * then). + * + * Apart from ``expires`` all of the arguments to the inner constructors have + * reasonable default values for new metadata. + */ +class Metadata { + constructor(signed, signatures, unrecognizedFields) { + this.signed = signed; + this.signatures = signatures || {}; + this.unrecognizedFields = unrecognizedFields || {}; + } + verifyDelegate(delegatedRole, delegatedMetadata) { + let role; + let keys = {}; + switch (this.signed.type) { + case types_1.MetadataKind.Root: + keys = this.signed.keys; + role = this.signed.roles[delegatedRole]; + break; + case types_1.MetadataKind.Targets: + if (!this.signed.delegations) { + throw new error_1.ValueError(`No delegations found for ${delegatedRole}`); + } + keys = this.signed.delegations.keys; + if (this.signed.delegations.roles) { + role = this.signed.delegations.roles[delegatedRole]; + } + else if (this.signed.delegations.succinctRoles) { + if (this.signed.delegations.succinctRoles.isDelegatedRole(delegatedRole)) { + role = this.signed.delegations.succinctRoles; + } + } + break; + default: + throw new TypeError('invalid metadata type'); + } + if (!role) { + throw new error_1.ValueError(`no delegation found for ${delegatedRole}`); + } + const signingKeys = new Set(); + role.keyIDs.forEach((keyID) => { + const key = keys[keyID]; + // If we dont' have the key, continue checking other keys + if (!key) { + return; + } + try { + key.verifySignature(delegatedMetadata); + signingKeys.add(key.keyID); + } + catch (error) { + // continue + } + }); + if (signingKeys.size < role.threshold) { + throw new error_1.UnsignedMetadataError(`${delegatedRole} was signed by ${signingKeys.size}/${role.threshold} keys`); + } + } + equals(other) { + if (!(other instanceof Metadata)) { + return false; + } + return (this.signed.equals(other.signed) && + util_1.default.isDeepStrictEqual(this.signatures, other.signatures) && + util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); + } + static fromJSON(type, data) { + const { signed, signatures, ...rest } = data; + if (!(0, guard_1.isDefined)(signed) || !(0, guard_1.isObject)(signed)) { + throw new TypeError('signed is not defined'); + } + if (type !== signed._type) { + throw new error_1.ValueError(`expected '${type}', got ${signed['_type']}`); + } + let signedObj; + switch (type) { + case types_1.MetadataKind.Root: + signedObj = root_1.Root.fromJSON(signed); + break; + case types_1.MetadataKind.Timestamp: + signedObj = timestamp_1.Timestamp.fromJSON(signed); + break; + case types_1.MetadataKind.Snapshot: + signedObj = snapshot_1.Snapshot.fromJSON(signed); + break; + case types_1.MetadataKind.Targets: + signedObj = targets_1.Targets.fromJSON(signed); + break; + default: + throw new TypeError('invalid metadata type'); + } + const sigMap = signaturesFromJSON(signatures); + return new Metadata(signedObj, sigMap, rest); + } +} +exports.Metadata = Metadata; +function signaturesFromJSON(data) { + if (!(0, guard_1.isObjectArray)(data)) { + throw new TypeError('signatures is not an array'); + } + return data.reduce((acc, sigData) => { + const signature = signature_1.Signature.fromJSON(sigData); + return { ...acc, [signature.keyID]: signature }; + }, {}); +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/role.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/role.d.ts new file mode 100644 index 0000000..4575300 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/role.d.ts @@ -0,0 +1,103 @@ +import { JSONObject, JSONValue } from '../utils/types'; +export declare const TOP_LEVEL_ROLE_NAMES: string[]; +export interface RoleOptions { + keyIDs: string[]; + threshold: number; + unrecognizedFields?: Record; +} +/** + * Container that defines which keys are required to sign roles metadata. + * + * Role defines how many keys are required to successfully sign the roles + * metadata, and which keys are accepted. + */ +export declare class Role { + readonly keyIDs: string[]; + readonly threshold: number; + readonly unrecognizedFields?: Record; + constructor(options: RoleOptions); + equals(other: Role): boolean; + toJSON(): JSONObject; + static fromJSON(data: JSONObject): Role; +} +interface DelegatedRoleOptions extends RoleOptions { + name: string; + terminating: boolean; + paths?: string[]; + pathHashPrefixes?: string[]; +} +/** + * A container with information about a delegated role. + * + * A delegation can happen in two ways: + * - ``paths`` is set: delegates targets matching any path pattern in ``paths`` + * - ``pathHashPrefixes`` is set: delegates targets whose target path hash + * starts with any of the prefixes in ``pathHashPrefixes`` + * + * ``paths`` and ``pathHashPrefixes`` are mutually exclusive: both cannot be + * set, at least one of them must be set. + */ +export declare class DelegatedRole extends Role { + readonly name: string; + readonly terminating: boolean; + readonly paths?: string[]; + readonly pathHashPrefixes?: string[]; + constructor(opts: DelegatedRoleOptions); + equals(other: DelegatedRole): boolean; + isDelegatedPath(targetFilepath: string): boolean; + toJSON(): JSONObject; + static fromJSON(data: JSONObject): DelegatedRole; +} +interface SuccinctRolesOption extends RoleOptions { + bitLength: number; + namePrefix: string; +} +/** + * Succinctly defines a hash bin delegation graph. + * + * A ``SuccinctRoles`` object describes a delegation graph that covers all + * targets, distributing them uniformly over the delegated roles (i.e. bins) + * in the graph. + * + * The total number of bins is 2 to the power of the passed ``bit_length``. + * + * Bin names are the concatenation of the passed ``name_prefix`` and a + * zero-padded hex representation of the bin index separated by a hyphen. + * + * The passed ``keyids`` and ``threshold`` is used for each bin, and each bin + * is 'terminating'. + * + * For details: https://github.com/theupdateframework/taps/blob/master/tap15.md + */ +export declare class SuccinctRoles extends Role { + readonly bitLength: number; + readonly namePrefix: string; + readonly numberOfBins: number; + readonly suffixLen: number; + constructor(opts: SuccinctRolesOption); + equals(other: SuccinctRoles): boolean; + /*** + * Calculates the name of the delegated role responsible for 'target_filepath'. + * + * The target at path ''target_filepath' is assigned to a bin by casting + * the left-most 'bit_length' of bits of the file path hash digest to + * int, using it as bin index between 0 and '2**bit_length - 1'. + * + * Args: + * target_filepath: URL path to a target file, relative to a base + * targets URL. + */ + getRoleForTarget(targetFilepath: string): string; + getRoles(): Generator; + /*** + * Determines whether the given ``role_name`` is in one of + * the delegated roles that ``SuccinctRoles`` represents. + * + * Args: + * role_name: The name of the role to check against. + */ + isDelegatedRole(roleName: string): boolean; + toJSON(): JSONObject; + static fromJSON(data: JSONObject): SuccinctRoles; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/role.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/role.js new file mode 100644 index 0000000..da80a09 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/role.js @@ -0,0 +1,298 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SuccinctRoles = exports.DelegatedRole = exports.Role = exports.TOP_LEVEL_ROLE_NAMES = void 0; +const crypto_1 = __importDefault(require("crypto")); +const minimatch_1 = __importDefault(require("minimatch")); +const util_1 = __importDefault(require("util")); +const error_1 = require("../error"); +const guard_1 = require("../utils/guard"); +exports.TOP_LEVEL_ROLE_NAMES = [ + 'root', + 'targets', + 'snapshot', + 'timestamp', +]; +/** + * Container that defines which keys are required to sign roles metadata. + * + * Role defines how many keys are required to successfully sign the roles + * metadata, and which keys are accepted. + */ +class Role { + constructor(options) { + const { keyIDs, threshold, unrecognizedFields } = options; + if (hasDuplicates(keyIDs)) { + throw new error_1.ValueError('duplicate key IDs found'); + } + if (threshold < 1) { + throw new error_1.ValueError('threshold must be at least 1'); + } + this.keyIDs = keyIDs; + this.threshold = threshold; + this.unrecognizedFields = unrecognizedFields || {}; + } + equals(other) { + if (!(other instanceof Role)) { + return false; + } + return (this.threshold === other.threshold && + util_1.default.isDeepStrictEqual(this.keyIDs, other.keyIDs) && + util_1.default.isDeepStrictEqual(this.unrecognizedFields, other.unrecognizedFields)); + } + toJSON() { + return { + keyids: this.keyIDs, + threshold: this.threshold, + ...this.unrecognizedFields, + }; + } + static fromJSON(data) { + const { keyids, threshold, ...rest } = data; + if (!(0, guard_1.isStringArray)(keyids)) { + throw new TypeError('keyids must be an array'); + } + if (typeof threshold !== 'number') { + throw new TypeError('threshold must be a number'); + } + return new Role({ + keyIDs: keyids, + threshold, + unrecognizedFields: rest, + }); + } +} +exports.Role = Role; +function hasDuplicates(array) { + return new Set(array).size !== array.length; +} +/** + * A container with information about a delegated role. + * + * A delegation can happen in two ways: + * - ``paths`` is set: delegates targets matching any path pattern in ``paths`` + * - ``pathHashPrefixes`` is set: delegates targets whose target path hash + * starts with any of the prefixes in ``pathHashPrefixes`` + * + * ``paths`` and ``pathHashPrefixes`` are mutually exclusive: both cannot be + * set, at least one of them must be set. + */ +class DelegatedRole extends Role { + constructor(opts) { + super(opts); + const { name, terminating, paths, pathHashPrefixes } = opts; + this.name = name; + this.terminating = terminating; + if (opts.paths && opts.pathHashPrefixes) { + throw new error_1.ValueError('paths and pathHashPrefixes are mutually exclusive'); + } + this.paths = paths; + this.pathHashPrefixes = pathHashPrefixes; + } + equals(other) { + if (!(other instanceof DelegatedRole)) { + return false; + } + return (super.equals(other) && + this.name === other.name && + this.terminating === other.terminating && + util_1.default.isDeepStrictEqual(this.paths, other.paths) && + util_1.default.isDeepStrictEqual(this.pathHashPrefixes, other.pathHashPrefixes)); + } + isDelegatedPath(targetFilepath) { + if (this.paths) { + return this.paths.some((pathPattern) => isTargetInPathPattern(targetFilepath, pathPattern)); + } + if (this.pathHashPrefixes) { + const hasher = crypto_1.default.createHash('sha256'); + const pathHash = hasher.update(targetFilepath).digest('hex'); + return this.pathHashPrefixes.some((pathHashPrefix) => pathHash.startsWith(pathHashPrefix)); + } + return false; + } + toJSON() { + const json = { + ...super.toJSON(), + name: this.name, + terminating: this.terminating, + }; + if (this.paths) { + json.paths = this.paths; + } + if (this.pathHashPrefixes) { + json.path_hash_prefixes = this.pathHashPrefixes; + } + return json; + } + static fromJSON(data) { + const { keyids, threshold, name, terminating, paths, path_hash_prefixes, ...rest } = data; + if (!(0, guard_1.isStringArray)(keyids)) { + throw new TypeError('keyids must be an array of strings'); + } + if (typeof threshold !== 'number') { + throw new TypeError('threshold must be a number'); + } + if (typeof name !== 'string') { + throw new TypeError('name must be a string'); + } + if (typeof terminating !== 'boolean') { + throw new TypeError('terminating must be a boolean'); + } + if ((0, guard_1.isDefined)(paths) && !(0, guard_1.isStringArray)(paths)) { + throw new TypeError('paths must be an array of strings'); + } + if ((0, guard_1.isDefined)(path_hash_prefixes) && !(0, guard_1.isStringArray)(path_hash_prefixes)) { + throw new TypeError('path_hash_prefixes must be an array of strings'); + } + return new DelegatedRole({ + keyIDs: keyids, + threshold, + name, + terminating, + paths, + pathHashPrefixes: path_hash_prefixes, + unrecognizedFields: rest, + }); + } +} +exports.DelegatedRole = DelegatedRole; +// JS version of Ruby's Array#zip +const zip = (a, b) => a.map((k, i) => [k, b[i]]); +function isTargetInPathPattern(target, pattern) { + const targetParts = target.split('/'); + const patternParts = pattern.split('/'); + if (patternParts.length != targetParts.length) { + return false; + } + return zip(targetParts, patternParts).every(([targetPart, patternPart]) => (0, minimatch_1.default)(targetPart, patternPart)); +} +/** + * Succinctly defines a hash bin delegation graph. + * + * A ``SuccinctRoles`` object describes a delegation graph that covers all + * targets, distributing them uniformly over the delegated roles (i.e. bins) + * in the graph. + * + * The total number of bins is 2 to the power of the passed ``bit_length``. + * + * Bin names are the concatenation of the passed ``name_prefix`` and a + * zero-padded hex representation of the bin index separated by a hyphen. + * + * The passed ``keyids`` and ``threshold`` is used for each bin, and each bin + * is 'terminating'. + * + * For details: https://github.com/theupdateframework/taps/blob/master/tap15.md + */ +class SuccinctRoles extends Role { + constructor(opts) { + super(opts); + const { bitLength, namePrefix } = opts; + if (bitLength <= 0 || bitLength > 32) { + throw new error_1.ValueError('bitLength must be between 1 and 32'); + } + this.bitLength = bitLength; + this.namePrefix = namePrefix; + // Calculate the suffix_len value based on the total number of bins in + // hex. If bit_length = 10 then number_of_bins = 1024 or bin names will + // have a suffix between "000" and "3ff" in hex and suffix_len will be 3 + // meaning the third bin will have a suffix of "003". + this.numberOfBins = Math.pow(2, bitLength); + // suffix_len is calculated based on "number_of_bins - 1" as the name + // of the last bin contains the number "number_of_bins -1" as a suffix. + this.suffixLen = (this.numberOfBins - 1).toString(16).length; + } + equals(other) { + if (!(other instanceof SuccinctRoles)) { + return false; + } + return (super.equals(other) && + this.bitLength === other.bitLength && + this.namePrefix === other.namePrefix); + } + /*** + * Calculates the name of the delegated role responsible for 'target_filepath'. + * + * The target at path ''target_filepath' is assigned to a bin by casting + * the left-most 'bit_length' of bits of the file path hash digest to + * int, using it as bin index between 0 and '2**bit_length - 1'. + * + * Args: + * target_filepath: URL path to a target file, relative to a base + * targets URL. + */ + getRoleForTarget(targetFilepath) { + const hasher = crypto_1.default.createHash('sha256'); + const hasherBuffer = hasher.update(targetFilepath).digest(); + // can't ever need more than 4 bytes (32 bits). + const hashBytes = hasherBuffer.subarray(0, 4); + // Right shift hash bytes, so that we only have the leftmost + // bit_length bits that we care about. + const shiftValue = 32 - this.bitLength; + const binNumber = hashBytes.readUInt32BE() >>> shiftValue; + // Add zero padding if necessary and cast to hex the suffix. + const suffix = binNumber.toString(16).padStart(this.suffixLen, '0'); + return `${this.namePrefix}-${suffix}`; + } + *getRoles() { + for (let i = 0; i < this.numberOfBins; i++) { + const suffix = i.toString(16).padStart(this.suffixLen, '0'); + yield `${this.namePrefix}-${suffix}`; + } + } + /*** + * Determines whether the given ``role_name`` is in one of + * the delegated roles that ``SuccinctRoles`` represents. + * + * Args: + * role_name: The name of the role to check against. + */ + isDelegatedRole(roleName) { + const desiredPrefix = this.namePrefix + '-'; + if (!roleName.startsWith(desiredPrefix)) { + return false; + } + const suffix = roleName.slice(desiredPrefix.length, roleName.length); + if (suffix.length != this.suffixLen) { + return false; + } + // make sure the suffix is a hex string + if (!suffix.match(/^[0-9a-fA-F]+$/)) { + return false; + } + const num = parseInt(suffix, 16); + return 0 <= num && num < this.numberOfBins; + } + toJSON() { + const json = { + ...super.toJSON(), + bit_length: this.bitLength, + name_prefix: this.namePrefix, + }; + return json; + } + static fromJSON(data) { + const { keyids, threshold, bit_length, name_prefix, ...rest } = data; + if (!(0, guard_1.isStringArray)(keyids)) { + throw new TypeError('keyids must be an array of strings'); + } + if (typeof threshold !== 'number') { + throw new TypeError('threshold must be a number'); + } + if (typeof bit_length !== 'number') { + throw new TypeError('bit_length must be a number'); + } + if (typeof name_prefix !== 'string') { + throw new TypeError('name_prefix must be a string'); + } + return new SuccinctRoles({ + keyIDs: keyids, + threshold, + bitLength: bit_length, + namePrefix: name_prefix, + unrecognizedFields: rest, + }); + } +} +exports.SuccinctRoles = SuccinctRoles; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/root.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/root.d.ts new file mode 100644 index 0000000..6635662 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/root.d.ts @@ -0,0 +1,28 @@ +import { JSONObject, MetadataKind } from '../utils/types'; +import { Signed, SignedOptions } from './base'; +import { Key } from './key'; +import { Role } from './role'; +type KeyMap = Record; +type RoleMap = Record; +export interface RootOptions extends SignedOptions { + keys?: Record; + roles?: Record; + consistentSnapshot?: boolean; +} +/** + * A container for the signed part of root metadata. + * + * The top-level role and metadata file signed by the root keys. + * This role specifies trusted keys for all other top-level roles, which may further delegate trust. + */ +export declare class Root extends Signed { + readonly type = MetadataKind.Root; + readonly keys: KeyMap; + readonly roles: RoleMap; + readonly consistentSnapshot: boolean; + constructor(options: RootOptions); + equals(other: Root): boolean; + toJSON(): JSONObject; + static fromJSON(data: JSONObject): Root; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/root.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/root.js new file mode 100644 index 0000000..574ec1a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/root.js @@ -0,0 +1,107 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Root = void 0; +const util_1 = __importDefault(require("util")); +const error_1 = require("../error"); +const guard_1 = require("../utils/guard"); +const types_1 = require("../utils/types"); +const base_1 = require("./base"); +const key_1 = require("./key"); +const role_1 = require("./role"); +/** + * A container for the signed part of root metadata. + * + * The top-level role and metadata file signed by the root keys. + * This role specifies trusted keys for all other top-level roles, which may further delegate trust. + */ +class Root extends base_1.Signed { + constructor(options) { + super(options); + this.type = types_1.MetadataKind.Root; + this.keys = options.keys || {}; + this.consistentSnapshot = options.consistentSnapshot ?? true; + if (!options.roles) { + this.roles = role_1.TOP_LEVEL_ROLE_NAMES.reduce((acc, role) => ({ + ...acc, + [role]: new role_1.Role({ keyIDs: [], threshold: 1 }), + }), {}); + } + else { + const roleNames = new Set(Object.keys(options.roles)); + if (!role_1.TOP_LEVEL_ROLE_NAMES.every((role) => roleNames.has(role))) { + throw new error_1.ValueError('missing top-level role'); + } + this.roles = options.roles; + } + } + equals(other) { + if (!(other instanceof Root)) { + return false; + } + return (super.equals(other) && + this.consistentSnapshot === other.consistentSnapshot && + util_1.default.isDeepStrictEqual(this.keys, other.keys) && + util_1.default.isDeepStrictEqual(this.roles, other.roles)); + } + toJSON() { + return { + spec_version: this.specVersion, + version: this.version, + expires: this.expires, + keys: keysToJSON(this.keys), + roles: rolesToJSON(this.roles), + consistent_snapshot: this.consistentSnapshot, + ...this.unrecognizedFields, + }; + } + static fromJSON(data) { + const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); + const { keys, roles, consistent_snapshot, ...rest } = unrecognizedFields; + if (typeof consistent_snapshot !== 'boolean') { + throw new TypeError('consistent_snapshot must be a boolean'); + } + return new Root({ + ...commonFields, + keys: keysFromJSON(keys), + roles: rolesFromJSON(roles), + consistentSnapshot: consistent_snapshot, + unrecognizedFields: rest, + }); + } +} +exports.Root = Root; +function keysToJSON(keys) { + return Object.entries(keys).reduce((acc, [keyID, key]) => ({ ...acc, [keyID]: key.toJSON() }), {}); +} +function rolesToJSON(roles) { + return Object.entries(roles).reduce((acc, [roleName, role]) => ({ ...acc, [roleName]: role.toJSON() }), {}); +} +function keysFromJSON(data) { + let keys; + if ((0, guard_1.isDefined)(data)) { + if (!(0, guard_1.isObjectRecord)(data)) { + throw new TypeError('keys must be an object'); + } + keys = Object.entries(data).reduce((acc, [keyID, keyData]) => ({ + ...acc, + [keyID]: key_1.Key.fromJSON(keyID, keyData), + }), {}); + } + return keys; +} +function rolesFromJSON(data) { + let roles; + if ((0, guard_1.isDefined)(data)) { + if (!(0, guard_1.isObjectRecord)(data)) { + throw new TypeError('roles must be an object'); + } + roles = Object.entries(data).reduce((acc, [roleName, roleData]) => ({ + ...acc, + [roleName]: role_1.Role.fromJSON(roleData), + }), {}); + } + return roles; +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/signature.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/signature.d.ts new file mode 100644 index 0000000..1d78e2d --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/signature.d.ts @@ -0,0 +1,19 @@ +import { JSONObject } from '../utils/types'; +export interface SignatureOptions { + keyID: string; + sig: string; +} +/** + * A container class containing information about a signature. + * + * Contains a signature and the keyid uniquely identifying the key used + * to generate the signature. + * + * Provide a `fromJSON` method to create a Signature from a JSON object. + */ +export declare class Signature { + readonly keyID: string; + readonly sig: string; + constructor(options: SignatureOptions); + static fromJSON(data: JSONObject): Signature; +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/signature.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/signature.js new file mode 100644 index 0000000..9550fa7 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/signature.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Signature = void 0; +/** + * A container class containing information about a signature. + * + * Contains a signature and the keyid uniquely identifying the key used + * to generate the signature. + * + * Provide a `fromJSON` method to create a Signature from a JSON object. + */ +class Signature { + constructor(options) { + const { keyID, sig } = options; + this.keyID = keyID; + this.sig = sig; + } + static fromJSON(data) { + const { keyid, sig } = data; + if (typeof keyid !== 'string') { + throw new TypeError('keyid must be a string'); + } + if (typeof sig !== 'string') { + throw new TypeError('sig must be a string'); + } + return new Signature({ + keyID: keyid, + sig: sig, + }); + } +} +exports.Signature = Signature; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/snapshot.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/snapshot.d.ts new file mode 100644 index 0000000..79bc073 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/snapshot.d.ts @@ -0,0 +1,23 @@ +import { JSONObject, MetadataKind } from '../utils/types'; +import { Signed, SignedOptions } from './base'; +import { MetaFile } from './file'; +type MetaFileMap = Record; +export interface SnapshotOptions extends SignedOptions { + meta?: MetaFileMap; +} +/** + * A container for the signed part of snapshot metadata. + * + * Snapshot contains information about all target Metadata files. + * A top-level role that specifies the latest versions of all targets metadata files, + * and hence the latest versions of all targets (including any dependencies between them) on the repository. + */ +export declare class Snapshot extends Signed { + readonly type = MetadataKind.Snapshot; + readonly meta: MetaFileMap; + constructor(opts: SnapshotOptions); + equals(other: Snapshot): boolean; + toJSON(): JSONObject; + static fromJSON(data: JSONObject): Snapshot; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/snapshot.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/snapshot.js new file mode 100644 index 0000000..0945a28 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/snapshot.js @@ -0,0 +1,71 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Snapshot = void 0; +const util_1 = __importDefault(require("util")); +const guard_1 = require("../utils/guard"); +const types_1 = require("../utils/types"); +const base_1 = require("./base"); +const file_1 = require("./file"); +/** + * A container for the signed part of snapshot metadata. + * + * Snapshot contains information about all target Metadata files. + * A top-level role that specifies the latest versions of all targets metadata files, + * and hence the latest versions of all targets (including any dependencies between them) on the repository. + */ +class Snapshot extends base_1.Signed { + constructor(opts) { + super(opts); + this.type = types_1.MetadataKind.Snapshot; + this.meta = opts.meta || { 'targets.json': new file_1.MetaFile({ version: 1 }) }; + } + equals(other) { + if (!(other instanceof Snapshot)) { + return false; + } + return super.equals(other) && util_1.default.isDeepStrictEqual(this.meta, other.meta); + } + toJSON() { + return { + meta: metaToJSON(this.meta), + spec_version: this.specVersion, + version: this.version, + expires: this.expires, + ...this.unrecognizedFields, + }; + } + static fromJSON(data) { + const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); + const { meta, ...rest } = unrecognizedFields; + return new Snapshot({ + ...commonFields, + meta: metaFromJSON(meta), + unrecognizedFields: rest, + }); + } +} +exports.Snapshot = Snapshot; +function metaToJSON(meta) { + return Object.entries(meta).reduce((acc, [path, metadata]) => ({ + ...acc, + [path]: metadata.toJSON(), + }), {}); +} +function metaFromJSON(data) { + let meta; + if ((0, guard_1.isDefined)(data)) { + if (!(0, guard_1.isObjectRecord)(data)) { + throw new TypeError('meta field is malformed'); + } + else { + meta = Object.entries(data).reduce((acc, [path, metadata]) => ({ + ...acc, + [path]: file_1.MetaFile.fromJSON(metadata), + }), {}); + } + return meta; + } +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/targets.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/targets.d.ts new file mode 100644 index 0000000..24dba9a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/targets.d.ts @@ -0,0 +1,19 @@ +import { JSONObject, MetadataKind } from '../utils/types'; +import { Signed, SignedOptions } from './base'; +import { Delegations } from './delegations'; +import { TargetFile } from './file'; +type TargetFileMap = Record; +interface TargetsOptions extends SignedOptions { + targets?: TargetFileMap; + delegations?: Delegations; +} +export declare class Targets extends Signed { + readonly type = MetadataKind.Targets; + readonly targets: TargetFileMap; + readonly delegations?: Delegations; + constructor(options: TargetsOptions); + equals(other: Targets): boolean; + toJSON(): JSONObject; + static fromJSON(data: JSONObject): Targets; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/targets.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/targets.js new file mode 100644 index 0000000..90a2528 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/targets.js @@ -0,0 +1,89 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Targets = void 0; +const util_1 = __importDefault(require("util")); +const guard_1 = require("../utils/guard"); +const types_1 = require("../utils/types"); +const base_1 = require("./base"); +const delegations_1 = require("./delegations"); +const file_1 = require("./file"); +// Container for the signed part of targets metadata. +// +// Targets contains verifying information about target files and also delegates +// responsible to other Targets roles. +class Targets extends base_1.Signed { + constructor(options) { + super(options); + this.type = types_1.MetadataKind.Targets; + this.targets = options.targets || {}; + this.delegations = options.delegations; + } + equals(other) { + if (!(other instanceof Targets)) { + return false; + } + return (super.equals(other) && + util_1.default.isDeepStrictEqual(this.targets, other.targets) && + util_1.default.isDeepStrictEqual(this.delegations, other.delegations)); + } + toJSON() { + const json = { + spec_version: this.specVersion, + version: this.version, + expires: this.expires, + targets: targetsToJSON(this.targets), + ...this.unrecognizedFields, + }; + if (this.delegations) { + json.delegations = this.delegations.toJSON(); + } + return json; + } + static fromJSON(data) { + const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); + const { targets, delegations, ...rest } = unrecognizedFields; + return new Targets({ + ...commonFields, + targets: targetsFromJSON(targets), + delegations: delegationsFromJSON(delegations), + unrecognizedFields: rest, + }); + } +} +exports.Targets = Targets; +function targetsToJSON(targets) { + return Object.entries(targets).reduce((acc, [path, target]) => ({ + ...acc, + [path]: target.toJSON(), + }), {}); +} +function targetsFromJSON(data) { + let targets; + if ((0, guard_1.isDefined)(data)) { + if (!(0, guard_1.isObjectRecord)(data)) { + throw new TypeError('targets must be an object'); + } + else { + targets = Object.entries(data).reduce((acc, [path, target]) => ({ + ...acc, + [path]: file_1.TargetFile.fromJSON(path, target), + }), {}); + } + } + return targets; +} +function delegationsFromJSON(data) { + let delegations; + if ((0, guard_1.isDefined)(data)) { + if (!(0, guard_1.isObject)(data)) { + throw new TypeError('delegations must be an object'); + } + else { + delegations = delegations_1.Delegations.fromJSON(data); + } + } + return delegations; +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/timestamp.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/timestamp.d.ts new file mode 100644 index 0000000..481ada8 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/timestamp.d.ts @@ -0,0 +1,21 @@ +import { JSONObject, MetadataKind } from '../utils/types'; +import { Signed, SignedOptions } from './base'; +import { MetaFile } from './file'; +interface TimestampOptions extends SignedOptions { + snapshotMeta?: MetaFile; +} +/** + * A container for the signed part of timestamp metadata. + * + * A top-level that specifies the latest version of the snapshot role metadata file, + * and hence the latest versions of all metadata and targets on the repository. + */ +export declare class Timestamp extends Signed { + readonly type = MetadataKind.Timestamp; + readonly snapshotMeta: MetaFile; + constructor(options: TimestampOptions); + equals(other: Timestamp): boolean; + toJSON(): JSONObject; + static fromJSON(data: JSONObject): Timestamp; +} +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/timestamp.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/timestamp.js new file mode 100644 index 0000000..84f681b --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/models/timestamp.js @@ -0,0 +1,58 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Timestamp = void 0; +const guard_1 = require("../utils/guard"); +const types_1 = require("../utils/types"); +const base_1 = require("./base"); +const file_1 = require("./file"); +/** + * A container for the signed part of timestamp metadata. + * + * A top-level that specifies the latest version of the snapshot role metadata file, + * and hence the latest versions of all metadata and targets on the repository. + */ +class Timestamp extends base_1.Signed { + constructor(options) { + super(options); + this.type = types_1.MetadataKind.Timestamp; + this.snapshotMeta = options.snapshotMeta || new file_1.MetaFile({ version: 1 }); + } + equals(other) { + if (!(other instanceof Timestamp)) { + return false; + } + return super.equals(other) && this.snapshotMeta.equals(other.snapshotMeta); + } + toJSON() { + return { + spec_version: this.specVersion, + version: this.version, + expires: this.expires, + meta: { 'snapshot.json': this.snapshotMeta.toJSON() }, + ...this.unrecognizedFields, + }; + } + static fromJSON(data) { + const { unrecognizedFields, ...commonFields } = base_1.Signed.commonFieldsFromJSON(data); + const { meta, ...rest } = unrecognizedFields; + return new Timestamp({ + ...commonFields, + snapshotMeta: snapshotMetaFromJSON(meta), + unrecognizedFields: rest, + }); + } +} +exports.Timestamp = Timestamp; +function snapshotMetaFromJSON(data) { + let snapshotMeta; + if ((0, guard_1.isDefined)(data)) { + const snapshotData = data['snapshot.json']; + if (!(0, guard_1.isDefined)(snapshotData) || !(0, guard_1.isObject)(snapshotData)) { + throw new TypeError('missing snapshot.json in meta'); + } + else { + snapshotMeta = file_1.MetaFile.fromJSON(snapshotData); + } + } + return snapshotMeta; +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/store.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/store.d.ts new file mode 100644 index 0000000..a6e20ae --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/store.d.ts @@ -0,0 +1,19 @@ +/// +import { Metadata, Root, Snapshot, Targets, Timestamp } from './models'; +export declare class TrustedMetadataStore { + private trustedSet; + private referenceTime; + constructor(rootData: Buffer); + get root(): Metadata; + get timestamp(): Metadata | undefined; + get snapshot(): Metadata | undefined; + get targets(): Metadata | undefined; + getRole(name: string): Metadata | undefined; + updateRoot(bytesBuffer: Buffer): Metadata; + updateTimestamp(bytesBuffer: Buffer): Metadata; + updateSnapshot(bytesBuffer: Buffer, trusted?: boolean): Metadata; + updateDelegatedTargets(bytesBuffer: Buffer, roleName: string, delegatorName: string): void; + private loadTrustedRoot; + private checkFinalTimestamp; + private checkFinalSnapsnot; +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/store.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/store.js new file mode 100644 index 0000000..351a196 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/store.js @@ -0,0 +1,209 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.TrustedMetadataStore = void 0; +const error_1 = require("./error"); +const models_1 = require("./models"); +const types_1 = require("./utils/types"); +class TrustedMetadataStore { + constructor(rootData) { + this.trustedSet = {}; + // Client workflow 5.1: record fixed update start time + this.referenceTime = new Date(); + // Client workflow 5.2: load trusted root metadata + this.loadTrustedRoot(rootData); + } + get root() { + if (!this.trustedSet.root) { + throw new ReferenceError('No trusted root metadata'); + } + return this.trustedSet.root; + } + get timestamp() { + return this.trustedSet.timestamp; + } + get snapshot() { + return this.trustedSet.snapshot; + } + get targets() { + return this.trustedSet.targets; + } + getRole(name) { + return this.trustedSet[name]; + } + updateRoot(bytesBuffer) { + const data = JSON.parse(bytesBuffer.toString('utf8')); + const newRoot = models_1.Metadata.fromJSON(types_1.MetadataKind.Root, data); + if (newRoot.signed.type != types_1.MetadataKind.Root) { + throw new error_1.RepositoryError(`Expected 'root', got ${newRoot.signed.type}`); + } + // Client workflow 5.4: check for arbitrary software attack + this.root.verifyDelegate(types_1.MetadataKind.Root, newRoot); + // Client workflow 5.5: check for rollback attack + if (newRoot.signed.version != this.root.signed.version + 1) { + throw new error_1.BadVersionError(`Expected version ${this.root.signed.version + 1}, got ${newRoot.signed.version}`); + } + // Check that new root is signed by self + newRoot.verifyDelegate(types_1.MetadataKind.Root, newRoot); + // Client workflow 5.7: set new root as trusted root + this.trustedSet.root = newRoot; + return newRoot; + } + updateTimestamp(bytesBuffer) { + if (this.snapshot) { + throw new error_1.RuntimeError('Cannot update timestamp after snapshot'); + } + if (this.root.signed.isExpired(this.referenceTime)) { + throw new error_1.ExpiredMetadataError('Final root.json is expired'); + } + const data = JSON.parse(bytesBuffer.toString('utf8')); + const newTimestamp = models_1.Metadata.fromJSON(types_1.MetadataKind.Timestamp, data); + if (newTimestamp.signed.type != types_1.MetadataKind.Timestamp) { + throw new error_1.RepositoryError(`Expected 'timestamp', got ${newTimestamp.signed.type}`); + } + // Client workflow 5.4.2: check for arbitrary software attack + this.root.verifyDelegate(types_1.MetadataKind.Timestamp, newTimestamp); + if (this.timestamp) { + // Prevent rolling back timestamp version + // Client workflow 5.4.3.1: check for rollback attack + if (newTimestamp.signed.version < this.timestamp.signed.version) { + throw new error_1.BadVersionError(`New timestamp version ${newTimestamp.signed.version} is less than current version ${this.timestamp.signed.version}`); + } + // Keep using old timestamp if versions are equal. + if (newTimestamp.signed.version === this.timestamp.signed.version) { + throw new error_1.EqualVersionError(`New timestamp version ${newTimestamp.signed.version} is equal to current version ${this.timestamp.signed.version}`); + } + // Prevent rolling back snapshot version + // Client workflow 5.4.3.2: check for rollback attack + const snapshotMeta = this.timestamp.signed.snapshotMeta; + const newSnapshotMeta = newTimestamp.signed.snapshotMeta; + if (newSnapshotMeta.version < snapshotMeta.version) { + throw new error_1.BadVersionError(`New snapshot version ${newSnapshotMeta.version} is less than current version ${snapshotMeta.version}`); + } + } + // expiry not checked to allow old timestamp to be used for rollback + // protection of new timestamp: expiry is checked in update_snapshot + this.trustedSet.timestamp = newTimestamp; + // Client workflow 5.4.4: check for freeze attack + this.checkFinalTimestamp(); + return newTimestamp; + } + updateSnapshot(bytesBuffer, trusted = false) { + if (!this.timestamp) { + throw new error_1.RuntimeError('Cannot update snapshot before timestamp'); + } + if (this.targets) { + throw new error_1.RuntimeError('Cannot update snapshot after targets'); + } + // Snapshot cannot be loaded if final timestamp is expired + this.checkFinalTimestamp(); + const snapshotMeta = this.timestamp.signed.snapshotMeta; + // Verify non-trusted data against the hashes in timestamp, if any. + // Trusted snapshot data has already been verified once. + // Client workflow 5.5.2: check against timestamp role's snaphsot hash + if (!trusted) { + snapshotMeta.verify(bytesBuffer); + } + const data = JSON.parse(bytesBuffer.toString('utf8')); + const newSnapshot = models_1.Metadata.fromJSON(types_1.MetadataKind.Snapshot, data); + if (newSnapshot.signed.type != types_1.MetadataKind.Snapshot) { + throw new error_1.RepositoryError(`Expected 'snapshot', got ${newSnapshot.signed.type}`); + } + // Client workflow 5.5.3: check for arbitrary software attack + this.root.verifyDelegate(types_1.MetadataKind.Snapshot, newSnapshot); + // version check against meta version (5.5.4) is deferred to allow old + // snapshot to be used in rollback protection + // Client workflow 5.5.5: check for rollback attack + if (this.snapshot) { + Object.entries(this.snapshot.signed.meta).forEach(([fileName, fileInfo]) => { + const newFileInfo = newSnapshot.signed.meta[fileName]; + if (!newFileInfo) { + throw new error_1.RepositoryError(`Missing file ${fileName} in new snapshot`); + } + if (newFileInfo.version < fileInfo.version) { + throw new error_1.BadVersionError(`New version ${newFileInfo.version} of ${fileName} is less than current version ${fileInfo.version}`); + } + }); + } + this.trustedSet.snapshot = newSnapshot; + // snapshot is loaded, but we raise if it's not valid _final_ snapshot + // Client workflow 5.5.4 & 5.5.6 + this.checkFinalSnapsnot(); + return newSnapshot; + } + updateDelegatedTargets(bytesBuffer, roleName, delegatorName) { + if (!this.snapshot) { + throw new error_1.RuntimeError('Cannot update delegated targets before snapshot'); + } + // Targets cannot be loaded if final snapshot is expired or its version + // does not match meta version in timestamp. + this.checkFinalSnapsnot(); + const delegator = this.trustedSet[delegatorName]; + if (!delegator) { + throw new error_1.RuntimeError(`No trusted ${delegatorName} metadata`); + } + // Extract metadata for the delegated role from snapshot + const meta = this.snapshot.signed.meta?.[`${roleName}.json`]; + if (!meta) { + throw new error_1.RepositoryError(`Missing ${roleName}.json in snapshot`); + } + // Client workflow 5.6.2: check against snapshot role's targets hash + meta.verify(bytesBuffer); + const data = JSON.parse(bytesBuffer.toString('utf8')); + const newDelegate = models_1.Metadata.fromJSON(types_1.MetadataKind.Targets, data); + if (newDelegate.signed.type != types_1.MetadataKind.Targets) { + throw new error_1.RepositoryError(`Expected 'targets', got ${newDelegate.signed.type}`); + } + // Client workflow 5.6.3: check for arbitrary software attack + delegator.verifyDelegate(roleName, newDelegate); + // Client workflow 5.6.4: Check against snapshot role’s targets version + const version = newDelegate.signed.version; + if (version != meta.version) { + throw new error_1.BadVersionError(`Version ${version} of ${roleName} does not match snapshot version ${meta.version}`); + } + // Client workflow 5.6.5: check for a freeze attack + if (newDelegate.signed.isExpired(this.referenceTime)) { + throw new error_1.ExpiredMetadataError(`${roleName}.json is expired`); + } + this.trustedSet[roleName] = newDelegate; + } + // Verifies and loads data as trusted root metadata. + // Note that an expired initial root is still considered valid. + loadTrustedRoot(bytesBuffer) { + const data = JSON.parse(bytesBuffer.toString('utf8')); + const root = models_1.Metadata.fromJSON(types_1.MetadataKind.Root, data); + if (root.signed.type != types_1.MetadataKind.Root) { + throw new error_1.RepositoryError(`Expected 'root', got ${root.signed.type}`); + } + root.verifyDelegate(types_1.MetadataKind.Root, root); + this.trustedSet['root'] = root; + } + checkFinalTimestamp() { + // Timestamp MUST be loaded + if (!this.timestamp) { + throw new ReferenceError('No trusted timestamp metadata'); + } + // Client workflow 5.4.4: check for freeze attack + if (this.timestamp.signed.isExpired(this.referenceTime)) { + throw new error_1.ExpiredMetadataError('Final timestamp.json is expired'); + } + } + checkFinalSnapsnot() { + // Snapshot and timestamp MUST be loaded + if (!this.snapshot) { + throw new ReferenceError('No trusted snapshot metadata'); + } + if (!this.timestamp) { + throw new ReferenceError('No trusted timestamp metadata'); + } + // Client workflow 5.5.6: check for freeze attack + if (this.snapshot.signed.isExpired(this.referenceTime)) { + throw new error_1.ExpiredMetadataError('snapshot.json is expired'); + } + // Client workflow 5.5.4: check against timestamp role’s snapshot version + const snapshotMeta = this.timestamp.signed.snapshotMeta; + if (this.snapshot.signed.version !== snapshotMeta.version) { + throw new error_1.BadVersionError("Snapshot version doesn't match timestamp"); + } + } +} +exports.TrustedMetadataStore = TrustedMetadataStore; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/updater.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/updater.d.ts new file mode 100644 index 0000000..e49dca2 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/updater.d.ts @@ -0,0 +1,33 @@ +import { BaseFetcher } from './fetcher'; +import { TargetFile } from './models/file'; +import { Config } from './utils/config'; +export interface UpdaterOptions { + metadataDir: string; + metadataBaseUrl: string; + targetDir?: string; + targetBaseUrl?: string; + fetcher?: BaseFetcher; + config?: Partial; +} +export declare class Updater { + private dir; + private metadataBaseUrl; + private targetDir?; + private targetBaseUrl?; + private trustedSet; + private config; + private fetcher; + constructor(options: UpdaterOptions); + refresh(): Promise; + getTargetInfo(targetPath: string): Promise; + downloadTarget(targetInfo: TargetFile, filePath?: string, targetBaseUrl?: string): Promise; + findCachedTarget(targetInfo: TargetFile, filePath?: string): Promise; + private loadLocalMetadata; + private loadRoot; + private loadTimestamp; + private loadSnapshot; + private loadTargets; + private preorderDepthFirstWalk; + private generateTargetPath; + private persistMetadata; +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/updater.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/updater.js new file mode 100644 index 0000000..9f33c66 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/updater.js @@ -0,0 +1,306 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Updater = void 0; +const fs = __importStar(require("fs")); +const path = __importStar(require("path")); +const error_1 = require("./error"); +const fetcher_1 = require("./fetcher"); +const store_1 = require("./store"); +const config_1 = require("./utils/config"); +const types_1 = require("./utils/types"); +class Updater { + constructor(options) { + const { metadataDir, metadataBaseUrl, targetDir, targetBaseUrl, fetcher, config, } = options; + this.dir = metadataDir; + this.metadataBaseUrl = metadataBaseUrl; + this.targetDir = targetDir; + this.targetBaseUrl = targetBaseUrl; + const data = this.loadLocalMetadata(types_1.MetadataKind.Root); + this.trustedSet = new store_1.TrustedMetadataStore(data); + this.config = { ...config_1.defaultConfig, ...config }; + this.fetcher = + fetcher || + new fetcher_1.Fetcher({ + timeout: this.config.fetchTimeout, + retries: this.config.fetchRetries, + }); + } + async refresh() { + await this.loadRoot(); + await this.loadTimestamp(); + await this.loadSnapshot(); + await this.loadTargets(types_1.MetadataKind.Targets, types_1.MetadataKind.Root); + } + // Returns the TargetFile instance with information for the given target path. + // + // Implicitly calls refresh if it hasn't already been called. + async getTargetInfo(targetPath) { + if (!this.trustedSet.targets) { + await this.refresh(); + } + return this.preorderDepthFirstWalk(targetPath); + } + async downloadTarget(targetInfo, filePath, targetBaseUrl) { + const targetPath = filePath || this.generateTargetPath(targetInfo); + if (!targetBaseUrl) { + if (!this.targetBaseUrl) { + throw new error_1.ValueError('Target base URL not set'); + } + targetBaseUrl = this.targetBaseUrl; + } + let targetFilePath = targetInfo.path; + const consistentSnapshot = this.trustedSet.root.signed.consistentSnapshot; + if (consistentSnapshot && this.config.prefixTargetsWithHash) { + const hashes = Object.values(targetInfo.hashes); + const basename = path.basename(targetFilePath); + targetFilePath = `${hashes[0]}.${basename}`; + } + const url = path.join(targetBaseUrl, targetFilePath); + // Client workflow 5.7.3: download target file + await this.fetcher.downloadFile(url, targetInfo.length, async (fileName) => { + // Verify hashes and length of downloaded file + await targetInfo.verify(fs.createReadStream(fileName)); + // Copy file to target path + fs.copyFileSync(fileName, targetPath); + }); + return targetPath; + } + async findCachedTarget(targetInfo, filePath) { + if (!filePath) { + filePath = this.generateTargetPath(targetInfo); + } + try { + if (fs.existsSync(filePath)) { + targetInfo.verify(fs.createReadStream(filePath)); + return filePath; + } + } + catch (error) { + return; // File not found + } + return; // File not found + } + loadLocalMetadata(fileName) { + const filePath = path.join(this.dir, `${fileName}.json`); + return fs.readFileSync(filePath); + } + // Sequentially load and persist on local disk every newer root metadata + // version available on the remote. + // Client workflow 5.3: update root role + async loadRoot() { + // Client workflow 5.3.2: version of trusted root metadata file + const rootVersion = this.trustedSet.root.signed.version; + const lowerBound = rootVersion + 1; + const upperBound = lowerBound + this.config.maxRootRotations; + for (let version = lowerBound; version <= upperBound; version++) { + const url = path.join(this.metadataBaseUrl, `${version}.root.json`); + try { + // Client workflow 5.3.3: download new root metadata file + const bytesData = await this.fetcher.downloadBytes(url, this.config.rootMaxLength); + // Client workflow 5.3.4 - 5.4.7 + this.trustedSet.updateRoot(bytesData); + // Client workflow 5.3.8: persist root metadata file + this.persistMetadata(types_1.MetadataKind.Root, bytesData); + } + catch (error) { + break; + } + } + } + // Load local and remote timestamp metadata. + // Client workflow 5.4: update timestamp role + async loadTimestamp() { + // Load local and remote timestamp metadata + try { + const data = this.loadLocalMetadata(types_1.MetadataKind.Timestamp); + this.trustedSet.updateTimestamp(data); + } + catch (error) { + // continue + } + //Load from remote (whether local load succeeded or not) + const url = path.join(this.metadataBaseUrl, `timestamp.json`); + // Client workflow 5.4.1: download timestamp metadata file + const bytesData = await this.fetcher.downloadBytes(url, this.config.timestampMaxLength); + try { + // Client workflow 5.4.2 - 5.4.4 + this.trustedSet.updateTimestamp(bytesData); + } + catch (error) { + // If new timestamp version is same as current, discardd the new one. + // This is normal and should NOT raise an error. + if (error instanceof error_1.EqualVersionError) { + return; + } + // Re-raise any other error + throw error; + } + // Client workflow 5.4.5: persist timestamp metadata + this.persistMetadata(types_1.MetadataKind.Timestamp, bytesData); + } + // Load local and remote snapshot metadata. + // Client workflow 5.5: update snapshot role + async loadSnapshot() { + //Load local (and if needed remote) snapshot metadata + try { + const data = this.loadLocalMetadata(types_1.MetadataKind.Snapshot); + this.trustedSet.updateSnapshot(data, true); + } + catch (error) { + if (!this.trustedSet.timestamp) { + throw new ReferenceError('No timestamp metadata'); + } + const snapshotMeta = this.trustedSet.timestamp.signed.snapshotMeta; + const maxLength = snapshotMeta.length || this.config.snapshotMaxLength; + const version = this.trustedSet.root.signed.consistentSnapshot + ? snapshotMeta.version + : undefined; + const url = path.join(this.metadataBaseUrl, version ? `${version}.snapshot.json` : `snapshot.json`); + try { + // Client workflow 5.5.1: download snapshot metadata file + const bytesData = await this.fetcher.downloadBytes(url, maxLength); + // Client workflow 5.5.2 - 5.5.6 + this.trustedSet.updateSnapshot(bytesData); + // Client workflow 5.5.7: persist snapshot metadata file + this.persistMetadata(types_1.MetadataKind.Snapshot, bytesData); + } + catch (error) { + throw new error_1.RuntimeError(`Unable to load snapshot metadata error ${error}`); + } + } + } + // Load local and remote targets metadata. + // Client workflow 5.6: update targets role + async loadTargets(role, parentRole) { + if (this.trustedSet.getRole(role)) { + return this.trustedSet.getRole(role); + } + try { + const buffer = this.loadLocalMetadata(role); + this.trustedSet.updateDelegatedTargets(buffer, role, parentRole); + } + catch (error) { + // Local 'role' does not exist or is invalid: update from remote + if (!this.trustedSet.snapshot) { + throw new ReferenceError('No snapshot metadata'); + } + const metaInfo = this.trustedSet.snapshot.signed.meta[`${role}.json`]; + // TODO: use length for fetching + const maxLength = metaInfo.length || this.config.targetsMaxLength; + const version = this.trustedSet.root.signed.consistentSnapshot + ? metaInfo.version + : undefined; + const url = path.join(this.metadataBaseUrl, version ? `${version}.${role}.json` : `${role}.json`); + try { + // Client workflow 5.6.1: download targets metadata file + const bytesData = await this.fetcher.downloadBytes(url, maxLength); + // Client workflow 5.6.2 - 5.6.6 + this.trustedSet.updateDelegatedTargets(bytesData, role, parentRole); + // Client workflow 5.6.7: persist targets metadata file + this.persistMetadata(role, bytesData); + } + catch (error) { + throw new error_1.RuntimeError(`Unable to load targets error ${error}`); + } + } + return this.trustedSet.getRole(role); + } + async preorderDepthFirstWalk(targetPath) { + // Interrogates the tree of target delegations in order of appearance + // (which implicitly order trustworthiness), and returns the matching + // target found in the most trusted role. + // List of delegations to be interrogated. A (role, parent role) pair + // is needed to load and verify the delegated targets metadata. + const delegationsToVisit = [ + { + roleName: types_1.MetadataKind.Targets, + parentRoleName: types_1.MetadataKind.Root, + }, + ]; + const visitedRoleNames = new Set(); + // Client workflow 5.6.7: preorder depth-first traversal of the graph of + // target delegations + while (visitedRoleNames.size <= this.config.maxDelegations && + delegationsToVisit.length > 0) { + // Pop the role name from the top of the stack. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const { roleName, parentRoleName } = delegationsToVisit.pop(); + // Skip any visited current role to prevent cycles. + // Client workflow 5.6.7.1: skip already-visited roles + if (visitedRoleNames.has(roleName)) { + continue; + } + // The metadata for 'role_name' must be downloaded/updated before + // its targets, delegations, and child roles can be inspected. + const targets = (await this.loadTargets(roleName, parentRoleName)) + ?.signed; + if (!targets) { + continue; + } + const target = targets.targets?.[targetPath]; + if (target) { + return target; + } + // After preorder check, add current role to set of visited roles. + visitedRoleNames.add(roleName); + if (targets.delegations) { + const childRolesToVisit = []; + // NOTE: This may be a slow operation if there are many delegated roles. + const rolesForTarget = targets.delegations.rolesForTarget(targetPath); + for (const { role: childName, terminating } of rolesForTarget) { + childRolesToVisit.push({ + roleName: childName, + parentRoleName: roleName, + }); + // Client workflow 5.6.7.2.1 + if (terminating) { + delegationsToVisit.splice(0); // empty the array + break; + } + } + childRolesToVisit.reverse(); + delegationsToVisit.push(...childRolesToVisit); + } + } + return; // no matching target found + } + generateTargetPath(targetInfo) { + if (!this.targetDir) { + throw new error_1.ValueError('Target directory not set'); + } + return path.join(this.targetDir, targetInfo.path); + } + async persistMetadata(metaDataName, bytesData) { + try { + const filePath = path.join(this.dir, `${metaDataName}.json`); + fs.writeFileSync(filePath, bytesData.toString('utf8')); + } + catch (error) { + throw new error_1.PersistError(`Failed to persist metadata ${metaDataName} error: ${error}`); + } + } +} +exports.Updater = Updater; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/config.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/config.d.ts new file mode 100644 index 0000000..2a906c7 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/config.d.ts @@ -0,0 +1,12 @@ +export declare const defaultConfig: { + maxRootRotations: number; + maxDelegations: number; + rootMaxLength: number; + timestampMaxLength: number; + snapshotMaxLength: number; + targetsMaxLength: number; + prefixTargetsWithHash: boolean; + fetchTimeout: number; + fetchRetries: number; +}; +export type Config = typeof defaultConfig; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/config.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/config.js new file mode 100644 index 0000000..c2d970e --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/config.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defaultConfig = void 0; +exports.defaultConfig = { + maxRootRotations: 32, + maxDelegations: 32, + rootMaxLength: 512000, + timestampMaxLength: 16384, + snapshotMaxLength: 2000000, + targetsMaxLength: 5000000, + prefixTargetsWithHash: true, + fetchTimeout: 100000, + fetchRetries: 2, +}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/guard.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/guard.d.ts new file mode 100644 index 0000000..17bc4ce --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/guard.d.ts @@ -0,0 +1,8 @@ +import { JSONObject, MetadataKind } from './types'; +export declare function isDefined(val: T | undefined): val is T; +export declare function isObject(value: unknown): value is JSONObject; +export declare function isStringArray(value: unknown): value is string[]; +export declare function isObjectArray(value: unknown): value is JSONObject[]; +export declare function isStringRecord(value: unknown): value is Record; +export declare function isObjectRecord(value: unknown): value is Record; +export declare function isMetadataKind(value: unknown): value is MetadataKind; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/guard.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/guard.js new file mode 100644 index 0000000..f2207af --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/guard.js @@ -0,0 +1,39 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isMetadataKind = exports.isObjectRecord = exports.isStringRecord = exports.isObjectArray = exports.isStringArray = exports.isObject = exports.isDefined = void 0; +const types_1 = require("./types"); +function isDefined(val) { + return val !== undefined; +} +exports.isDefined = isDefined; +function isObject(value) { + return typeof value === 'object' && value !== null; +} +exports.isObject = isObject; +function isStringArray(value) { + return Array.isArray(value) && value.every((v) => typeof v === 'string'); +} +exports.isStringArray = isStringArray; +function isObjectArray(value) { + return Array.isArray(value) && value.every(isObject); +} +exports.isObjectArray = isObjectArray; +function isStringRecord(value) { + return (typeof value === 'object' && + value !== null && + Object.keys(value).every((k) => typeof k === 'string') && + Object.values(value).every((v) => typeof v === 'string')); +} +exports.isStringRecord = isStringRecord; +function isObjectRecord(value) { + return (typeof value === 'object' && + value !== null && + Object.keys(value).every((k) => typeof k === 'string') && + Object.values(value).every((v) => typeof v === 'object' && v !== null)); +} +exports.isObjectRecord = isObjectRecord; +function isMetadataKind(value) { + return (typeof value === 'string' && + Object.values(types_1.MetadataKind).includes(value)); +} +exports.isMetadataKind = isMetadataKind; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/index.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/index.d.ts new file mode 100644 index 0000000..e2232bc --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/index.d.ts @@ -0,0 +1,5 @@ +export * as config from './config'; +export * as guard from './guard'; +export * as json from './json'; +export * as signer from './signer'; +export * as types from './types'; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/index.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/index.js new file mode 100644 index 0000000..604696a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/index.js @@ -0,0 +1,31 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.types = exports.signer = exports.json = exports.guard = exports.config = void 0; +exports.config = __importStar(require("./config")); +exports.guard = __importStar(require("./guard")); +exports.json = __importStar(require("./json")); +exports.signer = __importStar(require("./signer")); +exports.types = __importStar(require("./types")); diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/json.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/json.d.ts new file mode 100644 index 0000000..ecddbee --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/json.d.ts @@ -0,0 +1,2 @@ +/// +export declare function canonicalize(object: any): Buffer; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/json.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/json.js new file mode 100644 index 0000000..30f82ea --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/json.js @@ -0,0 +1,62 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.canonicalize = void 0; +const QUOTATION_MARK = Buffer.from('"'); +const COMMA = Buffer.from(','); +const COLON = Buffer.from(':'); +const LEFT_SQUARE_BRACKET = Buffer.from('['); +const RIGHT_SQUARE_BRACKET = Buffer.from(']'); +const LEFT_CURLY_BRACKET = Buffer.from('{'); +const RIGHT_CURLY_BRACKET = Buffer.from('}'); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function canonicalize(object) { + let buffer = Buffer.from(''); + if (object === null || typeof object !== 'object' || object.toJSON != null) { + // Primitives or toJSONable objects + if (typeof object === 'string') { + buffer = Buffer.concat([ + buffer, + QUOTATION_MARK, + Buffer.from(object), + QUOTATION_MARK, + ]); + } + else { + buffer = Buffer.concat([buffer, Buffer.from(JSON.stringify(object))]); + } + } + else if (Array.isArray(object)) { + // Array - maintain element order + buffer = Buffer.concat([buffer, LEFT_SQUARE_BRACKET]); + let first = true; + object.forEach((element) => { + if (!first) { + buffer = Buffer.concat([buffer, COMMA]); + } + first = false; + // recursive call + buffer = Buffer.concat([buffer, canonicalize(element)]); + }); + buffer = Buffer.concat([buffer, RIGHT_SQUARE_BRACKET]); + } + else { + // Object - Sort properties before serializing + buffer = Buffer.concat([buffer, LEFT_CURLY_BRACKET]); + let first = true; + Object.keys(object) + .sort() + .forEach((property) => { + if (!first) { + buffer = Buffer.concat([buffer, COMMA]); + } + first = false; + buffer = Buffer.concat([buffer, Buffer.from(JSON.stringify(property))]); + buffer = Buffer.concat([buffer, COLON]); + // recursive call + buffer = Buffer.concat([buffer, canonicalize(object[property])]); + }); + buffer = Buffer.concat([buffer, RIGHT_CURLY_BRACKET]); + } + return buffer; +} +exports.canonicalize = canonicalize; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/key.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/key.d.ts new file mode 100644 index 0000000..7b63128 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/key.d.ts @@ -0,0 +1,9 @@ +/// +import { VerifyKeyObjectInput } from 'crypto'; +interface KeyInfo { + keyType: string; + scheme: string; + keyVal: string; +} +export declare function getPublicKey(keyInfo: KeyInfo): VerifyKeyObjectInput; +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/key.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/key.js new file mode 100644 index 0000000..1f795ba --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/key.js @@ -0,0 +1,143 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getPublicKey = void 0; +const crypto_1 = __importDefault(require("crypto")); +const error_1 = require("../error"); +const oid_1 = require("./oid"); +const ASN1_TAG_SEQUENCE = 0x30; +const ANS1_TAG_BIT_STRING = 0x03; +const NULL_BYTE = 0x00; +const OID_EDDSA = '1.3.101.112'; +const OID_EC_PUBLIC_KEY = '1.2.840.10045.2.1'; +const OID_EC_CURVE_P256V1 = '1.2.840.10045.3.1.7'; +const PEM_HEADER = '-----BEGIN PUBLIC KEY-----'; +function getPublicKey(keyInfo) { + switch (keyInfo.keyType) { + case 'rsa': + return getRSAPublicKey(keyInfo); + case 'ed25519': + return getED25519PublicKey(keyInfo); + case 'ecdsa': + case 'ecdsa-sha2-nistp256': + case 'ecdsa-sha2-nistp384': + return getECDCSAPublicKey(keyInfo); + default: + throw new error_1.UnsupportedAlgorithmError(`Unsupported key type: ${keyInfo.keyType}`); + } +} +exports.getPublicKey = getPublicKey; +function getRSAPublicKey(keyInfo) { + // Only support PEM-encoded RSA keys + if (!keyInfo.keyVal.startsWith(PEM_HEADER)) { + throw new error_1.CryptoError('Invalid key format'); + } + const key = crypto_1.default.createPublicKey(keyInfo.keyVal); + switch (keyInfo.scheme) { + case 'rsassa-pss-sha256': + return { + key: key, + padding: crypto_1.default.constants.RSA_PKCS1_PSS_PADDING, + }; + default: + throw new error_1.UnsupportedAlgorithmError(`Unsupported RSA scheme: ${keyInfo.scheme}`); + } +} +function getED25519PublicKey(keyInfo) { + let key; + // If key is already PEM-encoded we can just parse it + if (keyInfo.keyVal.startsWith(PEM_HEADER)) { + key = crypto_1.default.createPublicKey(keyInfo.keyVal); + } + else { + // If key is not PEM-encoded it had better be hex + if (!isHex(keyInfo.keyVal)) { + throw new error_1.CryptoError('Invalid key format'); + } + key = crypto_1.default.createPublicKey({ + key: ed25519.hexToDER(keyInfo.keyVal), + format: 'der', + type: 'spki', + }); + } + return { key }; +} +function getECDCSAPublicKey(keyInfo) { + let key; + // If key is already PEM-encoded we can just parse it + if (keyInfo.keyVal.startsWith(PEM_HEADER)) { + key = crypto_1.default.createPublicKey(keyInfo.keyVal); + } + else { + // If key is not PEM-encoded it had better be hex + if (!isHex(keyInfo.keyVal)) { + throw new error_1.CryptoError('Invalid key format'); + } + key = crypto_1.default.createPublicKey({ + key: ecdsa.hexToDER(keyInfo.keyVal), + format: 'der', + type: 'spki', + }); + } + return { key }; +} +const ed25519 = { + // Translates a hex key into a crypto KeyObject + // https://keygen.sh/blog/how-to-use-hexadecimal-ed25519-keys-in-node/ + hexToDER: (hex) => { + const key = Buffer.from(hex, 'hex'); + const oid = (0, oid_1.encodeOIDString)(OID_EDDSA); + // Create a byte sequence containing the OID and key + const elements = Buffer.concat([ + Buffer.concat([ + Buffer.from([ASN1_TAG_SEQUENCE]), + Buffer.from([oid.length]), + oid, + ]), + Buffer.concat([ + Buffer.from([ANS1_TAG_BIT_STRING]), + Buffer.from([key.length + 1]), + Buffer.from([NULL_BYTE]), + key, + ]), + ]); + // Wrap up by creating a sequence of elements + const der = Buffer.concat([ + Buffer.from([ASN1_TAG_SEQUENCE]), + Buffer.from([elements.length]), + elements, + ]); + return der; + }, +}; +const ecdsa = { + hexToDER: (hex) => { + const key = Buffer.from(hex, 'hex'); + const bitString = Buffer.concat([ + Buffer.from([ANS1_TAG_BIT_STRING]), + Buffer.from([key.length + 1]), + Buffer.from([NULL_BYTE]), + key, + ]); + const oids = Buffer.concat([ + (0, oid_1.encodeOIDString)(OID_EC_PUBLIC_KEY), + (0, oid_1.encodeOIDString)(OID_EC_CURVE_P256V1), + ]); + const oidSequence = Buffer.concat([ + Buffer.from([ASN1_TAG_SEQUENCE]), + Buffer.from([oids.length]), + oids, + ]); + // Wrap up by creating a sequence of elements + const der = Buffer.concat([ + Buffer.from([ASN1_TAG_SEQUENCE]), + Buffer.from([oidSequence.length + bitString.length]), + oidSequence, + bitString, + ]); + return der; + }, +}; +const isHex = (key) => /^[0-9a-fA-F]+$/.test(key); diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/oid.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/oid.d.ts new file mode 100644 index 0000000..f20456a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/oid.d.ts @@ -0,0 +1,2 @@ +/// +export declare function encodeOIDString(oid: string): Buffer; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/oid.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/oid.js new file mode 100644 index 0000000..e1bb7af --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/oid.js @@ -0,0 +1,27 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.encodeOIDString = void 0; +const ANS1_TAG_OID = 0x06; +function encodeOIDString(oid) { + const parts = oid.split('.'); + // The first two subidentifiers are encoded into the first byte + const first = parseInt(parts[0], 10) * 40 + parseInt(parts[1], 10); + const rest = []; + parts.slice(2).forEach((part) => { + const bytes = encodeVariableLengthInteger(parseInt(part, 10)); + rest.push(...bytes); + }); + const der = Buffer.from([first, ...rest]); + return Buffer.from([ANS1_TAG_OID, der.length, ...der]); +} +exports.encodeOIDString = encodeOIDString; +function encodeVariableLengthInteger(value) { + const bytes = []; + let mask = 0x00; + while (value > 0) { + bytes.unshift((value & 0x7f) | mask); + value >>= 7; + mask = 0x80; + } + return bytes; +} diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/signer.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/signer.d.ts new file mode 100644 index 0000000..376ef11 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/signer.d.ts @@ -0,0 +1,3 @@ +import crypto from 'crypto'; +import { JSONObject } from '../utils/types'; +export declare const verifySignature: (metaDataSignedData: JSONObject, key: crypto.VerifyKeyObjectInput, signature: string) => boolean; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/signer.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/signer.js new file mode 100644 index 0000000..d3b2e75 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/signer.js @@ -0,0 +1,13 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.verifySignature = void 0; +const crypto_1 = __importDefault(require("crypto")); +const json_1 = require("./json"); +const verifySignature = (metaDataSignedData, key, signature) => { + const canonicalData = (0, json_1.canonicalize)(metaDataSignedData) || ''; + return crypto_1.default.verify(undefined, canonicalData, key, Buffer.from(signature, 'hex')); +}; +exports.verifySignature = verifySignature; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/tmpfile.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/tmpfile.d.ts new file mode 100644 index 0000000..4d5ee8a --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/tmpfile.d.ts @@ -0,0 +1,3 @@ +type TempFileHandler = (file: string) => Promise; +export declare const withTempFile: (handler: TempFileHandler) => Promise; +export {}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/tmpfile.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/tmpfile.js new file mode 100644 index 0000000..923eef6 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/tmpfile.js @@ -0,0 +1,25 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.withTempFile = void 0; +const promises_1 = __importDefault(require("fs/promises")); +const os_1 = __importDefault(require("os")); +const path_1 = __importDefault(require("path")); +// Invokes the given handler with the path to a temporary file. The file +// is deleted after the handler returns. +const withTempFile = async (handler) => withTempDir(async (dir) => handler(path_1.default.join(dir, 'tempfile'))); +exports.withTempFile = withTempFile; +// Invokes the given handler with a temporary directory. The directory is +// deleted after the handler returns. +const withTempDir = async (handler) => { + const tmpDir = await promises_1.default.realpath(os_1.default.tmpdir()); + const dir = await promises_1.default.mkdtemp(tmpDir + path_1.default.sep); + try { + return await handler(dir); + } + finally { + await promises_1.default.rm(dir, { force: true, recursive: true, maxRetries: 3 }); + } +}; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/types.d.ts b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/types.d.ts new file mode 100644 index 0000000..24319dd --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/types.d.ts @@ -0,0 +1,10 @@ +export declare enum MetadataKind { + Root = "root", + Timestamp = "timestamp", + Snapshot = "snapshot", + Targets = "targets" +} +export type JSONObject = { + [key: string]: JSONValue; +}; +export type JSONValue = null | boolean | number | string | JSONValue[] | JSONObject; diff --git a/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/types.js b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/types.js new file mode 100644 index 0000000..469f580 --- /dev/null +++ b/software/flow/node_modules/npm/node_modules/tuf-js/dist/utils/types.js @@ -0,0 +1,10 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MetadataKind = void 0; +var MetadataKind; +(function (MetadataKind) { + MetadataKind["Root"] = "root"; + MetadataKind["Timestamp"] = "timestamp"; + MetadataKind["Snapshot"] = "snapshot"; + MetadataKind["Targets"] = "targets"; +})(MetadataKind = exports.MetadataKind || (exports.MetadataKind = {})); diff --git a/software/flow/node_modules/socket.io-adapter/dist/contrib/yeast.d.ts b/software/flow/node_modules/socket.io-adapter/dist/contrib/yeast.d.ts new file mode 100644 index 0000000..29b5b45 --- /dev/null +++ b/software/flow/node_modules/socket.io-adapter/dist/contrib/yeast.d.ts @@ -0,0 +1,23 @@ +/** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ +export declare function encode(num: any): string; +/** + * Return the integer value specified by the given string. + * + * @param {String} str The string to convert. + * @returns {Number} The integer value represented by the string. + * @api public + */ +export declare function decode(str: any): number; +/** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ +export declare function yeast(): string; diff --git a/software/flow/node_modules/socket.io-adapter/dist/contrib/yeast.js b/software/flow/node_modules/socket.io-adapter/dist/contrib/yeast.js new file mode 100644 index 0000000..490b158 --- /dev/null +++ b/software/flow/node_modules/socket.io-adapter/dist/contrib/yeast.js @@ -0,0 +1,55 @@ +// imported from https://github.com/unshiftio/yeast +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.yeast = exports.decode = exports.encode = void 0; +const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""), length = 64, map = {}; +let seed = 0, i = 0, prev; +/** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ +function encode(num) { + let encoded = ""; + do { + encoded = alphabet[num % length] + encoded; + num = Math.floor(num / length); + } while (num > 0); + return encoded; +} +exports.encode = encode; +/** + * Return the integer value specified by the given string. + * + * @param {String} str The string to convert. + * @returns {Number} The integer value represented by the string. + * @api public + */ +function decode(str) { + let decoded = 0; + for (i = 0; i < str.length; i++) { + decoded = decoded * length + map[str.charAt(i)]; + } + return decoded; +} +exports.decode = decode; +/** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ +function yeast() { + const now = encode(+new Date()); + if (now !== prev) + return (seed = 0), (prev = now); + return now + "." + encode(seed++); +} +exports.yeast = yeast; +// +// Map each character to its index. +// +for (; i < length; i++) + map[alphabet[i]] = i; diff --git a/software/flow/node_modules/socket.io-adapter/dist/index.d.ts b/software/flow/node_modules/socket.io-adapter/dist/index.d.ts new file mode 100644 index 0000000..efed031 --- /dev/null +++ b/software/flow/node_modules/socket.io-adapter/dist/index.d.ts @@ -0,0 +1,179 @@ +/// +import { EventEmitter } from "events"; +/** + * A public ID, sent by the server at the beginning of the Socket.IO session and which can be used for private messaging + */ +export type SocketId = string; +/** + * A private ID, sent by the server at the beginning of the Socket.IO session and used for connection state recovery + * upon reconnection + */ +export type PrivateSessionId = string; +export type Room = string; +export interface BroadcastFlags { + volatile?: boolean; + compress?: boolean; + local?: boolean; + broadcast?: boolean; + binary?: boolean; + timeout?: number; +} +export interface BroadcastOptions { + rooms: Set; + except?: Set; + flags?: BroadcastFlags; +} +interface SessionToPersist { + sid: SocketId; + pid: PrivateSessionId; + rooms: Room[]; + data: unknown; +} +export type Session = SessionToPersist & { + missedPackets: unknown[][]; +}; +export declare class Adapter extends EventEmitter { + readonly nsp: any; + rooms: Map>; + sids: Map>; + private readonly encoder; + /** + * In-memory adapter constructor. + * + * @param {Namespace} nsp + */ + constructor(nsp: any); + /** + * To be overridden + */ + init(): Promise | void; + /** + * To be overridden + */ + close(): Promise | void; + /** + * Returns the number of Socket.IO servers in the cluster + * + * @public + */ + serverCount(): Promise; + /** + * Adds a socket to a list of room. + * + * @param {SocketId} id the socket id + * @param {Set} rooms a set of rooms + * @public + */ + addAll(id: SocketId, rooms: Set): Promise | void; + /** + * Removes a socket from a room. + * + * @param {SocketId} id the socket id + * @param {Room} room the room name + */ + del(id: SocketId, room: Room): Promise | void; + private _del; + /** + * Removes a socket from all rooms it's joined. + * + * @param {SocketId} id the socket id + */ + delAll(id: SocketId): void; + /** + * Broadcasts a packet. + * + * Options: + * - `flags` {Object} flags for this packet + * - `except` {Array} sids that should be excluded + * - `rooms` {Array} list of rooms to broadcast to + * + * @param {Object} packet the packet object + * @param {Object} opts the options + * @public + */ + broadcast(packet: any, opts: BroadcastOptions): void; + /** + * Broadcasts a packet and expects multiple acknowledgements. + * + * Options: + * - `flags` {Object} flags for this packet + * - `except` {Array} sids that should be excluded + * - `rooms` {Array} list of rooms to broadcast to + * + * @param {Object} packet the packet object + * @param {Object} opts the options + * @param clientCountCallback - the number of clients that received the packet + * @param ack - the callback that will be called for each client response + * + * @public + */ + broadcastWithAck(packet: any, opts: BroadcastOptions, clientCountCallback: (clientCount: number) => void, ack: (...args: any[]) => void): void; + private _encode; + /** + * Gets a list of sockets by sid. + * + * @param {Set} rooms the explicit set of rooms to check. + */ + sockets(rooms: Set): Promise>; + /** + * Gets the list of rooms a given socket has joined. + * + * @param {SocketId} id the socket id + */ + socketRooms(id: SocketId): Set | undefined; + /** + * Returns the matching socket instances + * + * @param opts - the filters to apply + */ + fetchSockets(opts: BroadcastOptions): Promise; + /** + * Makes the matching socket instances join the specified rooms + * + * @param opts - the filters to apply + * @param rooms - the rooms to join + */ + addSockets(opts: BroadcastOptions, rooms: Room[]): void; + /** + * Makes the matching socket instances leave the specified rooms + * + * @param opts - the filters to apply + * @param rooms - the rooms to leave + */ + delSockets(opts: BroadcastOptions, rooms: Room[]): void; + /** + * Makes the matching socket instances disconnect + * + * @param opts - the filters to apply + * @param close - whether to close the underlying connection + */ + disconnectSockets(opts: BroadcastOptions, close: boolean): void; + private apply; + private computeExceptSids; + /** + * Send a packet to the other Socket.IO servers in the cluster + * @param packet - an array of arguments, which may include an acknowledgement callback at the end + */ + serverSideEmit(packet: any[]): void; + /** + * Save the client session in order to restore it upon reconnection. + */ + persistSession(session: SessionToPersist): void; + /** + * Restore the session and find the packets that were missed by the client. + * @param pid + * @param offset + */ + restoreSession(pid: PrivateSessionId, offset: string): Promise; +} +export declare class SessionAwareAdapter extends Adapter { + readonly nsp: any; + private readonly maxDisconnectionDuration; + private sessions; + private packets; + constructor(nsp: any); + persistSession(session: SessionToPersist): void; + restoreSession(pid: PrivateSessionId, offset: string): Promise; + broadcast(packet: any, opts: BroadcastOptions): void; +} +export {}; diff --git a/software/flow/node_modules/socket.io-adapter/dist/index.js b/software/flow/node_modules/socket.io-adapter/dist/index.js new file mode 100644 index 0000000..1bfabf6 --- /dev/null +++ b/software/flow/node_modules/socket.io-adapter/dist/index.js @@ -0,0 +1,394 @@ +"use strict"; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SessionAwareAdapter = exports.Adapter = void 0; +const events_1 = require("events"); +const yeast_1 = require("./contrib/yeast"); +const WebSocket = require("ws"); +const canPreComputeFrame = typeof ((_a = WebSocket === null || WebSocket === void 0 ? void 0 : WebSocket.Sender) === null || _a === void 0 ? void 0 : _a.frame) === "function"; +class Adapter extends events_1.EventEmitter { + /** + * In-memory adapter constructor. + * + * @param {Namespace} nsp + */ + constructor(nsp) { + super(); + this.nsp = nsp; + this.rooms = new Map(); + this.sids = new Map(); + this.encoder = nsp.server.encoder; + } + /** + * To be overridden + */ + init() { } + /** + * To be overridden + */ + close() { } + /** + * Returns the number of Socket.IO servers in the cluster + * + * @public + */ + serverCount() { + return Promise.resolve(1); + } + /** + * Adds a socket to a list of room. + * + * @param {SocketId} id the socket id + * @param {Set} rooms a set of rooms + * @public + */ + addAll(id, rooms) { + if (!this.sids.has(id)) { + this.sids.set(id, new Set()); + } + for (const room of rooms) { + this.sids.get(id).add(room); + if (!this.rooms.has(room)) { + this.rooms.set(room, new Set()); + this.emit("create-room", room); + } + if (!this.rooms.get(room).has(id)) { + this.rooms.get(room).add(id); + this.emit("join-room", room, id); + } + } + } + /** + * Removes a socket from a room. + * + * @param {SocketId} id the socket id + * @param {Room} room the room name + */ + del(id, room) { + if (this.sids.has(id)) { + this.sids.get(id).delete(room); + } + this._del(room, id); + } + _del(room, id) { + const _room = this.rooms.get(room); + if (_room != null) { + const deleted = _room.delete(id); + if (deleted) { + this.emit("leave-room", room, id); + } + if (_room.size === 0 && this.rooms.delete(room)) { + this.emit("delete-room", room); + } + } + } + /** + * Removes a socket from all rooms it's joined. + * + * @param {SocketId} id the socket id + */ + delAll(id) { + if (!this.sids.has(id)) { + return; + } + for (const room of this.sids.get(id)) { + this._del(room, id); + } + this.sids.delete(id); + } + /** + * Broadcasts a packet. + * + * Options: + * - `flags` {Object} flags for this packet + * - `except` {Array} sids that should be excluded + * - `rooms` {Array} list of rooms to broadcast to + * + * @param {Object} packet the packet object + * @param {Object} opts the options + * @public + */ + broadcast(packet, opts) { + const flags = opts.flags || {}; + const packetOpts = { + preEncoded: true, + volatile: flags.volatile, + compress: flags.compress, + }; + packet.nsp = this.nsp.name; + const encodedPackets = this._encode(packet, packetOpts); + this.apply(opts, (socket) => { + if (typeof socket.notifyOutgoingListeners === "function") { + socket.notifyOutgoingListeners(packet); + } + socket.client.writeToEngine(encodedPackets, packetOpts); + }); + } + /** + * Broadcasts a packet and expects multiple acknowledgements. + * + * Options: + * - `flags` {Object} flags for this packet + * - `except` {Array} sids that should be excluded + * - `rooms` {Array} list of rooms to broadcast to + * + * @param {Object} packet the packet object + * @param {Object} opts the options + * @param clientCountCallback - the number of clients that received the packet + * @param ack - the callback that will be called for each client response + * + * @public + */ + broadcastWithAck(packet, opts, clientCountCallback, ack) { + const flags = opts.flags || {}; + const packetOpts = { + preEncoded: true, + volatile: flags.volatile, + compress: flags.compress, + }; + packet.nsp = this.nsp.name; + // we can use the same id for each packet, since the _ids counter is common (no duplicate) + packet.id = this.nsp._ids++; + const encodedPackets = this._encode(packet, packetOpts); + let clientCount = 0; + this.apply(opts, (socket) => { + // track the total number of acknowledgements that are expected + clientCount++; + // call the ack callback for each client response + socket.acks.set(packet.id, ack); + if (typeof socket.notifyOutgoingListeners === "function") { + socket.notifyOutgoingListeners(packet); + } + socket.client.writeToEngine(encodedPackets, packetOpts); + }); + clientCountCallback(clientCount); + } + _encode(packet, packetOpts) { + const encodedPackets = this.encoder.encode(packet); + if (canPreComputeFrame && + encodedPackets.length === 1 && + typeof encodedPackets[0] === "string") { + // "4" being the "message" packet type in the Engine.IO protocol + const data = Buffer.from("4" + encodedPackets[0]); + // see https://github.com/websockets/ws/issues/617#issuecomment-283002469 + packetOpts.wsPreEncodedFrame = WebSocket.Sender.frame(data, { + readOnly: false, + mask: false, + rsv1: false, + opcode: 1, + fin: true, + }); + } + return encodedPackets; + } + /** + * Gets a list of sockets by sid. + * + * @param {Set} rooms the explicit set of rooms to check. + */ + sockets(rooms) { + const sids = new Set(); + this.apply({ rooms }, (socket) => { + sids.add(socket.id); + }); + return Promise.resolve(sids); + } + /** + * Gets the list of rooms a given socket has joined. + * + * @param {SocketId} id the socket id + */ + socketRooms(id) { + return this.sids.get(id); + } + /** + * Returns the matching socket instances + * + * @param opts - the filters to apply + */ + fetchSockets(opts) { + const sockets = []; + this.apply(opts, (socket) => { + sockets.push(socket); + }); + return Promise.resolve(sockets); + } + /** + * Makes the matching socket instances join the specified rooms + * + * @param opts - the filters to apply + * @param rooms - the rooms to join + */ + addSockets(opts, rooms) { + this.apply(opts, (socket) => { + socket.join(rooms); + }); + } + /** + * Makes the matching socket instances leave the specified rooms + * + * @param opts - the filters to apply + * @param rooms - the rooms to leave + */ + delSockets(opts, rooms) { + this.apply(opts, (socket) => { + rooms.forEach((room) => socket.leave(room)); + }); + } + /** + * Makes the matching socket instances disconnect + * + * @param opts - the filters to apply + * @param close - whether to close the underlying connection + */ + disconnectSockets(opts, close) { + this.apply(opts, (socket) => { + socket.disconnect(close); + }); + } + apply(opts, callback) { + const rooms = opts.rooms; + const except = this.computeExceptSids(opts.except); + if (rooms.size) { + const ids = new Set(); + for (const room of rooms) { + if (!this.rooms.has(room)) + continue; + for (const id of this.rooms.get(room)) { + if (ids.has(id) || except.has(id)) + continue; + const socket = this.nsp.sockets.get(id); + if (socket) { + callback(socket); + ids.add(id); + } + } + } + } + else { + for (const [id] of this.sids) { + if (except.has(id)) + continue; + const socket = this.nsp.sockets.get(id); + if (socket) + callback(socket); + } + } + } + computeExceptSids(exceptRooms) { + const exceptSids = new Set(); + if (exceptRooms && exceptRooms.size > 0) { + for (const room of exceptRooms) { + if (this.rooms.has(room)) { + this.rooms.get(room).forEach((sid) => exceptSids.add(sid)); + } + } + } + return exceptSids; + } + /** + * Send a packet to the other Socket.IO servers in the cluster + * @param packet - an array of arguments, which may include an acknowledgement callback at the end + */ + serverSideEmit(packet) { + console.warn("this adapter does not support the serverSideEmit() functionality"); + } + /** + * Save the client session in order to restore it upon reconnection. + */ + persistSession(session) { } + /** + * Restore the session and find the packets that were missed by the client. + * @param pid + * @param offset + */ + restoreSession(pid, offset) { + return null; + } +} +exports.Adapter = Adapter; +class SessionAwareAdapter extends Adapter { + constructor(nsp) { + super(nsp); + this.nsp = nsp; + this.sessions = new Map(); + this.packets = []; + this.maxDisconnectionDuration = + nsp.server.opts.connectionStateRecovery.maxDisconnectionDuration; + const timer = setInterval(() => { + const threshold = Date.now() - this.maxDisconnectionDuration; + this.sessions.forEach((session, sessionId) => { + const hasExpired = session.disconnectedAt < threshold; + if (hasExpired) { + this.sessions.delete(sessionId); + } + }); + for (let i = this.packets.length - 1; i >= 0; i--) { + const hasExpired = this.packets[i].emittedAt < threshold; + if (hasExpired) { + this.packets.splice(0, i + 1); + break; + } + } + }, 60 * 1000); + // prevents the timer from keeping the process alive + timer.unref(); + } + persistSession(session) { + session.disconnectedAt = Date.now(); + this.sessions.set(session.pid, session); + } + restoreSession(pid, offset) { + const session = this.sessions.get(pid); + if (!session) { + // the session may have expired + return null; + } + const hasExpired = session.disconnectedAt + this.maxDisconnectionDuration < Date.now(); + if (hasExpired) { + // the session has expired + this.sessions.delete(pid); + return null; + } + const index = this.packets.findIndex((packet) => packet.id === offset); + if (index === -1) { + // the offset may be too old + return null; + } + const missedPackets = []; + for (let i = index + 1; i < this.packets.length; i++) { + const packet = this.packets[i]; + if (shouldIncludePacket(session.rooms, packet.opts)) { + missedPackets.push(packet.data); + } + } + return Promise.resolve(Object.assign(Object.assign({}, session), { missedPackets })); + } + broadcast(packet, opts) { + var _a; + const isEventPacket = packet.type === 2; + // packets with acknowledgement are not stored because the acknowledgement function cannot be serialized and + // restored on another server upon reconnection + const withoutAcknowledgement = packet.id === undefined; + const notVolatile = ((_a = opts.flags) === null || _a === void 0 ? void 0 : _a.volatile) === undefined; + if (isEventPacket && withoutAcknowledgement && notVolatile) { + const id = (0, yeast_1.yeast)(); + // the offset is stored at the end of the data array, so the client knows the ID of the last packet it has + // processed (and the format is backward-compatible) + packet.data.push(id); + this.packets.push({ + id, + opts, + data: packet.data, + emittedAt: Date.now(), + }); + } + super.broadcast(packet, opts); + } +} +exports.SessionAwareAdapter = SessionAwareAdapter; +function shouldIncludePacket(sessionRooms, opts) { + const included = opts.rooms.size === 0 || sessionRooms.some((room) => opts.rooms.has(room)); + const notExcluded = sessionRooms.every((room) => !opts.except.has(room)); + return included && notExcluded; +} diff --git a/software/flow/node_modules/socket.io/dist/broadcast-operator.d.ts b/software/flow/node_modules/socket.io/dist/broadcast-operator.d.ts new file mode 100644 index 0000000..b3f9e32 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/broadcast-operator.d.ts @@ -0,0 +1,283 @@ +import type { BroadcastFlags, Room, SocketId } from "socket.io-adapter"; +import { Handshake } from "./socket"; +import type { Adapter } from "socket.io-adapter"; +import type { EventParams, EventNames, EventsMap, TypedEventBroadcaster, DecorateAcknowledgements, DecorateAcknowledgementsWithTimeoutAndMultipleResponses, AllButLast, Last, SecondArg } from "./typed-events"; +export declare class BroadcastOperator implements TypedEventBroadcaster { + private readonly adapter; + private readonly rooms; + private readonly exceptRooms; + private readonly flags; + constructor(adapter: Adapter, rooms?: Set, exceptRooms?: Set, flags?: BroadcastFlags & { + expectSingleResponse?: boolean; + }); + /** + * Targets a room when emitting. + * + * @example + * // the “foo” event will be broadcast to all connected clients in the “room-101” room + * io.to("room-101").emit("foo", "bar"); + * + * // with an array of rooms (a client will be notified at most once) + * io.to(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * io.to("room-101").to("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + to(room: Room | Room[]): BroadcastOperator; + /** + * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases: + * + * @example + * // disconnect all clients in the "room-101" room + * io.in("room-101").disconnectSockets(); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + in(room: Room | Room[]): BroadcastOperator; + /** + * Excludes a room when emitting. + * + * @example + * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room + * io.except("room-101").emit("foo", "bar"); + * + * // with an array of rooms + * io.except(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * io.except("room-101").except("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + except(room: Room | Room[]): BroadcastOperator; + /** + * Sets the compress flag. + * + * @example + * io.compress(false).emit("hello"); + * + * @param compress - if `true`, compresses the sending data + * @return a new BroadcastOperator instance + */ + compress(compress: boolean): BroadcastOperator; + /** + * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to + * receive messages (because of network slowness or other issues, or because they’re connected through long polling + * and is in the middle of a request-response cycle). + * + * @example + * io.volatile.emit("hello"); // the clients may or may not receive it + * + * @return a new BroadcastOperator instance + */ + get volatile(): BroadcastOperator; + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node. + * + * @example + * // the “foo” event will be broadcast to all connected clients on this node + * io.local.emit("foo", "bar"); + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get local(): BroadcastOperator; + /** + * Adds a timeout in milliseconds for the next operation + * + * @example + * io.timeout(1000).emit("some-event", (err, responses) => { + * if (err) { + * // some clients did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per client + * } + * }); + * + * @param timeout + */ + timeout(timeout: number): BroadcastOperator, SocketData>; + /** + * Emits to all clients. + * + * @example + * // the “foo” event will be broadcast to all connected clients + * io.emit("foo", "bar"); + * + * // the “foo” event will be broadcast to all connected clients in the “room-101” room + * io.to("room-101").emit("foo", "bar"); + * + * // with an acknowledgement expected from all connected clients + * io.timeout(1000).emit("some-event", (err, responses) => { + * if (err) { + * // some clients did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per client + * } + * }); + * + * @return Always true + */ + emit>(ev: Ev, ...args: EventParams): boolean; + /** + * Emits an event and waits for an acknowledgement from all clients. + * + * @example + * try { + * const responses = await io.timeout(1000).emitWithAck("some-event"); + * console.log(responses); // one response per client + * } catch (e) { + * // some clients did not acknowledge the event in the given delay + * } + * + * @return a Promise that will be fulfilled when all clients have acknowledged the event + */ + emitWithAck>(ev: Ev, ...args: AllButLast>): Promise>>>; + /** + * Gets a list of clients. + * + * @deprecated this method will be removed in the next major release, please use {@link Server#serverSideEmit} or + * {@link fetchSockets} instead. + */ + allSockets(): Promise>; + /** + * Returns the matching socket instances. This method works across a cluster of several Socket.IO servers. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // return all Socket instances + * const sockets = await io.fetchSockets(); + * + * // return all Socket instances in the "room1" room + * const sockets = await io.in("room1").fetchSockets(); + * + * for (const socket of sockets) { + * console.log(socket.id); + * console.log(socket.handshake); + * console.log(socket.rooms); + * console.log(socket.data); + * + * socket.emit("hello"); + * socket.join("room1"); + * socket.leave("room2"); + * socket.disconnect(); + * } + */ + fetchSockets(): Promise[]>; + /** + * Makes the matching socket instances join the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * + * // make all socket instances join the "room1" room + * io.socketsJoin("room1"); + * + * // make all socket instances in the "room1" room join the "room2" and "room3" rooms + * io.in("room1").socketsJoin(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsJoin(room: Room | Room[]): void; + /** + * Makes the matching socket instances leave the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // make all socket instances leave the "room1" room + * io.socketsLeave("room1"); + * + * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms + * io.in("room1").socketsLeave(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsLeave(room: Room | Room[]): void; + /** + * Makes the matching socket instances disconnect. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // make all socket instances disconnect (the connections might be kept alive for other namespaces) + * io.disconnectSockets(); + * + * // make all socket instances in the "room1" room disconnect and close the underlying connections + * io.in("room1").disconnectSockets(true); + * + * @param close - whether to close the underlying connection + */ + disconnectSockets(close?: boolean): void; +} +/** + * Format of the data when the Socket instance exists on another Socket.IO server + */ +interface SocketDetails { + id: SocketId; + handshake: Handshake; + rooms: Room[]; + data: SocketData; +} +/** + * Expose of subset of the attributes and methods of the Socket class + */ +export declare class RemoteSocket implements TypedEventBroadcaster { + readonly id: SocketId; + readonly handshake: Handshake; + readonly rooms: Set; + readonly data: SocketData; + private readonly operator; + constructor(adapter: Adapter, details: SocketDetails); + /** + * Adds a timeout in milliseconds for the next operation. + * + * @example + * const sockets = await io.fetchSockets(); + * + * for (const socket of sockets) { + * if (someCondition) { + * socket.timeout(1000).emit("some-event", (err) => { + * if (err) { + * // the client did not acknowledge the event in the given delay + * } + * }); + * } + * } + * + * // note: if possible, using a room instead of looping over all sockets is preferable + * io.timeout(1000).to(someConditionRoom).emit("some-event", (err, responses) => { + * // ... + * }); + * + * @param timeout + */ + timeout(timeout: number): BroadcastOperator, SocketData>; + emit>(ev: Ev, ...args: EventParams): boolean; + /** + * Joins a room. + * + * @param {String|Array} room - room or array of rooms + */ + join(room: Room | Room[]): void; + /** + * Leaves a room. + * + * @param {String} room + */ + leave(room: Room): void; + /** + * Disconnects this client. + * + * @param {Boolean} close - if `true`, closes the underlying connection + * @return {Socket} self + */ + disconnect(close?: boolean): this; +} +export {}; diff --git a/software/flow/node_modules/socket.io/dist/broadcast-operator.js b/software/flow/node_modules/socket.io/dist/broadcast-operator.js new file mode 100644 index 0000000..a7314cb --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/broadcast-operator.js @@ -0,0 +1,437 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RemoteSocket = exports.BroadcastOperator = void 0; +const socket_1 = require("./socket"); +const socket_io_parser_1 = require("socket.io-parser"); +class BroadcastOperator { + constructor(adapter, rooms = new Set(), exceptRooms = new Set(), flags = {}) { + this.adapter = adapter; + this.rooms = rooms; + this.exceptRooms = exceptRooms; + this.flags = flags; + } + /** + * Targets a room when emitting. + * + * @example + * // the “foo” event will be broadcast to all connected clients in the “room-101” room + * io.to("room-101").emit("foo", "bar"); + * + * // with an array of rooms (a client will be notified at most once) + * io.to(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * io.to("room-101").to("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + to(room) { + const rooms = new Set(this.rooms); + if (Array.isArray(room)) { + room.forEach((r) => rooms.add(r)); + } + else { + rooms.add(room); + } + return new BroadcastOperator(this.adapter, rooms, this.exceptRooms, this.flags); + } + /** + * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases: + * + * @example + * // disconnect all clients in the "room-101" room + * io.in("room-101").disconnectSockets(); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + in(room) { + return this.to(room); + } + /** + * Excludes a room when emitting. + * + * @example + * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room + * io.except("room-101").emit("foo", "bar"); + * + * // with an array of rooms + * io.except(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * io.except("room-101").except("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + except(room) { + const exceptRooms = new Set(this.exceptRooms); + if (Array.isArray(room)) { + room.forEach((r) => exceptRooms.add(r)); + } + else { + exceptRooms.add(room); + } + return new BroadcastOperator(this.adapter, this.rooms, exceptRooms, this.flags); + } + /** + * Sets the compress flag. + * + * @example + * io.compress(false).emit("hello"); + * + * @param compress - if `true`, compresses the sending data + * @return a new BroadcastOperator instance + */ + compress(compress) { + const flags = Object.assign({}, this.flags, { compress }); + return new BroadcastOperator(this.adapter, this.rooms, this.exceptRooms, flags); + } + /** + * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to + * receive messages (because of network slowness or other issues, or because they’re connected through long polling + * and is in the middle of a request-response cycle). + * + * @example + * io.volatile.emit("hello"); // the clients may or may not receive it + * + * @return a new BroadcastOperator instance + */ + get volatile() { + const flags = Object.assign({}, this.flags, { volatile: true }); + return new BroadcastOperator(this.adapter, this.rooms, this.exceptRooms, flags); + } + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node. + * + * @example + * // the “foo” event will be broadcast to all connected clients on this node + * io.local.emit("foo", "bar"); + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get local() { + const flags = Object.assign({}, this.flags, { local: true }); + return new BroadcastOperator(this.adapter, this.rooms, this.exceptRooms, flags); + } + /** + * Adds a timeout in milliseconds for the next operation + * + * @example + * io.timeout(1000).emit("some-event", (err, responses) => { + * if (err) { + * // some clients did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per client + * } + * }); + * + * @param timeout + */ + timeout(timeout) { + const flags = Object.assign({}, this.flags, { timeout }); + return new BroadcastOperator(this.adapter, this.rooms, this.exceptRooms, flags); + } + /** + * Emits to all clients. + * + * @example + * // the “foo” event will be broadcast to all connected clients + * io.emit("foo", "bar"); + * + * // the “foo” event will be broadcast to all connected clients in the “room-101” room + * io.to("room-101").emit("foo", "bar"); + * + * // with an acknowledgement expected from all connected clients + * io.timeout(1000).emit("some-event", (err, responses) => { + * if (err) { + * // some clients did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per client + * } + * }); + * + * @return Always true + */ + emit(ev, ...args) { + if (socket_1.RESERVED_EVENTS.has(ev)) { + throw new Error(`"${String(ev)}" is a reserved event name`); + } + // set up packet object + const data = [ev, ...args]; + const packet = { + type: socket_io_parser_1.PacketType.EVENT, + data: data, + }; + const withAck = typeof data[data.length - 1] === "function"; + if (!withAck) { + this.adapter.broadcast(packet, { + rooms: this.rooms, + except: this.exceptRooms, + flags: this.flags, + }); + return true; + } + const ack = data.pop(); + let timedOut = false; + let responses = []; + const timer = setTimeout(() => { + timedOut = true; + ack.apply(this, [ + new Error("operation has timed out"), + this.flags.expectSingleResponse ? null : responses, + ]); + }, this.flags.timeout); + let expectedServerCount = -1; + let actualServerCount = 0; + let expectedClientCount = 0; + const checkCompleteness = () => { + if (!timedOut && + expectedServerCount === actualServerCount && + responses.length === expectedClientCount) { + clearTimeout(timer); + ack.apply(this, [ + null, + this.flags.expectSingleResponse ? null : responses, + ]); + } + }; + this.adapter.broadcastWithAck(packet, { + rooms: this.rooms, + except: this.exceptRooms, + flags: this.flags, + }, (clientCount) => { + // each Socket.IO server in the cluster sends the number of clients that were notified + expectedClientCount += clientCount; + actualServerCount++; + checkCompleteness(); + }, (clientResponse) => { + // each client sends an acknowledgement + responses.push(clientResponse); + checkCompleteness(); + }); + this.adapter.serverCount().then((serverCount) => { + expectedServerCount = serverCount; + checkCompleteness(); + }); + return true; + } + /** + * Emits an event and waits for an acknowledgement from all clients. + * + * @example + * try { + * const responses = await io.timeout(1000).emitWithAck("some-event"); + * console.log(responses); // one response per client + * } catch (e) { + * // some clients did not acknowledge the event in the given delay + * } + * + * @return a Promise that will be fulfilled when all clients have acknowledged the event + */ + emitWithAck(ev, ...args) { + return new Promise((resolve, reject) => { + args.push((err, responses) => { + if (err) { + err.responses = responses; + return reject(err); + } + else { + return resolve(responses); + } + }); + this.emit(ev, ...args); + }); + } + /** + * Gets a list of clients. + * + * @deprecated this method will be removed in the next major release, please use {@link Server#serverSideEmit} or + * {@link fetchSockets} instead. + */ + allSockets() { + if (!this.adapter) { + throw new Error("No adapter for this namespace, are you trying to get the list of clients of a dynamic namespace?"); + } + return this.adapter.sockets(this.rooms); + } + /** + * Returns the matching socket instances. This method works across a cluster of several Socket.IO servers. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // return all Socket instances + * const sockets = await io.fetchSockets(); + * + * // return all Socket instances in the "room1" room + * const sockets = await io.in("room1").fetchSockets(); + * + * for (const socket of sockets) { + * console.log(socket.id); + * console.log(socket.handshake); + * console.log(socket.rooms); + * console.log(socket.data); + * + * socket.emit("hello"); + * socket.join("room1"); + * socket.leave("room2"); + * socket.disconnect(); + * } + */ + fetchSockets() { + return this.adapter + .fetchSockets({ + rooms: this.rooms, + except: this.exceptRooms, + flags: this.flags, + }) + .then((sockets) => { + return sockets.map((socket) => { + if (socket instanceof socket_1.Socket) { + // FIXME the TypeScript compiler complains about missing private properties + return socket; + } + else { + return new RemoteSocket(this.adapter, socket); + } + }); + }); + } + /** + * Makes the matching socket instances join the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * + * // make all socket instances join the "room1" room + * io.socketsJoin("room1"); + * + * // make all socket instances in the "room1" room join the "room2" and "room3" rooms + * io.in("room1").socketsJoin(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsJoin(room) { + this.adapter.addSockets({ + rooms: this.rooms, + except: this.exceptRooms, + flags: this.flags, + }, Array.isArray(room) ? room : [room]); + } + /** + * Makes the matching socket instances leave the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // make all socket instances leave the "room1" room + * io.socketsLeave("room1"); + * + * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms + * io.in("room1").socketsLeave(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsLeave(room) { + this.adapter.delSockets({ + rooms: this.rooms, + except: this.exceptRooms, + flags: this.flags, + }, Array.isArray(room) ? room : [room]); + } + /** + * Makes the matching socket instances disconnect. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // make all socket instances disconnect (the connections might be kept alive for other namespaces) + * io.disconnectSockets(); + * + * // make all socket instances in the "room1" room disconnect and close the underlying connections + * io.in("room1").disconnectSockets(true); + * + * @param close - whether to close the underlying connection + */ + disconnectSockets(close = false) { + this.adapter.disconnectSockets({ + rooms: this.rooms, + except: this.exceptRooms, + flags: this.flags, + }, close); + } +} +exports.BroadcastOperator = BroadcastOperator; +/** + * Expose of subset of the attributes and methods of the Socket class + */ +class RemoteSocket { + constructor(adapter, details) { + this.id = details.id; + this.handshake = details.handshake; + this.rooms = new Set(details.rooms); + this.data = details.data; + this.operator = new BroadcastOperator(adapter, new Set([this.id]), new Set(), { + expectSingleResponse: true, // so that remoteSocket.emit() with acknowledgement behaves like socket.emit() + }); + } + /** + * Adds a timeout in milliseconds for the next operation. + * + * @example + * const sockets = await io.fetchSockets(); + * + * for (const socket of sockets) { + * if (someCondition) { + * socket.timeout(1000).emit("some-event", (err) => { + * if (err) { + * // the client did not acknowledge the event in the given delay + * } + * }); + * } + * } + * + * // note: if possible, using a room instead of looping over all sockets is preferable + * io.timeout(1000).to(someConditionRoom).emit("some-event", (err, responses) => { + * // ... + * }); + * + * @param timeout + */ + timeout(timeout) { + return this.operator.timeout(timeout); + } + emit(ev, ...args) { + return this.operator.emit(ev, ...args); + } + /** + * Joins a room. + * + * @param {String|Array} room - room or array of rooms + */ + join(room) { + return this.operator.socketsJoin(room); + } + /** + * Leaves a room. + * + * @param {String} room + */ + leave(room) { + return this.operator.socketsLeave(room); + } + /** + * Disconnects this client. + * + * @param {Boolean} close - if `true`, closes the underlying connection + * @return {Socket} self + */ + disconnect(close = false) { + this.operator.disconnectSockets(close); + return this; + } +} +exports.RemoteSocket = RemoteSocket; diff --git a/software/flow/node_modules/socket.io/dist/client.d.ts b/software/flow/node_modules/socket.io/dist/client.d.ts new file mode 100644 index 0000000..fe67228 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/client.d.ts @@ -0,0 +1,120 @@ +/// +import { Packet } from "socket.io-parser"; +import type { IncomingMessage } from "http"; +import type { Server } from "./index"; +import type { EventsMap } from "./typed-events"; +import type { Socket } from "./socket"; +import type { Socket as RawSocket } from "engine.io"; +interface WriteOptions { + compress?: boolean; + volatile?: boolean; + preEncoded?: boolean; + wsPreEncoded?: string; +} +export declare class Client { + readonly conn: RawSocket; + private readonly id; + private readonly server; + private readonly encoder; + private readonly decoder; + private sockets; + private nsps; + private connectTimeout?; + /** + * Client constructor. + * + * @param server instance + * @param conn + * @package + */ + constructor(server: Server, conn: any); + /** + * @return the reference to the request that originated the Engine.IO connection + * + * @public + */ + get request(): IncomingMessage; + /** + * Sets up event listeners. + * + * @private + */ + private setup; + /** + * Connects a client to a namespace. + * + * @param {String} name - the namespace + * @param {Object} auth - the auth parameters + * @private + */ + private connect; + /** + * Connects a client to a namespace. + * + * @param name - the namespace + * @param {Object} auth - the auth parameters + * + * @private + */ + private doConnect; + /** + * Disconnects from all namespaces and closes transport. + * + * @private + */ + _disconnect(): void; + /** + * Removes a socket. Called by each `Socket`. + * + * @private + */ + _remove(socket: Socket): void; + /** + * Closes the underlying connection. + * + * @private + */ + private close; + /** + * Writes a packet to the transport. + * + * @param {Object} packet object + * @param {Object} opts + * @private + */ + _packet(packet: Packet | any[], opts?: WriteOptions): void; + private writeToEngine; + /** + * Called with incoming transport data. + * + * @private + */ + private ondata; + /** + * Called when parser fully decodes a packet. + * + * @private + */ + private ondecoded; + /** + * Handles an error. + * + * @param {Object} err object + * @private + */ + private onerror; + /** + * Called upon transport close. + * + * @param reason + * @param description + * @private + */ + private onclose; + /** + * Cleans up event listeners. + * @private + */ + private destroy; +} +export {}; diff --git a/software/flow/node_modules/socket.io/dist/client.js b/software/flow/node_modules/socket.io/dist/client.js new file mode 100644 index 0000000..420db45 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/client.js @@ -0,0 +1,268 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Client = void 0; +const socket_io_parser_1 = require("socket.io-parser"); +const debugModule = require("debug"); +const url = require("url"); +const debug = debugModule("socket.io:client"); +class Client { + /** + * Client constructor. + * + * @param server instance + * @param conn + * @package + */ + constructor(server, conn) { + this.sockets = new Map(); + this.nsps = new Map(); + this.server = server; + this.conn = conn; + this.encoder = server.encoder; + this.decoder = new server._parser.Decoder(); + this.id = conn.id; + this.setup(); + } + /** + * @return the reference to the request that originated the Engine.IO connection + * + * @public + */ + get request() { + return this.conn.request; + } + /** + * Sets up event listeners. + * + * @private + */ + setup() { + this.onclose = this.onclose.bind(this); + this.ondata = this.ondata.bind(this); + this.onerror = this.onerror.bind(this); + this.ondecoded = this.ondecoded.bind(this); + // @ts-ignore + this.decoder.on("decoded", this.ondecoded); + this.conn.on("data", this.ondata); + this.conn.on("error", this.onerror); + this.conn.on("close", this.onclose); + this.connectTimeout = setTimeout(() => { + if (this.nsps.size === 0) { + debug("no namespace joined yet, close the client"); + this.close(); + } + else { + debug("the client has already joined a namespace, nothing to do"); + } + }, this.server._connectTimeout); + } + /** + * Connects a client to a namespace. + * + * @param {String} name - the namespace + * @param {Object} auth - the auth parameters + * @private + */ + connect(name, auth = {}) { + if (this.server._nsps.has(name)) { + debug("connecting to namespace %s", name); + return this.doConnect(name, auth); + } + this.server._checkNamespace(name, auth, (dynamicNspName) => { + if (dynamicNspName) { + this.doConnect(name, auth); + } + else { + debug("creation of namespace %s was denied", name); + this._packet({ + type: socket_io_parser_1.PacketType.CONNECT_ERROR, + nsp: name, + data: { + message: "Invalid namespace", + }, + }); + } + }); + } + /** + * Connects a client to a namespace. + * + * @param name - the namespace + * @param {Object} auth - the auth parameters + * + * @private + */ + doConnect(name, auth) { + const nsp = this.server.of(name); + nsp._add(this, auth, (socket) => { + this.sockets.set(socket.id, socket); + this.nsps.set(nsp.name, socket); + if (this.connectTimeout) { + clearTimeout(this.connectTimeout); + this.connectTimeout = undefined; + } + }); + } + /** + * Disconnects from all namespaces and closes transport. + * + * @private + */ + _disconnect() { + for (const socket of this.sockets.values()) { + socket.disconnect(); + } + this.sockets.clear(); + this.close(); + } + /** + * Removes a socket. Called by each `Socket`. + * + * @private + */ + _remove(socket) { + if (this.sockets.has(socket.id)) { + const nsp = this.sockets.get(socket.id).nsp.name; + this.sockets.delete(socket.id); + this.nsps.delete(nsp); + } + else { + debug("ignoring remove for %s", socket.id); + } + } + /** + * Closes the underlying connection. + * + * @private + */ + close() { + if ("open" === this.conn.readyState) { + debug("forcing transport close"); + this.conn.close(); + this.onclose("forced server close"); + } + } + /** + * Writes a packet to the transport. + * + * @param {Object} packet object + * @param {Object} opts + * @private + */ + _packet(packet, opts = {}) { + if (this.conn.readyState !== "open") { + debug("ignoring packet write %j", packet); + return; + } + const encodedPackets = opts.preEncoded + ? packet // previous versions of the adapter incorrectly used socket.packet() instead of writeToEngine() + : this.encoder.encode(packet); + this.writeToEngine(encodedPackets, opts); + } + writeToEngine(encodedPackets, opts) { + if (opts.volatile && !this.conn.transport.writable) { + debug("volatile packet is discarded since the transport is not currently writable"); + return; + } + const packets = Array.isArray(encodedPackets) + ? encodedPackets + : [encodedPackets]; + for (const encodedPacket of packets) { + this.conn.write(encodedPacket, opts); + } + } + /** + * Called with incoming transport data. + * + * @private + */ + ondata(data) { + // try/catch is needed for protocol violations (GH-1880) + try { + this.decoder.add(data); + } + catch (e) { + debug("invalid packet format"); + this.onerror(e); + } + } + /** + * Called when parser fully decodes a packet. + * + * @private + */ + ondecoded(packet) { + let namespace; + let authPayload; + if (this.conn.protocol === 3) { + const parsed = url.parse(packet.nsp, true); + namespace = parsed.pathname; + authPayload = parsed.query; + } + else { + namespace = packet.nsp; + authPayload = packet.data; + } + const socket = this.nsps.get(namespace); + if (!socket && packet.type === socket_io_parser_1.PacketType.CONNECT) { + this.connect(namespace, authPayload); + } + else if (socket && + packet.type !== socket_io_parser_1.PacketType.CONNECT && + packet.type !== socket_io_parser_1.PacketType.CONNECT_ERROR) { + process.nextTick(function () { + socket._onpacket(packet); + }); + } + else { + debug("invalid state (packet type: %s)", packet.type); + this.close(); + } + } + /** + * Handles an error. + * + * @param {Object} err object + * @private + */ + onerror(err) { + for (const socket of this.sockets.values()) { + socket._onerror(err); + } + this.conn.close(); + } + /** + * Called upon transport close. + * + * @param reason + * @param description + * @private + */ + onclose(reason, description) { + debug("client close with reason %s", reason); + // ignore a potential subsequent `close` event + this.destroy(); + // `nsps` and `sockets` are cleaned up seamlessly + for (const socket of this.sockets.values()) { + socket._onclose(reason, description); + } + this.sockets.clear(); + this.decoder.destroy(); // clean up decoder + } + /** + * Cleans up event listeners. + * @private + */ + destroy() { + this.conn.removeListener("data", this.ondata); + this.conn.removeListener("error", this.onerror); + this.conn.removeListener("close", this.onclose); + // @ts-ignore + this.decoder.removeListener("decoded", this.ondecoded); + if (this.connectTimeout) { + clearTimeout(this.connectTimeout); + this.connectTimeout = undefined; + } + } +} +exports.Client = Client; diff --git a/software/flow/node_modules/socket.io/dist/index.d.ts b/software/flow/node_modules/socket.io/dist/index.d.ts new file mode 100644 index 0000000..673cb86 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/index.d.ts @@ -0,0 +1,538 @@ +/// +/// +/// +import http = require("http"); +import type { Server as HTTPSServer } from "https"; +import type { Http2SecureServer } from "http2"; +import type { ServerOptions as EngineOptions, AttachOptions, BaseServer } from "engine.io"; +import { ExtendedError, Namespace, ServerReservedEventsMap } from "./namespace"; +import { Adapter, Room, SocketId } from "socket.io-adapter"; +import * as parser from "socket.io-parser"; +import type { Encoder } from "socket.io-parser"; +import { Socket, DisconnectReason } from "./socket"; +import type { BroadcastOperator, RemoteSocket } from "./broadcast-operator"; +import { EventsMap, DefaultEventsMap, EventParams, StrictEventEmitter, EventNames, DecorateAcknowledgementsWithTimeoutAndMultipleResponses, AllButLast, Last, FirstArg, SecondArg } from "./typed-events"; +declare type ParentNspNameMatchFn = (name: string, auth: { + [key: string]: any; +}, fn: (err: Error | null, success: boolean) => void) => void; +declare type AdapterConstructor = typeof Adapter | ((nsp: Namespace) => Adapter); +interface ServerOptions extends EngineOptions, AttachOptions { + /** + * name of the path to capture + * @default "/socket.io" + */ + path: string; + /** + * whether to serve the client files + * @default true + */ + serveClient: boolean; + /** + * the adapter to use + * @default the in-memory adapter (https://github.com/socketio/socket.io-adapter) + */ + adapter: AdapterConstructor; + /** + * the parser to use + * @default the default parser (https://github.com/socketio/socket.io-parser) + */ + parser: any; + /** + * how many ms before a client without namespace is closed + * @default 45000 + */ + connectTimeout: number; + /** + * Whether to enable the recovery of connection state when a client temporarily disconnects. + * + * The connection state includes the missed packets, the rooms the socket was in and the `data` attribute. + */ + connectionStateRecovery: { + /** + * The backup duration of the sessions and the packets. + * + * @default 120000 (2 minutes) + */ + maxDisconnectionDuration?: number; + /** + * Whether to skip middlewares upon successful connection state recovery. + * + * @default true + */ + skipMiddlewares?: boolean; + }; + /** + * Whether to remove child namespaces that have no sockets connected to them + * @default false + */ + cleanupEmptyChildNamespaces: boolean; +} +/** + * Represents a Socket.IO server. + * + * @example + * import { Server } from "socket.io"; + * + * const io = new Server(); + * + * io.on("connection", (socket) => { + * console.log(`socket ${socket.id} connected`); + * + * // send an event to the client + * socket.emit("foo", "bar"); + * + * socket.on("foobar", () => { + * // an event was received from the client + * }); + * + * // upon disconnection + * socket.on("disconnect", (reason) => { + * console.log(`socket ${socket.id} disconnected due to ${reason}`); + * }); + * }); + * + * io.listen(3000); + */ +export declare class Server extends StrictEventEmitter> { + readonly sockets: Namespace; + /** + * A reference to the underlying Engine.IO server. + * + * @example + * const clientsCount = io.engine.clientsCount; + * + */ + engine: BaseServer; + /** @private */ + readonly _parser: typeof parser; + /** @private */ + readonly encoder: Encoder; + /** + * @private + */ + _nsps: Map>; + private parentNsps; + /** + * A subset of the {@link parentNsps} map, only containing {@link ParentNamespace} which are based on a regular + * expression. + * + * @private + */ + private parentNamespacesFromRegExp; + private _adapter?; + private _serveClient; + private readonly opts; + private eio; + private _path; + private clientPathRegex; + /** + * @private + */ + _connectTimeout: number; + private httpServer; + /** + * Server constructor. + * + * @param srv http server, port, or options + * @param [opts] + */ + constructor(opts?: Partial); + constructor(srv?: http.Server | HTTPSServer | Http2SecureServer | number, opts?: Partial); + constructor(srv: undefined | Partial | http.Server | HTTPSServer | Http2SecureServer | number, opts?: Partial); + get _opts(): Partial; + /** + * Sets/gets whether client code is being served. + * + * @param v - whether to serve client code + * @return self when setting or value when getting + */ + serveClient(v: boolean): this; + serveClient(): boolean; + serveClient(v?: boolean): this | boolean; + /** + * Executes the middleware for an incoming namespace not already created on the server. + * + * @param name - name of incoming namespace + * @param auth - the auth parameters + * @param fn - callback + * + * @private + */ + _checkNamespace(name: string, auth: { + [key: string]: any; + }, fn: (nsp: Namespace | false) => void): void; + /** + * Sets the client serving path. + * + * @param {String} v pathname + * @return {Server|String} self when setting or value when getting + */ + path(v: string): this; + path(): string; + path(v?: string): this | string; + /** + * Set the delay after which a client without namespace is closed + * @param v + */ + connectTimeout(v: number): this; + connectTimeout(): number; + connectTimeout(v?: number): this | number; + /** + * Sets the adapter for rooms. + * + * @param v pathname + * @return self when setting or value when getting + */ + adapter(): AdapterConstructor | undefined; + adapter(v: AdapterConstructor): this; + /** + * Attaches socket.io to a server or port. + * + * @param srv - server or port + * @param opts - options passed to engine.io + * @return self + */ + listen(srv: http.Server | HTTPSServer | Http2SecureServer | number, opts?: Partial): this; + /** + * Attaches socket.io to a server or port. + * + * @param srv - server or port + * @param opts - options passed to engine.io + * @return self + */ + attach(srv: http.Server | HTTPSServer | Http2SecureServer | number, opts?: Partial): this; + attachApp(app: any, opts?: Partial): void; + /** + * Initialize engine + * + * @param srv - the server to attach to + * @param opts - options passed to engine.io + * @private + */ + private initEngine; + /** + * Attaches the static file serving. + * + * @param srv http server + * @private + */ + private attachServe; + /** + * Handles a request serving of client source and map + * + * @param req + * @param res + * @private + */ + private serve; + /** + * @param filename + * @param req + * @param res + * @private + */ + private static sendFile; + /** + * Binds socket.io to an engine.io instance. + * + * @param engine engine.io (or compatible) server + * @return self + */ + bind(engine: BaseServer): this; + /** + * Called with each incoming transport connection. + * + * @param {engine.Socket} conn + * @return self + * @private + */ + private onconnection; + /** + * Looks up a namespace. + * + * @example + * // with a simple string + * const myNamespace = io.of("/my-namespace"); + * + * // with a regex + * const dynamicNsp = io.of(/^\/dynamic-\d+$/).on("connection", (socket) => { + * const namespace = socket.nsp; // newNamespace.name === "/dynamic-101" + * + * // broadcast to all clients in the given sub-namespace + * namespace.emit("hello"); + * }); + * + * @param name - nsp name + * @param fn optional, nsp `connection` ev handler + */ + of(name: string | RegExp | ParentNspNameMatchFn, fn?: (socket: Socket) => void): Namespace; + /** + * Closes server connection + * + * @param [fn] optional, called as `fn([err])` on error OR all conns closed + */ + close(fn?: (err?: Error) => void): void; + /** + * Registers a middleware, which is a function that gets executed for every incoming {@link Socket}. + * + * @example + * io.use((socket, next) => { + * // ... + * next(); + * }); + * + * @param fn - the middleware function + */ + use(fn: (socket: Socket, next: (err?: ExtendedError) => void) => void): this; + /** + * Targets a room when emitting. + * + * @example + * // the “foo” event will be broadcast to all connected clients in the “room-101” room + * io.to("room-101").emit("foo", "bar"); + * + * // with an array of rooms (a client will be notified at most once) + * io.to(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * io.to("room-101").to("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + to(room: Room | Room[]): BroadcastOperator; + /** + * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases: + * + * @example + * // disconnect all clients in the "room-101" room + * io.in("room-101").disconnectSockets(); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + in(room: Room | Room[]): BroadcastOperator; + /** + * Excludes a room when emitting. + * + * @example + * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room + * io.except("room-101").emit("foo", "bar"); + * + * // with an array of rooms + * io.except(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * io.except("room-101").except("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + except(room: Room | Room[]): BroadcastOperator; + /** + * Emits an event and waits for an acknowledgement from all clients. + * + * @example + * try { + * const responses = await io.timeout(1000).emitWithAck("some-event"); + * console.log(responses); // one response per client + * } catch (e) { + * // some clients did not acknowledge the event in the given delay + * } + * + * @return a Promise that will be fulfilled when all clients have acknowledged the event + */ + emitWithAck>(ev: Ev, ...args: AllButLast>): Promise>>>; + /** + * Sends a `message` event to all clients. + * + * This method mimics the WebSocket.send() method. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send + * + * @example + * io.send("hello"); + * + * // this is equivalent to + * io.emit("message", "hello"); + * + * @return self + */ + send(...args: EventParams): this; + /** + * Sends a `message` event to all clients. Alias of {@link send}. + * + * @return self + */ + write(...args: EventParams): this; + /** + * Sends a message to the other Socket.IO servers of the cluster. + * + * @example + * io.serverSideEmit("hello", "world"); + * + * io.on("hello", (arg1) => { + * console.log(arg1); // prints "world" + * }); + * + * // acknowledgements (without binary content) are supported too: + * io.serverSideEmit("ping", (err, responses) => { + * if (err) { + * // some servers did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per server (except the current one) + * } + * }); + * + * io.on("ping", (cb) => { + * cb("pong"); + * }); + * + * @param ev - the event name + * @param args - an array of arguments, which may include an acknowledgement callback at the end + */ + serverSideEmit>(ev: Ev, ...args: EventParams, Ev>): boolean; + /** + * Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster. + * + * @example + * try { + * const responses = await io.serverSideEmitWithAck("ping"); + * console.log(responses); // one response per server (except the current one) + * } catch (e) { + * // some servers did not acknowledge the event in the given delay + * } + * + * @param ev - the event name + * @param args - an array of arguments + * + * @return a Promise that will be fulfilled when all servers have acknowledged the event + */ + serverSideEmitWithAck>(ev: Ev, ...args: AllButLast>): Promise>>[]>; + /** + * Gets a list of socket ids. + * + * @deprecated this method will be removed in the next major release, please use {@link Server#serverSideEmit} or + * {@link Server#fetchSockets} instead. + */ + allSockets(): Promise>; + /** + * Sets the compress flag. + * + * @example + * io.compress(false).emit("hello"); + * + * @param compress - if `true`, compresses the sending data + * @return a new {@link BroadcastOperator} instance for chaining + */ + compress(compress: boolean): BroadcastOperator; + /** + * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to + * receive messages (because of network slowness or other issues, or because they’re connected through long polling + * and is in the middle of a request-response cycle). + * + * @example + * io.volatile.emit("hello"); // the clients may or may not receive it + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get volatile(): BroadcastOperator; + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node. + * + * @example + * // the “foo” event will be broadcast to all connected clients on this node + * io.local.emit("foo", "bar"); + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get local(): BroadcastOperator; + /** + * Adds a timeout in milliseconds for the next operation. + * + * @example + * io.timeout(1000).emit("some-event", (err, responses) => { + * if (err) { + * // some clients did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per client + * } + * }); + * + * @param timeout + */ + timeout(timeout: number): BroadcastOperator, SocketData>; + /** + * Returns the matching socket instances. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // return all Socket instances + * const sockets = await io.fetchSockets(); + * + * // return all Socket instances in the "room1" room + * const sockets = await io.in("room1").fetchSockets(); + * + * for (const socket of sockets) { + * console.log(socket.id); + * console.log(socket.handshake); + * console.log(socket.rooms); + * console.log(socket.data); + * + * socket.emit("hello"); + * socket.join("room1"); + * socket.leave("room2"); + * socket.disconnect(); + * } + */ + fetchSockets(): Promise[]>; + /** + * Makes the matching socket instances join the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * + * // make all socket instances join the "room1" room + * io.socketsJoin("room1"); + * + * // make all socket instances in the "room1" room join the "room2" and "room3" rooms + * io.in("room1").socketsJoin(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsJoin(room: Room | Room[]): void; + /** + * Makes the matching socket instances leave the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // make all socket instances leave the "room1" room + * io.socketsLeave("room1"); + * + * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms + * io.in("room1").socketsLeave(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsLeave(room: Room | Room[]): void; + /** + * Makes the matching socket instances disconnect. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // make all socket instances disconnect (the connections might be kept alive for other namespaces) + * io.disconnectSockets(); + * + * // make all socket instances in the "room1" room disconnect and close the underlying connections + * io.in("room1").disconnectSockets(true); + * + * @param close - whether to close the underlying connection + */ + disconnectSockets(close?: boolean): void; +} +export { Socket, DisconnectReason, ServerOptions, Namespace, BroadcastOperator, RemoteSocket, }; +export { Event } from "./socket"; diff --git a/software/flow/node_modules/socket.io/dist/index.js b/software/flow/node_modules/socket.io/dist/index.js new file mode 100644 index 0000000..aa6151c --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/index.js @@ -0,0 +1,802 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Namespace = exports.Socket = exports.Server = void 0; +const http = require("http"); +const fs_1 = require("fs"); +const zlib_1 = require("zlib"); +const accepts = require("accepts"); +const stream_1 = require("stream"); +const path = require("path"); +const engine_io_1 = require("engine.io"); +const client_1 = require("./client"); +const events_1 = require("events"); +const namespace_1 = require("./namespace"); +Object.defineProperty(exports, "Namespace", { enumerable: true, get: function () { return namespace_1.Namespace; } }); +const parent_namespace_1 = require("./parent-namespace"); +const socket_io_adapter_1 = require("socket.io-adapter"); +const parser = __importStar(require("socket.io-parser")); +const debug_1 = __importDefault(require("debug")); +const socket_1 = require("./socket"); +Object.defineProperty(exports, "Socket", { enumerable: true, get: function () { return socket_1.Socket; } }); +const typed_events_1 = require("./typed-events"); +const uws_1 = require("./uws"); +const debug = (0, debug_1.default)("socket.io:server"); +const clientVersion = require("../package.json").version; +const dotMapRegex = /\.map/; +/** + * Represents a Socket.IO server. + * + * @example + * import { Server } from "socket.io"; + * + * const io = new Server(); + * + * io.on("connection", (socket) => { + * console.log(`socket ${socket.id} connected`); + * + * // send an event to the client + * socket.emit("foo", "bar"); + * + * socket.on("foobar", () => { + * // an event was received from the client + * }); + * + * // upon disconnection + * socket.on("disconnect", (reason) => { + * console.log(`socket ${socket.id} disconnected due to ${reason}`); + * }); + * }); + * + * io.listen(3000); + */ +class Server extends typed_events_1.StrictEventEmitter { + constructor(srv, opts = {}) { + super(); + /** + * @private + */ + this._nsps = new Map(); + this.parentNsps = new Map(); + /** + * A subset of the {@link parentNsps} map, only containing {@link ParentNamespace} which are based on a regular + * expression. + * + * @private + */ + this.parentNamespacesFromRegExp = new Map(); + if ("object" === typeof srv && + srv instanceof Object && + !srv.listen) { + opts = srv; + srv = undefined; + } + this.path(opts.path || "/socket.io"); + this.connectTimeout(opts.connectTimeout || 45000); + this.serveClient(false !== opts.serveClient); + this._parser = opts.parser || parser; + this.encoder = new this._parser.Encoder(); + this.opts = opts; + if (opts.connectionStateRecovery) { + opts.connectionStateRecovery = Object.assign({ + maxDisconnectionDuration: 2 * 60 * 1000, + skipMiddlewares: true, + }, opts.connectionStateRecovery); + this.adapter(opts.adapter || socket_io_adapter_1.SessionAwareAdapter); + } + else { + this.adapter(opts.adapter || socket_io_adapter_1.Adapter); + } + opts.cleanupEmptyChildNamespaces = !!opts.cleanupEmptyChildNamespaces; + this.sockets = this.of("/"); + if (srv || typeof srv == "number") + this.attach(srv); + } + get _opts() { + return this.opts; + } + serveClient(v) { + if (!arguments.length) + return this._serveClient; + this._serveClient = v; + return this; + } + /** + * Executes the middleware for an incoming namespace not already created on the server. + * + * @param name - name of incoming namespace + * @param auth - the auth parameters + * @param fn - callback + * + * @private + */ + _checkNamespace(name, auth, fn) { + if (this.parentNsps.size === 0) + return fn(false); + const keysIterator = this.parentNsps.keys(); + const run = () => { + const nextFn = keysIterator.next(); + if (nextFn.done) { + return fn(false); + } + nextFn.value(name, auth, (err, allow) => { + if (err || !allow) { + return run(); + } + if (this._nsps.has(name)) { + // the namespace was created in the meantime + debug("dynamic namespace %s already exists", name); + return fn(this._nsps.get(name)); + } + const namespace = this.parentNsps.get(nextFn.value).createChild(name); + debug("dynamic namespace %s was created", name); + fn(namespace); + }); + }; + run(); + } + path(v) { + if (!arguments.length) + return this._path; + this._path = v.replace(/\/$/, ""); + const escapedPath = this._path.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); + this.clientPathRegex = new RegExp("^" + + escapedPath + + "/socket\\.io(\\.msgpack|\\.esm)?(\\.min)?\\.js(\\.map)?(?:\\?|$)"); + return this; + } + connectTimeout(v) { + if (v === undefined) + return this._connectTimeout; + this._connectTimeout = v; + return this; + } + adapter(v) { + if (!arguments.length) + return this._adapter; + this._adapter = v; + for (const nsp of this._nsps.values()) { + nsp._initAdapter(); + } + return this; + } + /** + * Attaches socket.io to a server or port. + * + * @param srv - server or port + * @param opts - options passed to engine.io + * @return self + */ + listen(srv, opts = {}) { + return this.attach(srv, opts); + } + /** + * Attaches socket.io to a server or port. + * + * @param srv - server or port + * @param opts - options passed to engine.io + * @return self + */ + attach(srv, opts = {}) { + if ("function" == typeof srv) { + const msg = "You are trying to attach socket.io to an express " + + "request handler function. Please pass a http.Server instance."; + throw new Error(msg); + } + // handle a port as a string + if (Number(srv) == srv) { + srv = Number(srv); + } + if ("number" == typeof srv) { + debug("creating http server and binding to %d", srv); + const port = srv; + srv = http.createServer((req, res) => { + res.writeHead(404); + res.end(); + }); + srv.listen(port); + } + // merge the options passed to the Socket.IO server + Object.assign(opts, this.opts); + // set engine.io path to `/socket.io` + opts.path = opts.path || this._path; + this.initEngine(srv, opts); + return this; + } + attachApp(app /*: TemplatedApp */, opts = {}) { + // merge the options passed to the Socket.IO server + Object.assign(opts, this.opts); + // set engine.io path to `/socket.io` + opts.path = opts.path || this._path; + // initialize engine + debug("creating uWebSockets.js-based engine with opts %j", opts); + const engine = new engine_io_1.uServer(opts); + engine.attach(app, opts); + // bind to engine events + this.bind(engine); + if (this._serveClient) { + // attach static file serving + app.get(`${this._path}/*`, (res, req) => { + if (!this.clientPathRegex.test(req.getUrl())) { + req.setYield(true); + return; + } + const filename = req + .getUrl() + .replace(this._path, "") + .replace(/\?.*$/, "") + .replace(/^\//, ""); + const isMap = dotMapRegex.test(filename); + const type = isMap ? "map" : "source"; + // Per the standard, ETags must be quoted: + // https://tools.ietf.org/html/rfc7232#section-2.3 + const expectedEtag = '"' + clientVersion + '"'; + const weakEtag = "W/" + expectedEtag; + const etag = req.getHeader("if-none-match"); + if (etag) { + if (expectedEtag === etag || weakEtag === etag) { + debug("serve client %s 304", type); + res.writeStatus("304 Not Modified"); + res.end(); + return; + } + } + debug("serve client %s", type); + res.writeHeader("cache-control", "public, max-age=0"); + res.writeHeader("content-type", "application/" + (isMap ? "json" : "javascript") + "; charset=utf-8"); + res.writeHeader("etag", expectedEtag); + const filepath = path.join(__dirname, "../client-dist/", filename); + (0, uws_1.serveFile)(res, filepath); + }); + } + (0, uws_1.patchAdapter)(app); + } + /** + * Initialize engine + * + * @param srv - the server to attach to + * @param opts - options passed to engine.io + * @private + */ + initEngine(srv, opts) { + // initialize engine + debug("creating engine.io instance with opts %j", opts); + this.eio = (0, engine_io_1.attach)(srv, opts); + // attach static file serving + if (this._serveClient) + this.attachServe(srv); + // Export http server + this.httpServer = srv; + // bind to engine events + this.bind(this.eio); + } + /** + * Attaches the static file serving. + * + * @param srv http server + * @private + */ + attachServe(srv) { + debug("attaching client serving req handler"); + const evs = srv.listeners("request").slice(0); + srv.removeAllListeners("request"); + srv.on("request", (req, res) => { + if (this.clientPathRegex.test(req.url)) { + this.serve(req, res); + } + else { + for (let i = 0; i < evs.length; i++) { + evs[i].call(srv, req, res); + } + } + }); + } + /** + * Handles a request serving of client source and map + * + * @param req + * @param res + * @private + */ + serve(req, res) { + const filename = req.url.replace(this._path, "").replace(/\?.*$/, ""); + const isMap = dotMapRegex.test(filename); + const type = isMap ? "map" : "source"; + // Per the standard, ETags must be quoted: + // https://tools.ietf.org/html/rfc7232#section-2.3 + const expectedEtag = '"' + clientVersion + '"'; + const weakEtag = "W/" + expectedEtag; + const etag = req.headers["if-none-match"]; + if (etag) { + if (expectedEtag === etag || weakEtag === etag) { + debug("serve client %s 304", type); + res.writeHead(304); + res.end(); + return; + } + } + debug("serve client %s", type); + res.setHeader("Cache-Control", "public, max-age=0"); + res.setHeader("Content-Type", "application/" + (isMap ? "json" : "javascript") + "; charset=utf-8"); + res.setHeader("ETag", expectedEtag); + Server.sendFile(filename, req, res); + } + /** + * @param filename + * @param req + * @param res + * @private + */ + static sendFile(filename, req, res) { + const readStream = (0, fs_1.createReadStream)(path.join(__dirname, "../client-dist/", filename)); + const encoding = accepts(req).encodings(["br", "gzip", "deflate"]); + const onError = (err) => { + if (err) { + res.end(); + } + }; + switch (encoding) { + case "br": + res.writeHead(200, { "content-encoding": "br" }); + readStream.pipe((0, zlib_1.createBrotliCompress)()).pipe(res); + (0, stream_1.pipeline)(readStream, (0, zlib_1.createBrotliCompress)(), res, onError); + break; + case "gzip": + res.writeHead(200, { "content-encoding": "gzip" }); + (0, stream_1.pipeline)(readStream, (0, zlib_1.createGzip)(), res, onError); + break; + case "deflate": + res.writeHead(200, { "content-encoding": "deflate" }); + (0, stream_1.pipeline)(readStream, (0, zlib_1.createDeflate)(), res, onError); + break; + default: + res.writeHead(200); + (0, stream_1.pipeline)(readStream, res, onError); + } + } + /** + * Binds socket.io to an engine.io instance. + * + * @param engine engine.io (or compatible) server + * @return self + */ + bind(engine) { + this.engine = engine; + this.engine.on("connection", this.onconnection.bind(this)); + return this; + } + /** + * Called with each incoming transport connection. + * + * @param {engine.Socket} conn + * @return self + * @private + */ + onconnection(conn) { + debug("incoming connection with id %s", conn.id); + const client = new client_1.Client(this, conn); + if (conn.protocol === 3) { + // @ts-ignore + client.connect("/"); + } + return this; + } + /** + * Looks up a namespace. + * + * @example + * // with a simple string + * const myNamespace = io.of("/my-namespace"); + * + * // with a regex + * const dynamicNsp = io.of(/^\/dynamic-\d+$/).on("connection", (socket) => { + * const namespace = socket.nsp; // newNamespace.name === "/dynamic-101" + * + * // broadcast to all clients in the given sub-namespace + * namespace.emit("hello"); + * }); + * + * @param name - nsp name + * @param fn optional, nsp `connection` ev handler + */ + of(name, fn) { + if (typeof name === "function" || name instanceof RegExp) { + const parentNsp = new parent_namespace_1.ParentNamespace(this); + debug("initializing parent namespace %s", parentNsp.name); + if (typeof name === "function") { + this.parentNsps.set(name, parentNsp); + } + else { + this.parentNsps.set((nsp, conn, next) => next(null, name.test(nsp)), parentNsp); + this.parentNamespacesFromRegExp.set(name, parentNsp); + } + if (fn) { + // @ts-ignore + parentNsp.on("connect", fn); + } + return parentNsp; + } + if (String(name)[0] !== "/") + name = "/" + name; + let nsp = this._nsps.get(name); + if (!nsp) { + for (const [regex, parentNamespace] of this.parentNamespacesFromRegExp) { + if (regex.test(name)) { + debug("attaching namespace %s to parent namespace %s", name, regex); + return parentNamespace.createChild(name); + } + } + debug("initializing namespace %s", name); + nsp = new namespace_1.Namespace(this, name); + this._nsps.set(name, nsp); + if (name !== "/") { + // @ts-ignore + this.sockets.emitReserved("new_namespace", nsp); + } + } + if (fn) + nsp.on("connect", fn); + return nsp; + } + /** + * Closes server connection + * + * @param [fn] optional, called as `fn([err])` on error OR all conns closed + */ + close(fn) { + for (const socket of this.sockets.sockets.values()) { + socket._onclose("server shutting down"); + } + this.engine.close(); + // restore the Adapter prototype + (0, uws_1.restoreAdapter)(); + if (this.httpServer) { + this.httpServer.close(fn); + } + else { + fn && fn(); + } + } + /** + * Registers a middleware, which is a function that gets executed for every incoming {@link Socket}. + * + * @example + * io.use((socket, next) => { + * // ... + * next(); + * }); + * + * @param fn - the middleware function + */ + use(fn) { + this.sockets.use(fn); + return this; + } + /** + * Targets a room when emitting. + * + * @example + * // the “foo” event will be broadcast to all connected clients in the “room-101” room + * io.to("room-101").emit("foo", "bar"); + * + * // with an array of rooms (a client will be notified at most once) + * io.to(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * io.to("room-101").to("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + to(room) { + return this.sockets.to(room); + } + /** + * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases: + * + * @example + * // disconnect all clients in the "room-101" room + * io.in("room-101").disconnectSockets(); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + in(room) { + return this.sockets.in(room); + } + /** + * Excludes a room when emitting. + * + * @example + * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room + * io.except("room-101").emit("foo", "bar"); + * + * // with an array of rooms + * io.except(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * io.except("room-101").except("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + except(room) { + return this.sockets.except(room); + } + /** + * Emits an event and waits for an acknowledgement from all clients. + * + * @example + * try { + * const responses = await io.timeout(1000).emitWithAck("some-event"); + * console.log(responses); // one response per client + * } catch (e) { + * // some clients did not acknowledge the event in the given delay + * } + * + * @return a Promise that will be fulfilled when all clients have acknowledged the event + */ + emitWithAck(ev, ...args) { + return this.sockets.emitWithAck(ev, ...args); + } + /** + * Sends a `message` event to all clients. + * + * This method mimics the WebSocket.send() method. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send + * + * @example + * io.send("hello"); + * + * // this is equivalent to + * io.emit("message", "hello"); + * + * @return self + */ + send(...args) { + this.sockets.emit("message", ...args); + return this; + } + /** + * Sends a `message` event to all clients. Alias of {@link send}. + * + * @return self + */ + write(...args) { + this.sockets.emit("message", ...args); + return this; + } + /** + * Sends a message to the other Socket.IO servers of the cluster. + * + * @example + * io.serverSideEmit("hello", "world"); + * + * io.on("hello", (arg1) => { + * console.log(arg1); // prints "world" + * }); + * + * // acknowledgements (without binary content) are supported too: + * io.serverSideEmit("ping", (err, responses) => { + * if (err) { + * // some servers did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per server (except the current one) + * } + * }); + * + * io.on("ping", (cb) => { + * cb("pong"); + * }); + * + * @param ev - the event name + * @param args - an array of arguments, which may include an acknowledgement callback at the end + */ + serverSideEmit(ev, ...args) { + return this.sockets.serverSideEmit(ev, ...args); + } + /** + * Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster. + * + * @example + * try { + * const responses = await io.serverSideEmitWithAck("ping"); + * console.log(responses); // one response per server (except the current one) + * } catch (e) { + * // some servers did not acknowledge the event in the given delay + * } + * + * @param ev - the event name + * @param args - an array of arguments + * + * @return a Promise that will be fulfilled when all servers have acknowledged the event + */ + serverSideEmitWithAck(ev, ...args) { + return this.sockets.serverSideEmitWithAck(ev, ...args); + } + /** + * Gets a list of socket ids. + * + * @deprecated this method will be removed in the next major release, please use {@link Server#serverSideEmit} or + * {@link Server#fetchSockets} instead. + */ + allSockets() { + return this.sockets.allSockets(); + } + /** + * Sets the compress flag. + * + * @example + * io.compress(false).emit("hello"); + * + * @param compress - if `true`, compresses the sending data + * @return a new {@link BroadcastOperator} instance for chaining + */ + compress(compress) { + return this.sockets.compress(compress); + } + /** + * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to + * receive messages (because of network slowness or other issues, or because they’re connected through long polling + * and is in the middle of a request-response cycle). + * + * @example + * io.volatile.emit("hello"); // the clients may or may not receive it + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get volatile() { + return this.sockets.volatile; + } + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node. + * + * @example + * // the “foo” event will be broadcast to all connected clients on this node + * io.local.emit("foo", "bar"); + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get local() { + return this.sockets.local; + } + /** + * Adds a timeout in milliseconds for the next operation. + * + * @example + * io.timeout(1000).emit("some-event", (err, responses) => { + * if (err) { + * // some clients did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per client + * } + * }); + * + * @param timeout + */ + timeout(timeout) { + return this.sockets.timeout(timeout); + } + /** + * Returns the matching socket instances. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // return all Socket instances + * const sockets = await io.fetchSockets(); + * + * // return all Socket instances in the "room1" room + * const sockets = await io.in("room1").fetchSockets(); + * + * for (const socket of sockets) { + * console.log(socket.id); + * console.log(socket.handshake); + * console.log(socket.rooms); + * console.log(socket.data); + * + * socket.emit("hello"); + * socket.join("room1"); + * socket.leave("room2"); + * socket.disconnect(); + * } + */ + fetchSockets() { + return this.sockets.fetchSockets(); + } + /** + * Makes the matching socket instances join the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * + * // make all socket instances join the "room1" room + * io.socketsJoin("room1"); + * + * // make all socket instances in the "room1" room join the "room2" and "room3" rooms + * io.in("room1").socketsJoin(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsJoin(room) { + return this.sockets.socketsJoin(room); + } + /** + * Makes the matching socket instances leave the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // make all socket instances leave the "room1" room + * io.socketsLeave("room1"); + * + * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms + * io.in("room1").socketsLeave(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsLeave(room) { + return this.sockets.socketsLeave(room); + } + /** + * Makes the matching socket instances disconnect. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * // make all socket instances disconnect (the connections might be kept alive for other namespaces) + * io.disconnectSockets(); + * + * // make all socket instances in the "room1" room disconnect and close the underlying connections + * io.in("room1").disconnectSockets(true); + * + * @param close - whether to close the underlying connection + */ + disconnectSockets(close = false) { + return this.sockets.disconnectSockets(close); + } +} +exports.Server = Server; +/** + * Expose main namespace (/). + */ +const emitterMethods = Object.keys(events_1.EventEmitter.prototype).filter(function (key) { + return typeof events_1.EventEmitter.prototype[key] === "function"; +}); +emitterMethods.forEach(function (fn) { + Server.prototype[fn] = function () { + return this.sockets[fn].apply(this.sockets, arguments); + }; +}); +module.exports = (srv, opts) => new Server(srv, opts); +module.exports.Server = Server; +module.exports.Namespace = namespace_1.Namespace; +module.exports.Socket = socket_1.Socket; +var socket_2 = require("./socket"); diff --git a/software/flow/node_modules/socket.io/dist/namespace.d.ts b/software/flow/node_modules/socket.io/dist/namespace.d.ts new file mode 100644 index 0000000..8173537 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/namespace.d.ts @@ -0,0 +1,442 @@ +import { Socket } from "./socket"; +import type { Server } from "./index"; +import { EventParams, EventNames, EventsMap, StrictEventEmitter, DefaultEventsMap, DecorateAcknowledgementsWithTimeoutAndMultipleResponses, AllButLast, Last, FirstArg, SecondArg } from "./typed-events"; +import type { Client } from "./client"; +import type { Adapter, Room, SocketId } from "socket.io-adapter"; +import { BroadcastOperator } from "./broadcast-operator"; +export interface ExtendedError extends Error { + data?: any; +} +export interface NamespaceReservedEventsMap { + connect: (socket: Socket) => void; + connection: (socket: Socket) => void; +} +export interface ServerReservedEventsMap extends NamespaceReservedEventsMap { + new_namespace: (namespace: Namespace) => void; +} +export declare const RESERVED_EVENTS: ReadonlySet; +/** + * A Namespace is a communication channel that allows you to split the logic of your application over a single shared + * connection. + * + * Each namespace has its own: + * + * - event handlers + * + * ``` + * io.of("/orders").on("connection", (socket) => { + * socket.on("order:list", () => {}); + * socket.on("order:create", () => {}); + * }); + * + * io.of("/users").on("connection", (socket) => { + * socket.on("user:list", () => {}); + * }); + * ``` + * + * - rooms + * + * ``` + * const orderNamespace = io.of("/orders"); + * + * orderNamespace.on("connection", (socket) => { + * socket.join("room1"); + * orderNamespace.to("room1").emit("hello"); + * }); + * + * const userNamespace = io.of("/users"); + * + * userNamespace.on("connection", (socket) => { + * socket.join("room1"); // distinct from the room in the "orders" namespace + * userNamespace.to("room1").emit("holà"); + * }); + * ``` + * + * - middlewares + * + * ``` + * const orderNamespace = io.of("/orders"); + * + * orderNamespace.use((socket, next) => { + * // ensure the socket has access to the "orders" namespace + * }); + * + * const userNamespace = io.of("/users"); + * + * userNamespace.use((socket, next) => { + * // ensure the socket has access to the "users" namespace + * }); + * ``` + */ +export declare class Namespace extends StrictEventEmitter> { + readonly name: string; + readonly sockets: Map>; + adapter: Adapter; + /** @private */ + readonly server: Server; + /** @private */ + _fns: Array<(socket: Socket, next: (err?: ExtendedError) => void) => void>; + /** @private */ + _ids: number; + /** + * Namespace constructor. + * + * @param server instance + * @param name + */ + constructor(server: Server, name: string); + /** + * Initializes the `Adapter` for this nsp. + * Run upon changing adapter by `Server#adapter` + * in addition to the constructor. + * + * @private + */ + _initAdapter(): void; + /** + * Registers a middleware, which is a function that gets executed for every incoming {@link Socket}. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.use((socket, next) => { + * // ... + * next(); + * }); + * + * @param fn - the middleware function + */ + use(fn: (socket: Socket, next: (err?: ExtendedError) => void) => void): this; + /** + * Executes the middleware for an incoming client. + * + * @param socket - the socket that will get added + * @param fn - last fn call in the middleware + * @private + */ + private run; + /** + * Targets a room when emitting. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // the “foo” event will be broadcast to all connected clients in the “room-101” room + * myNamespace.to("room-101").emit("foo", "bar"); + * + * // with an array of rooms (a client will be notified at most once) + * myNamespace.to(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * myNamespace.to("room-101").to("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + to(room: Room | Room[]): BroadcastOperator; + /** + * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases: + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // disconnect all clients in the "room-101" room + * myNamespace.in("room-101").disconnectSockets(); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + in(room: Room | Room[]): BroadcastOperator; + /** + * Excludes a room when emitting. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room + * myNamespace.except("room-101").emit("foo", "bar"); + * + * // with an array of rooms + * myNamespace.except(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * myNamespace.except("room-101").except("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + except(room: Room | Room[]): BroadcastOperator; + /** + * Adds a new client. + * + * @return {Socket} + * @private + */ + _add(client: Client, auth: Record, fn: (socket: Socket) => void): any; + private _createSocket; + private _doConnect; + /** + * Removes a client. Called by each `Socket`. + * + * @private + */ + _remove(socket: Socket): void; + /** + * Emits to all connected clients. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.emit("hello", "world"); + * + * // all serializable datastructures are supported (no need to call JSON.stringify) + * myNamespace.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) }); + * + * // with an acknowledgement from the clients + * myNamespace.timeout(1000).emit("some-event", (err, responses) => { + * if (err) { + * // some clients did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per client + * } + * }); + * + * @return Always true + */ + emit>(ev: Ev, ...args: EventParams): boolean; + /** + * Emits an event and waits for an acknowledgement from all clients. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * try { + * const responses = await myNamespace.timeout(1000).emitWithAck("some-event"); + * console.log(responses); // one response per client + * } catch (e) { + * // some clients did not acknowledge the event in the given delay + * } + * + * @return a Promise that will be fulfilled when all clients have acknowledged the event + */ + emitWithAck>(ev: Ev, ...args: AllButLast>): Promise>>>; + /** + * Sends a `message` event to all clients. + * + * This method mimics the WebSocket.send() method. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.send("hello"); + * + * // this is equivalent to + * myNamespace.emit("message", "hello"); + * + * @return self + */ + send(...args: EventParams): this; + /** + * Sends a `message` event to all clients. Sends a `message` event. Alias of {@link send}. + * + * @return self + */ + write(...args: EventParams): this; + /** + * Sends a message to the other Socket.IO servers of the cluster. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.serverSideEmit("hello", "world"); + * + * myNamespace.on("hello", (arg1) => { + * console.log(arg1); // prints "world" + * }); + * + * // acknowledgements (without binary content) are supported too: + * myNamespace.serverSideEmit("ping", (err, responses) => { + * if (err) { + * // some servers did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per server (except the current one) + * } + * }); + * + * myNamespace.on("ping", (cb) => { + * cb("pong"); + * }); + * + * @param ev - the event name + * @param args - an array of arguments, which may include an acknowledgement callback at the end + */ + serverSideEmit>(ev: Ev, ...args: EventParams, Ev>): boolean; + /** + * Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * try { + * const responses = await myNamespace.serverSideEmitWithAck("ping"); + * console.log(responses); // one response per server (except the current one) + * } catch (e) { + * // some servers did not acknowledge the event in the given delay + * } + * + * @param ev - the event name + * @param args - an array of arguments + * + * @return a Promise that will be fulfilled when all servers have acknowledged the event + */ + serverSideEmitWithAck>(ev: Ev, ...args: AllButLast>): Promise>>[]>; + /** + * Called when a packet is received from another Socket.IO server + * + * @param args - an array of arguments, which may include an acknowledgement callback at the end + * + * @private + */ + _onServerSideEmit(args: [string, ...any[]]): void; + /** + * Gets a list of clients. + * + * @deprecated this method will be removed in the next major release, please use {@link Namespace#serverSideEmit} or + * {@link Namespace#fetchSockets} instead. + */ + allSockets(): Promise>; + /** + * Sets the compress flag. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.compress(false).emit("hello"); + * + * @param compress - if `true`, compresses the sending data + * @return self + */ + compress(compress: boolean): BroadcastOperator; + /** + * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to + * receive messages (because of network slowness or other issues, or because they’re connected through long polling + * and is in the middle of a request-response cycle). + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.volatile.emit("hello"); // the clients may or may not receive it + * + * @return self + */ + get volatile(): BroadcastOperator; + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // the “foo” event will be broadcast to all connected clients on this node + * myNamespace.local.emit("foo", "bar"); + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get local(): BroadcastOperator; + /** + * Adds a timeout in milliseconds for the next operation. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.timeout(1000).emit("some-event", (err, responses) => { + * if (err) { + * // some clients did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per client + * } + * }); + * + * @param timeout + */ + timeout(timeout: number): BroadcastOperator, SocketData>; + /** + * Returns the matching socket instances. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // return all Socket instances + * const sockets = await myNamespace.fetchSockets(); + * + * // return all Socket instances in the "room1" room + * const sockets = await myNamespace.in("room1").fetchSockets(); + * + * for (const socket of sockets) { + * console.log(socket.id); + * console.log(socket.handshake); + * console.log(socket.rooms); + * console.log(socket.data); + * + * socket.emit("hello"); + * socket.join("room1"); + * socket.leave("room2"); + * socket.disconnect(); + * } + */ + fetchSockets(): Promise[]>; + /** + * Makes the matching socket instances join the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // make all socket instances join the "room1" room + * myNamespace.socketsJoin("room1"); + * + * // make all socket instances in the "room1" room join the "room2" and "room3" rooms + * myNamespace.in("room1").socketsJoin(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsJoin(room: Room | Room[]): void; + /** + * Makes the matching socket instances leave the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // make all socket instances leave the "room1" room + * myNamespace.socketsLeave("room1"); + * + * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms + * myNamespace.in("room1").socketsLeave(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsLeave(room: Room | Room[]): void; + /** + * Makes the matching socket instances disconnect. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // make all socket instances disconnect (the connections might be kept alive for other namespaces) + * myNamespace.disconnectSockets(); + * + * // make all socket instances in the "room1" room disconnect and close the underlying connections + * myNamespace.in("room1").disconnectSockets(true); + * + * @param close - whether to close the underlying connection + */ + disconnectSockets(close?: boolean): void; +} diff --git a/software/flow/node_modules/socket.io/dist/namespace.js b/software/flow/node_modules/socket.io/dist/namespace.js new file mode 100644 index 0000000..80fa14f --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/namespace.js @@ -0,0 +1,593 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Namespace = exports.RESERVED_EVENTS = void 0; +const socket_1 = require("./socket"); +const typed_events_1 = require("./typed-events"); +const debug_1 = __importDefault(require("debug")); +const broadcast_operator_1 = require("./broadcast-operator"); +const debug = (0, debug_1.default)("socket.io:namespace"); +exports.RESERVED_EVENTS = new Set(["connect", "connection", "new_namespace"]); +/** + * A Namespace is a communication channel that allows you to split the logic of your application over a single shared + * connection. + * + * Each namespace has its own: + * + * - event handlers + * + * ``` + * io.of("/orders").on("connection", (socket) => { + * socket.on("order:list", () => {}); + * socket.on("order:create", () => {}); + * }); + * + * io.of("/users").on("connection", (socket) => { + * socket.on("user:list", () => {}); + * }); + * ``` + * + * - rooms + * + * ``` + * const orderNamespace = io.of("/orders"); + * + * orderNamespace.on("connection", (socket) => { + * socket.join("room1"); + * orderNamespace.to("room1").emit("hello"); + * }); + * + * const userNamespace = io.of("/users"); + * + * userNamespace.on("connection", (socket) => { + * socket.join("room1"); // distinct from the room in the "orders" namespace + * userNamespace.to("room1").emit("holà"); + * }); + * ``` + * + * - middlewares + * + * ``` + * const orderNamespace = io.of("/orders"); + * + * orderNamespace.use((socket, next) => { + * // ensure the socket has access to the "orders" namespace + * }); + * + * const userNamespace = io.of("/users"); + * + * userNamespace.use((socket, next) => { + * // ensure the socket has access to the "users" namespace + * }); + * ``` + */ +class Namespace extends typed_events_1.StrictEventEmitter { + /** + * Namespace constructor. + * + * @param server instance + * @param name + */ + constructor(server, name) { + super(); + this.sockets = new Map(); + /** @private */ + this._fns = []; + /** @private */ + this._ids = 0; + this.server = server; + this.name = name; + this._initAdapter(); + } + /** + * Initializes the `Adapter` for this nsp. + * Run upon changing adapter by `Server#adapter` + * in addition to the constructor. + * + * @private + */ + _initAdapter() { + // @ts-ignore + this.adapter = new (this.server.adapter())(this); + } + /** + * Registers a middleware, which is a function that gets executed for every incoming {@link Socket}. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.use((socket, next) => { + * // ... + * next(); + * }); + * + * @param fn - the middleware function + */ + use(fn) { + this._fns.push(fn); + return this; + } + /** + * Executes the middleware for an incoming client. + * + * @param socket - the socket that will get added + * @param fn - last fn call in the middleware + * @private + */ + run(socket, fn) { + const fns = this._fns.slice(0); + if (!fns.length) + return fn(null); + function run(i) { + fns[i](socket, function (err) { + // upon error, short-circuit + if (err) + return fn(err); + // if no middleware left, summon callback + if (!fns[i + 1]) + return fn(null); + // go on to next + run(i + 1); + }); + } + run(0); + } + /** + * Targets a room when emitting. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // the “foo” event will be broadcast to all connected clients in the “room-101” room + * myNamespace.to("room-101").emit("foo", "bar"); + * + * // with an array of rooms (a client will be notified at most once) + * myNamespace.to(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * myNamespace.to("room-101").to("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + to(room) { + return new broadcast_operator_1.BroadcastOperator(this.adapter).to(room); + } + /** + * Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases: + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // disconnect all clients in the "room-101" room + * myNamespace.in("room-101").disconnectSockets(); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + in(room) { + return new broadcast_operator_1.BroadcastOperator(this.adapter).in(room); + } + /** + * Excludes a room when emitting. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room + * myNamespace.except("room-101").emit("foo", "bar"); + * + * // with an array of rooms + * myNamespace.except(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * myNamespace.except("room-101").except("room-102").emit("foo", "bar"); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + except(room) { + return new broadcast_operator_1.BroadcastOperator(this.adapter).except(room); + } + /** + * Adds a new client. + * + * @return {Socket} + * @private + */ + async _add(client, auth, fn) { + var _a; + debug("adding socket to nsp %s", this.name); + const socket = await this._createSocket(client, auth); + if ( + // @ts-ignore + ((_a = this.server.opts.connectionStateRecovery) === null || _a === void 0 ? void 0 : _a.skipMiddlewares) && + socket.recovered && + client.conn.readyState === "open") { + return this._doConnect(socket, fn); + } + this.run(socket, (err) => { + process.nextTick(() => { + if ("open" !== client.conn.readyState) { + debug("next called after client was closed - ignoring socket"); + socket._cleanup(); + return; + } + if (err) { + debug("middleware error, sending CONNECT_ERROR packet to the client"); + socket._cleanup(); + if (client.conn.protocol === 3) { + return socket._error(err.data || err.message); + } + else { + return socket._error({ + message: err.message, + data: err.data, + }); + } + } + this._doConnect(socket, fn); + }); + }); + } + async _createSocket(client, auth) { + const sessionId = auth.pid; + const offset = auth.offset; + if ( + // @ts-ignore + this.server.opts.connectionStateRecovery && + typeof sessionId === "string" && + typeof offset === "string") { + let session; + try { + session = await this.adapter.restoreSession(sessionId, offset); + } + catch (e) { + debug("error while restoring session: %s", e); + } + if (session) { + debug("connection state recovered for sid %s", session.sid); + return new socket_1.Socket(this, client, auth, session); + } + } + return new socket_1.Socket(this, client, auth); + } + _doConnect(socket, fn) { + // track socket + this.sockets.set(socket.id, socket); + // it's paramount that the internal `onconnect` logic + // fires before user-set events to prevent state order + // violations (such as a disconnection before the connection + // logic is complete) + socket._onconnect(); + if (fn) + fn(socket); + // fire user-set events + this.emitReserved("connect", socket); + this.emitReserved("connection", socket); + } + /** + * Removes a client. Called by each `Socket`. + * + * @private + */ + _remove(socket) { + if (this.sockets.has(socket.id)) { + this.sockets.delete(socket.id); + } + else { + debug("ignoring remove for %s", socket.id); + } + } + /** + * Emits to all connected clients. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.emit("hello", "world"); + * + * // all serializable datastructures are supported (no need to call JSON.stringify) + * myNamespace.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) }); + * + * // with an acknowledgement from the clients + * myNamespace.timeout(1000).emit("some-event", (err, responses) => { + * if (err) { + * // some clients did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per client + * } + * }); + * + * @return Always true + */ + emit(ev, ...args) { + return new broadcast_operator_1.BroadcastOperator(this.adapter).emit(ev, ...args); + } + /** + * Emits an event and waits for an acknowledgement from all clients. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * try { + * const responses = await myNamespace.timeout(1000).emitWithAck("some-event"); + * console.log(responses); // one response per client + * } catch (e) { + * // some clients did not acknowledge the event in the given delay + * } + * + * @return a Promise that will be fulfilled when all clients have acknowledged the event + */ + emitWithAck(ev, ...args) { + return new broadcast_operator_1.BroadcastOperator(this.adapter).emitWithAck(ev, ...args); + } + /** + * Sends a `message` event to all clients. + * + * This method mimics the WebSocket.send() method. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.send("hello"); + * + * // this is equivalent to + * myNamespace.emit("message", "hello"); + * + * @return self + */ + send(...args) { + this.emit("message", ...args); + return this; + } + /** + * Sends a `message` event to all clients. Sends a `message` event. Alias of {@link send}. + * + * @return self + */ + write(...args) { + this.emit("message", ...args); + return this; + } + /** + * Sends a message to the other Socket.IO servers of the cluster. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.serverSideEmit("hello", "world"); + * + * myNamespace.on("hello", (arg1) => { + * console.log(arg1); // prints "world" + * }); + * + * // acknowledgements (without binary content) are supported too: + * myNamespace.serverSideEmit("ping", (err, responses) => { + * if (err) { + * // some servers did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per server (except the current one) + * } + * }); + * + * myNamespace.on("ping", (cb) => { + * cb("pong"); + * }); + * + * @param ev - the event name + * @param args - an array of arguments, which may include an acknowledgement callback at the end + */ + serverSideEmit(ev, ...args) { + if (exports.RESERVED_EVENTS.has(ev)) { + throw new Error(`"${String(ev)}" is a reserved event name`); + } + args.unshift(ev); + this.adapter.serverSideEmit(args); + return true; + } + /** + * Sends a message and expect an acknowledgement from the other Socket.IO servers of the cluster. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * try { + * const responses = await myNamespace.serverSideEmitWithAck("ping"); + * console.log(responses); // one response per server (except the current one) + * } catch (e) { + * // some servers did not acknowledge the event in the given delay + * } + * + * @param ev - the event name + * @param args - an array of arguments + * + * @return a Promise that will be fulfilled when all servers have acknowledged the event + */ + serverSideEmitWithAck(ev, ...args) { + return new Promise((resolve, reject) => { + args.push((err, responses) => { + if (err) { + err.responses = responses; + return reject(err); + } + else { + return resolve(responses); + } + }); + this.serverSideEmit(ev, ...args); + }); + } + /** + * Called when a packet is received from another Socket.IO server + * + * @param args - an array of arguments, which may include an acknowledgement callback at the end + * + * @private + */ + _onServerSideEmit(args) { + super.emitUntyped.apply(this, args); + } + /** + * Gets a list of clients. + * + * @deprecated this method will be removed in the next major release, please use {@link Namespace#serverSideEmit} or + * {@link Namespace#fetchSockets} instead. + */ + allSockets() { + return new broadcast_operator_1.BroadcastOperator(this.adapter).allSockets(); + } + /** + * Sets the compress flag. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.compress(false).emit("hello"); + * + * @param compress - if `true`, compresses the sending data + * @return self + */ + compress(compress) { + return new broadcast_operator_1.BroadcastOperator(this.adapter).compress(compress); + } + /** + * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to + * receive messages (because of network slowness or other issues, or because they’re connected through long polling + * and is in the middle of a request-response cycle). + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.volatile.emit("hello"); // the clients may or may not receive it + * + * @return self + */ + get volatile() { + return new broadcast_operator_1.BroadcastOperator(this.adapter).volatile; + } + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // the “foo” event will be broadcast to all connected clients on this node + * myNamespace.local.emit("foo", "bar"); + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get local() { + return new broadcast_operator_1.BroadcastOperator(this.adapter).local; + } + /** + * Adds a timeout in milliseconds for the next operation. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * myNamespace.timeout(1000).emit("some-event", (err, responses) => { + * if (err) { + * // some clients did not acknowledge the event in the given delay + * } else { + * console.log(responses); // one response per client + * } + * }); + * + * @param timeout + */ + timeout(timeout) { + return new broadcast_operator_1.BroadcastOperator(this.adapter).timeout(timeout); + } + /** + * Returns the matching socket instances. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // return all Socket instances + * const sockets = await myNamespace.fetchSockets(); + * + * // return all Socket instances in the "room1" room + * const sockets = await myNamespace.in("room1").fetchSockets(); + * + * for (const socket of sockets) { + * console.log(socket.id); + * console.log(socket.handshake); + * console.log(socket.rooms); + * console.log(socket.data); + * + * socket.emit("hello"); + * socket.join("room1"); + * socket.leave("room2"); + * socket.disconnect(); + * } + */ + fetchSockets() { + return new broadcast_operator_1.BroadcastOperator(this.adapter).fetchSockets(); + } + /** + * Makes the matching socket instances join the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // make all socket instances join the "room1" room + * myNamespace.socketsJoin("room1"); + * + * // make all socket instances in the "room1" room join the "room2" and "room3" rooms + * myNamespace.in("room1").socketsJoin(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsJoin(room) { + return new broadcast_operator_1.BroadcastOperator(this.adapter).socketsJoin(room); + } + /** + * Makes the matching socket instances leave the specified rooms. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // make all socket instances leave the "room1" room + * myNamespace.socketsLeave("room1"); + * + * // make all socket instances in the "room1" room leave the "room2" and "room3" rooms + * myNamespace.in("room1").socketsLeave(["room2", "room3"]); + * + * @param room - a room, or an array of rooms + */ + socketsLeave(room) { + return new broadcast_operator_1.BroadcastOperator(this.adapter).socketsLeave(room); + } + /** + * Makes the matching socket instances disconnect. + * + * Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}. + * + * @example + * const myNamespace = io.of("/my-namespace"); + * + * // make all socket instances disconnect (the connections might be kept alive for other namespaces) + * myNamespace.disconnectSockets(); + * + * // make all socket instances in the "room1" room disconnect and close the underlying connections + * myNamespace.in("room1").disconnectSockets(true); + * + * @param close - whether to close the underlying connection + */ + disconnectSockets(close = false) { + return new broadcast_operator_1.BroadcastOperator(this.adapter).disconnectSockets(close); + } +} +exports.Namespace = Namespace; diff --git a/software/flow/node_modules/socket.io/dist/parent-namespace.d.ts b/software/flow/node_modules/socket.io/dist/parent-namespace.d.ts new file mode 100644 index 0000000..dcc9956 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/parent-namespace.d.ts @@ -0,0 +1,30 @@ +import { Namespace } from "./namespace"; +import type { Server, RemoteSocket } from "./index"; +import type { EventParams, EventNames, EventsMap, DefaultEventsMap } from "./typed-events"; +/** + * A parent namespace is a special {@link Namespace} that holds a list of child namespaces which were created either + * with a regular expression or with a function. + * + * @example + * const parentNamespace = io.of(/\/dynamic-\d+/); + * + * parentNamespace.on("connection", (socket) => { + * const childNamespace = socket.nsp; + * } + * + * // will reach all the clients that are in one of the child namespaces, like "/dynamic-101" + * parentNamespace.emit("hello", "world"); + * + */ +export declare class ParentNamespace extends Namespace { + private static count; + private children; + constructor(server: Server); + /** + * @private + */ + _initAdapter(): void; + emit>(ev: Ev, ...args: EventParams): boolean; + createChild(name: string): Namespace; + fetchSockets(): Promise[]>; +} diff --git a/software/flow/node_modules/socket.io/dist/parent-namespace.js b/software/flow/node_modules/socket.io/dist/parent-namespace.js new file mode 100644 index 0000000..52727d8 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/parent-namespace.js @@ -0,0 +1,82 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ParentNamespace = void 0; +const namespace_1 = require("./namespace"); +const debug_1 = __importDefault(require("debug")); +const debug = (0, debug_1.default)("socket.io:parent-namespace"); +/** + * A parent namespace is a special {@link Namespace} that holds a list of child namespaces which were created either + * with a regular expression or with a function. + * + * @example + * const parentNamespace = io.of(/\/dynamic-\d+/); + * + * parentNamespace.on("connection", (socket) => { + * const childNamespace = socket.nsp; + * } + * + * // will reach all the clients that are in one of the child namespaces, like "/dynamic-101" + * parentNamespace.emit("hello", "world"); + * + */ +class ParentNamespace extends namespace_1.Namespace { + constructor(server) { + super(server, "/_" + ParentNamespace.count++); + this.children = new Set(); + } + /** + * @private + */ + _initAdapter() { + const broadcast = (packet, opts) => { + this.children.forEach((nsp) => { + nsp.adapter.broadcast(packet, opts); + }); + }; + // @ts-ignore FIXME is there a way to declare an inner class in TypeScript? + this.adapter = { broadcast }; + } + emit(ev, ...args) { + this.children.forEach((nsp) => { + nsp.emit(ev, ...args); + }); + return true; + } + createChild(name) { + debug("creating child namespace %s", name); + const namespace = new namespace_1.Namespace(this.server, name); + namespace._fns = this._fns.slice(0); + this.listeners("connect").forEach((listener) => namespace.on("connect", listener)); + this.listeners("connection").forEach((listener) => namespace.on("connection", listener)); + this.children.add(namespace); + if (this.server._opts.cleanupEmptyChildNamespaces) { + const remove = namespace._remove; + namespace._remove = (socket) => { + remove.call(namespace, socket); + if (namespace.sockets.size === 0) { + debug("closing child namespace %s", name); + namespace.adapter.close(); + this.server._nsps.delete(namespace.name); + this.children.delete(namespace); + } + }; + } + this.server._nsps.set(name, namespace); + // @ts-ignore + this.server.sockets.emitReserved("new_namespace", namespace); + return namespace; + } + fetchSockets() { + // note: we could make the fetchSockets() method work for dynamic namespaces created with a regex (by sending the + // regex to the other Socket.IO servers, and returning the sockets of each matching namespace for example), but + // the behavior for namespaces created with a function is less clear + // note²: we cannot loop over each children namespace, because with multiple Socket.IO servers, a given namespace + // may exist on one node but not exist on another (since it is created upon client connection) + throw new Error("fetchSockets() is not supported on parent namespaces"); + } +} +exports.ParentNamespace = ParentNamespace; +ParentNamespace.count = 0; diff --git a/software/flow/node_modules/socket.io/dist/socket.d.ts b/software/flow/node_modules/socket.io/dist/socket.d.ts new file mode 100644 index 0000000..83fac2c --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/socket.d.ts @@ -0,0 +1,669 @@ +/// +/// +import { Packet } from "socket.io-parser"; +import { AllButLast, DecorateAcknowledgements, DecorateAcknowledgementsWithMultipleResponses, DefaultEventsMap, EventNames, EventParams, EventsMap, FirstArg, Last, StrictEventEmitter } from "./typed-events"; +import type { Client } from "./client"; +import type { Namespace } from "./namespace"; +import type { IncomingHttpHeaders, IncomingMessage } from "http"; +import type { Room, Session, SocketId } from "socket.io-adapter"; +import type { ParsedUrlQuery } from "querystring"; +import { BroadcastOperator } from "./broadcast-operator"; +export declare type DisconnectReason = "transport error" | "transport close" | "forced close" | "ping timeout" | "parse error" | "server shutting down" | "forced server close" | "client namespace disconnect" | "server namespace disconnect"; +export interface SocketReservedEventsMap { + disconnect: (reason: DisconnectReason, description?: any) => void; + disconnecting: (reason: DisconnectReason, description?: any) => void; + error: (err: Error) => void; +} +export interface EventEmitterReservedEventsMap { + newListener: (eventName: string | Symbol, listener: (...args: any[]) => void) => void; + removeListener: (eventName: string | Symbol, listener: (...args: any[]) => void) => void; +} +export declare const RESERVED_EVENTS: ReadonlySet; +/** + * The handshake details + */ +export interface Handshake { + /** + * The headers sent as part of the handshake + */ + headers: IncomingHttpHeaders; + /** + * The date of creation (as string) + */ + time: string; + /** + * The ip of the client + */ + address: string; + /** + * Whether the connection is cross-domain + */ + xdomain: boolean; + /** + * Whether the connection is secure + */ + secure: boolean; + /** + * The date of creation (as unix timestamp) + */ + issued: number; + /** + * The request URL string + */ + url: string; + /** + * The query object + */ + query: ParsedUrlQuery; + /** + * The auth object + */ + auth: { + [key: string]: any; + }; +} +/** + * `[eventName, ...args]` + */ +export declare type Event = [string, ...any[]]; +/** + * This is the main object for interacting with a client. + * + * A Socket belongs to a given {@link Namespace} and uses an underlying {@link Client} to communicate. + * + * Within each {@link Namespace}, you can also define arbitrary channels (called "rooms") that the {@link Socket} can + * join and leave. That provides a convenient way to broadcast to a group of socket instances. + * + * @example + * io.on("connection", (socket) => { + * console.log(`socket ${socket.id} connected`); + * + * // send an event to the client + * socket.emit("foo", "bar"); + * + * socket.on("foobar", () => { + * // an event was received from the client + * }); + * + * // join the room named "room1" + * socket.join("room1"); + * + * // broadcast to everyone in the room named "room1" + * io.to("room1").emit("hello"); + * + * // upon disconnection + * socket.on("disconnect", (reason) => { + * console.log(`socket ${socket.id} disconnected due to ${reason}`); + * }); + * }); + */ +export declare class Socket extends StrictEventEmitter { + readonly nsp: Namespace; + readonly client: Client; + /** + * An unique identifier for the session. + */ + readonly id: SocketId; + /** + * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will + * be transmitted to the client, the data attribute and the rooms will be restored. + */ + readonly recovered: boolean; + /** + * The handshake details. + */ + readonly handshake: Handshake; + /** + * Additional information that can be attached to the Socket instance and which will be used in the + * {@link Server.fetchSockets()} method. + */ + data: Partial; + /** + * Whether the socket is currently connected or not. + * + * @example + * io.use((socket, next) => { + * console.log(socket.connected); // false + * next(); + * }); + * + * io.on("connection", (socket) => { + * console.log(socket.connected); // true + * }); + */ + connected: boolean; + /** + * The session ID, which must not be shared (unlike {@link id}). + * + * @private + */ + private readonly pid; + private readonly server; + private readonly adapter; + private acks; + private fns; + private flags; + private _anyListeners?; + private _anyOutgoingListeners?; + /** + * Interface to a `Client` for a given `Namespace`. + * + * @param {Namespace} nsp + * @param {Client} client + * @param {Object} auth + * @package + */ + constructor(nsp: Namespace, client: Client, auth: Record, previousSession?: Session); + /** + * Builds the `handshake` BC object + * + * @private + */ + private buildHandshake; + /** + * Emits to this client. + * + * @example + * io.on("connection", (socket) => { + * socket.emit("hello", "world"); + * + * // all serializable datastructures are supported (no need to call JSON.stringify) + * socket.emit("hello", 1, "2", { 3: ["4"], 5: Buffer.from([6]) }); + * + * // with an acknowledgement from the client + * socket.emit("hello", "world", (val) => { + * // ... + * }); + * }); + * + * @return Always returns `true`. + */ + emit>(ev: Ev, ...args: EventParams): boolean; + /** + * Emits an event and waits for an acknowledgement + * + * @example + * io.on("connection", async (socket) => { + * // without timeout + * const response = await socket.emitWithAck("hello", "world"); + * + * // with a specific timeout + * try { + * const response = await socket.timeout(1000).emitWithAck("hello", "world"); + * } catch (err) { + * // the client did not acknowledge the event in the given delay + * } + * }); + * + * @return a Promise that will be fulfilled when the client acknowledges the event + */ + emitWithAck>(ev: Ev, ...args: AllButLast>): Promise>>>; + /** + * @private + */ + private registerAckCallback; + /** + * Targets a room when broadcasting. + * + * @example + * io.on("connection", (socket) => { + * // the “foo” event will be broadcast to all connected clients in the “room-101” room, except this socket + * socket.to("room-101").emit("foo", "bar"); + * + * // the code above is equivalent to: + * io.to("room-101").except(socket.id).emit("foo", "bar"); + * + * // with an array of rooms (a client will be notified at most once) + * socket.to(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * socket.to("room-101").to("room-102").emit("foo", "bar"); + * }); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + to(room: Room | Room[]): BroadcastOperator, SocketData>; + /** + * Targets a room when broadcasting. Similar to `to()`, but might feel clearer in some cases: + * + * @example + * io.on("connection", (socket) => { + * // disconnect all clients in the "room-101" room, except this socket + * socket.in("room-101").disconnectSockets(); + * }); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + in(room: Room | Room[]): BroadcastOperator, SocketData>; + /** + * Excludes a room when broadcasting. + * + * @example + * io.on("connection", (socket) => { + * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room + * // and this socket + * socket.except("room-101").emit("foo", "bar"); + * + * // with an array of rooms + * socket.except(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * socket.except("room-101").except("room-102").emit("foo", "bar"); + * }); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + except(room: Room | Room[]): BroadcastOperator, SocketData>; + /** + * Sends a `message` event. + * + * This method mimics the WebSocket.send() method. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send + * + * @example + * io.on("connection", (socket) => { + * socket.send("hello"); + * + * // this is equivalent to + * socket.emit("message", "hello"); + * }); + * + * @return self + */ + send(...args: EventParams): this; + /** + * Sends a `message` event. Alias of {@link send}. + * + * @return self + */ + write(...args: EventParams): this; + /** + * Writes a packet. + * + * @param {Object} packet - packet object + * @param {Object} opts - options + * @private + */ + private packet; + /** + * Joins a room. + * + * @example + * io.on("connection", (socket) => { + * // join a single room + * socket.join("room1"); + * + * // join multiple rooms + * socket.join(["room1", "room2"]); + * }); + * + * @param {String|Array} rooms - room or array of rooms + * @return a Promise or nothing, depending on the adapter + */ + join(rooms: Room | Array): Promise | void; + /** + * Leaves a room. + * + * @example + * io.on("connection", (socket) => { + * // leave a single room + * socket.leave("room1"); + * + * // leave multiple rooms + * socket.leave("room1").leave("room2"); + * }); + * + * @param {String} room + * @return a Promise or nothing, depending on the adapter + */ + leave(room: string): Promise | void; + /** + * Leave all rooms. + * + * @private + */ + private leaveAll; + /** + * Called by `Namespace` upon successful + * middleware execution (ie: authorization). + * Socket is added to namespace array before + * call to join, so adapters can access it. + * + * @private + */ + _onconnect(): void; + /** + * Called with each packet. Called by `Client`. + * + * @param {Object} packet + * @private + */ + _onpacket(packet: Packet): void; + /** + * Called upon event packet. + * + * @param {Packet} packet - packet object + * @private + */ + private onevent; + /** + * Produces an ack callback to emit with an event. + * + * @param {Number} id - packet id + * @private + */ + private ack; + /** + * Called upon ack packet. + * + * @private + */ + private onack; + /** + * Called upon client disconnect packet. + * + * @private + */ + private ondisconnect; + /** + * Handles a client error. + * + * @private + */ + _onerror(err: Error): void; + /** + * Called upon closing. Called by `Client`. + * + * @param {String} reason + * @param description + * @throw {Error} optional error object + * + * @private + */ + _onclose(reason: DisconnectReason, description?: any): this | undefined; + /** + * Makes the socket leave all the rooms it was part of and prevents it from joining any other room + * + * @private + */ + _cleanup(): void; + /** + * Produces an `error` packet. + * + * @param {Object} err - error object + * + * @private + */ + _error(err: any): void; + /** + * Disconnects this client. + * + * @example + * io.on("connection", (socket) => { + * // disconnect this socket (the connection might be kept alive for other namespaces) + * socket.disconnect(); + * + * // disconnect this socket and close the underlying connection + * socket.disconnect(true); + * }) + * + * @param {Boolean} close - if `true`, closes the underlying connection + * @return self + */ + disconnect(close?: boolean): this; + /** + * Sets the compress flag. + * + * @example + * io.on("connection", (socket) => { + * socket.compress(false).emit("hello"); + * }); + * + * @param {Boolean} compress - if `true`, compresses the sending data + * @return {Socket} self + */ + compress(compress: boolean): this; + /** + * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to + * receive messages (because of network slowness or other issues, or because they’re connected through long polling + * and is in the middle of a request-response cycle). + * + * @example + * io.on("connection", (socket) => { + * socket.volatile.emit("hello"); // the client may or may not receive it + * }); + * + * @return {Socket} self + */ + get volatile(): this; + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the + * sender. + * + * @example + * io.on("connection", (socket) => { + * // the “foo” event will be broadcast to all connected clients, except this socket + * socket.broadcast.emit("foo", "bar"); + * }); + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get broadcast(): BroadcastOperator, SocketData>; + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node. + * + * @example + * io.on("connection", (socket) => { + * // the “foo” event will be broadcast to all connected clients on this node, except this socket + * socket.local.emit("foo", "bar"); + * }); + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get local(): BroadcastOperator, SocketData>; + /** + * Sets a modifier for a subsequent event emission that the callback will be called with an error when the + * given number of milliseconds have elapsed without an acknowledgement from the client: + * + * @example + * io.on("connection", (socket) => { + * socket.timeout(5000).emit("my-event", (err) => { + * if (err) { + * // the client did not acknowledge the event in the given delay + * } + * }); + * }); + * + * @returns self + */ + timeout(timeout: number): Socket, ServerSideEvents, SocketData>; + /** + * Dispatch incoming event to socket listeners. + * + * @param {Array} event - event that will get emitted + * @private + */ + private dispatch; + /** + * Sets up socket middleware. + * + * @example + * io.on("connection", (socket) => { + * socket.use(([event, ...args], next) => { + * if (isUnauthorized(event)) { + * return next(new Error("unauthorized event")); + * } + * // do not forget to call next + * next(); + * }); + * + * socket.on("error", (err) => { + * if (err && err.message === "unauthorized event") { + * socket.disconnect(); + * } + * }); + * }); + * + * @param {Function} fn - middleware function (event, next) + * @return {Socket} self + */ + use(fn: (event: Event, next: (err?: Error) => void) => void): this; + /** + * Executes the middleware for an incoming event. + * + * @param {Array} event - event that will get emitted + * @param {Function} fn - last fn call in the middleware + * @private + */ + private run; + /** + * Whether the socket is currently disconnected + */ + get disconnected(): boolean; + /** + * A reference to the request that originated the underlying Engine.IO Socket. + */ + get request(): IncomingMessage; + /** + * A reference to the underlying Client transport connection (Engine.IO Socket object). + * + * @example + * io.on("connection", (socket) => { + * console.log(socket.conn.transport.name); // prints "polling" or "websocket" + * + * socket.conn.once("upgrade", () => { + * console.log(socket.conn.transport.name); // prints "websocket" + * }); + * }); + */ + get conn(): import("engine.io").Socket; + /** + * Returns the rooms the socket is currently in. + * + * @example + * io.on("connection", (socket) => { + * console.log(socket.rooms); // Set { } + * + * socket.join("room1"); + * + * console.log(socket.rooms); // Set { , "room1" } + * }); + */ + get rooms(): Set; + /** + * Adds a listener that will be fired when any event is received. The event name is passed as the first argument to + * the callback. + * + * @example + * io.on("connection", (socket) => { + * socket.onAny((event, ...args) => { + * console.log(`got event ${event}`); + * }); + * }); + * + * @param listener + */ + onAny(listener: (...args: any[]) => void): this; + /** + * Adds a listener that will be fired when any event is received. The event name is passed as the first argument to + * the callback. The listener is added to the beginning of the listeners array. + * + * @param listener + */ + prependAny(listener: (...args: any[]) => void): this; + /** + * Removes the listener that will be fired when any event is received. + * + * @example + * io.on("connection", (socket) => { + * const catchAllListener = (event, ...args) => { + * console.log(`got event ${event}`); + * } + * + * socket.onAny(catchAllListener); + * + * // remove a specific listener + * socket.offAny(catchAllListener); + * + * // or remove all listeners + * socket.offAny(); + * }); + * + * @param listener + */ + offAny(listener?: (...args: any[]) => void): this; + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + */ + listenersAny(): ((...args: any[]) => void)[]; + /** + * Adds a listener that will be fired when any event is sent. The event name is passed as the first argument to + * the callback. + * + * Note: acknowledgements sent to the client are not included. + * + * @example + * io.on("connection", (socket) => { + * socket.onAnyOutgoing((event, ...args) => { + * console.log(`sent event ${event}`); + * }); + * }); + * + * @param listener + */ + onAnyOutgoing(listener: (...args: any[]) => void): this; + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @example + * io.on("connection", (socket) => { + * socket.prependAnyOutgoing((event, ...args) => { + * console.log(`sent event ${event}`); + * }); + * }); + * + * @param listener + */ + prependAnyOutgoing(listener: (...args: any[]) => void): this; + /** + * Removes the listener that will be fired when any event is sent. + * + * @example + * io.on("connection", (socket) => { + * const catchAllListener = (event, ...args) => { + * console.log(`sent event ${event}`); + * } + * + * socket.onAnyOutgoing(catchAllListener); + * + * // remove a specific listener + * socket.offAnyOutgoing(catchAllListener); + * + * // or remove all listeners + * socket.offAnyOutgoing(); + * }); + * + * @param listener - the catch-all listener + */ + offAnyOutgoing(listener?: (...args: any[]) => void): this; + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + */ + listenersAnyOutgoing(): ((...args: any[]) => void)[]; + /** + * Notify the listeners for each packet sent (emit or broadcast) + * + * @param packet + * + * @private + */ + private notifyOutgoingListeners; + private newBroadcastOperator; +} diff --git a/software/flow/node_modules/socket.io/dist/socket.js b/software/flow/node_modules/socket.io/dist/socket.js new file mode 100644 index 0000000..6f5ac29 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/socket.js @@ -0,0 +1,983 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Socket = exports.RESERVED_EVENTS = void 0; +const socket_io_parser_1 = require("socket.io-parser"); +const debug_1 = __importDefault(require("debug")); +const typed_events_1 = require("./typed-events"); +const base64id_1 = __importDefault(require("base64id")); +const broadcast_operator_1 = require("./broadcast-operator"); +const debug = (0, debug_1.default)("socket.io:socket"); +const RECOVERABLE_DISCONNECT_REASONS = new Set([ + "transport error", + "transport close", + "forced close", + "ping timeout", + "server shutting down", + "forced server close", +]); +exports.RESERVED_EVENTS = new Set([ + "connect", + "connect_error", + "disconnect", + "disconnecting", + "newListener", + "removeListener", +]); +function noop() { } +/** + * This is the main object for interacting with a client. + * + * A Socket belongs to a given {@link Namespace} and uses an underlying {@link Client} to communicate. + * + * Within each {@link Namespace}, you can also define arbitrary channels (called "rooms") that the {@link Socket} can + * join and leave. That provides a convenient way to broadcast to a group of socket instances. + * + * @example + * io.on("connection", (socket) => { + * console.log(`socket ${socket.id} connected`); + * + * // send an event to the client + * socket.emit("foo", "bar"); + * + * socket.on("foobar", () => { + * // an event was received from the client + * }); + * + * // join the room named "room1" + * socket.join("room1"); + * + * // broadcast to everyone in the room named "room1" + * io.to("room1").emit("hello"); + * + * // upon disconnection + * socket.on("disconnect", (reason) => { + * console.log(`socket ${socket.id} disconnected due to ${reason}`); + * }); + * }); + */ +class Socket extends typed_events_1.StrictEventEmitter { + /** + * Interface to a `Client` for a given `Namespace`. + * + * @param {Namespace} nsp + * @param {Client} client + * @param {Object} auth + * @package + */ + constructor(nsp, client, auth, previousSession) { + super(); + this.nsp = nsp; + this.client = client; + /** + * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will + * be transmitted to the client, the data attribute and the rooms will be restored. + */ + this.recovered = false; + /** + * Additional information that can be attached to the Socket instance and which will be used in the + * {@link Server.fetchSockets()} method. + */ + this.data = {}; + /** + * Whether the socket is currently connected or not. + * + * @example + * io.use((socket, next) => { + * console.log(socket.connected); // false + * next(); + * }); + * + * io.on("connection", (socket) => { + * console.log(socket.connected); // true + * }); + */ + this.connected = false; + this.acks = new Map(); + this.fns = []; + this.flags = {}; + this.server = nsp.server; + this.adapter = this.nsp.adapter; + if (previousSession) { + this.id = previousSession.sid; + this.pid = previousSession.pid; + previousSession.rooms.forEach((room) => this.join(room)); + this.data = previousSession.data; + previousSession.missedPackets.forEach((packet) => { + this.packet({ + type: socket_io_parser_1.PacketType.EVENT, + data: packet, + }); + }); + this.recovered = true; + } + else { + if (client.conn.protocol === 3) { + // @ts-ignore + this.id = nsp.name !== "/" ? nsp.name + "#" + client.id : client.id; + } + else { + this.id = base64id_1.default.generateId(); // don't reuse the Engine.IO id because it's sensitive information + } + if (this.server._opts.connectionStateRecovery) { + this.pid = base64id_1.default.generateId(); + } + } + this.handshake = this.buildHandshake(auth); + } + /** + * Builds the `handshake` BC object + * + * @private + */ + buildHandshake(auth) { + return { + headers: this.request.headers, + time: new Date() + "", + address: this.conn.remoteAddress, + xdomain: !!this.request.headers.origin, + // @ts-ignore + secure: !!this.request.connection.encrypted, + issued: +new Date(), + url: this.request.url, + // @ts-ignore + query: this.request._query, + auth, + }; + } + /** + * Emits to this client. + * + * @example + * io.on("connection", (socket) => { + * socket.emit("hello", "world"); + * + * // all serializable datastructures are supported (no need to call JSON.stringify) + * socket.emit("hello", 1, "2", { 3: ["4"], 5: Buffer.from([6]) }); + * + * // with an acknowledgement from the client + * socket.emit("hello", "world", (val) => { + * // ... + * }); + * }); + * + * @return Always returns `true`. + */ + emit(ev, ...args) { + if (exports.RESERVED_EVENTS.has(ev)) { + throw new Error(`"${String(ev)}" is a reserved event name`); + } + const data = [ev, ...args]; + const packet = { + type: socket_io_parser_1.PacketType.EVENT, + data: data, + }; + // access last argument to see if it's an ACK callback + if (typeof data[data.length - 1] === "function") { + const id = this.nsp._ids++; + debug("emitting packet with ack id %d", id); + this.registerAckCallback(id, data.pop()); + packet.id = id; + } + const flags = Object.assign({}, this.flags); + this.flags = {}; + // @ts-ignore + if (this.nsp.server.opts.connectionStateRecovery) { + // this ensures the packet is stored and can be transmitted upon reconnection + this.adapter.broadcast(packet, { + rooms: new Set([this.id]), + except: new Set(), + flags, + }); + } + else { + this.notifyOutgoingListeners(packet); + this.packet(packet, flags); + } + return true; + } + /** + * Emits an event and waits for an acknowledgement + * + * @example + * io.on("connection", async (socket) => { + * // without timeout + * const response = await socket.emitWithAck("hello", "world"); + * + * // with a specific timeout + * try { + * const response = await socket.timeout(1000).emitWithAck("hello", "world"); + * } catch (err) { + * // the client did not acknowledge the event in the given delay + * } + * }); + * + * @return a Promise that will be fulfilled when the client acknowledges the event + */ + emitWithAck(ev, ...args) { + // the timeout flag is optional + const withErr = this.flags.timeout !== undefined; + return new Promise((resolve, reject) => { + args.push((arg1, arg2) => { + if (withErr) { + return arg1 ? reject(arg1) : resolve(arg2); + } + else { + return resolve(arg1); + } + }); + this.emit(ev, ...args); + }); + } + /** + * @private + */ + registerAckCallback(id, ack) { + const timeout = this.flags.timeout; + if (timeout === undefined) { + this.acks.set(id, ack); + return; + } + const timer = setTimeout(() => { + debug("event with ack id %d has timed out after %d ms", id, timeout); + this.acks.delete(id); + ack.call(this, new Error("operation has timed out")); + }, timeout); + this.acks.set(id, (...args) => { + clearTimeout(timer); + ack.apply(this, [null, ...args]); + }); + } + /** + * Targets a room when broadcasting. + * + * @example + * io.on("connection", (socket) => { + * // the “foo” event will be broadcast to all connected clients in the “room-101” room, except this socket + * socket.to("room-101").emit("foo", "bar"); + * + * // the code above is equivalent to: + * io.to("room-101").except(socket.id).emit("foo", "bar"); + * + * // with an array of rooms (a client will be notified at most once) + * socket.to(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * socket.to("room-101").to("room-102").emit("foo", "bar"); + * }); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + to(room) { + return this.newBroadcastOperator().to(room); + } + /** + * Targets a room when broadcasting. Similar to `to()`, but might feel clearer in some cases: + * + * @example + * io.on("connection", (socket) => { + * // disconnect all clients in the "room-101" room, except this socket + * socket.in("room-101").disconnectSockets(); + * }); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + in(room) { + return this.newBroadcastOperator().in(room); + } + /** + * Excludes a room when broadcasting. + * + * @example + * io.on("connection", (socket) => { + * // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room + * // and this socket + * socket.except("room-101").emit("foo", "bar"); + * + * // with an array of rooms + * socket.except(["room-101", "room-102"]).emit("foo", "bar"); + * + * // with multiple chained calls + * socket.except("room-101").except("room-102").emit("foo", "bar"); + * }); + * + * @param room - a room, or an array of rooms + * @return a new {@link BroadcastOperator} instance for chaining + */ + except(room) { + return this.newBroadcastOperator().except(room); + } + /** + * Sends a `message` event. + * + * This method mimics the WebSocket.send() method. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send + * + * @example + * io.on("connection", (socket) => { + * socket.send("hello"); + * + * // this is equivalent to + * socket.emit("message", "hello"); + * }); + * + * @return self + */ + send(...args) { + this.emit("message", ...args); + return this; + } + /** + * Sends a `message` event. Alias of {@link send}. + * + * @return self + */ + write(...args) { + this.emit("message", ...args); + return this; + } + /** + * Writes a packet. + * + * @param {Object} packet - packet object + * @param {Object} opts - options + * @private + */ + packet(packet, opts = {}) { + packet.nsp = this.nsp.name; + opts.compress = false !== opts.compress; + this.client._packet(packet, opts); + } + /** + * Joins a room. + * + * @example + * io.on("connection", (socket) => { + * // join a single room + * socket.join("room1"); + * + * // join multiple rooms + * socket.join(["room1", "room2"]); + * }); + * + * @param {String|Array} rooms - room or array of rooms + * @return a Promise or nothing, depending on the adapter + */ + join(rooms) { + debug("join room %s", rooms); + return this.adapter.addAll(this.id, new Set(Array.isArray(rooms) ? rooms : [rooms])); + } + /** + * Leaves a room. + * + * @example + * io.on("connection", (socket) => { + * // leave a single room + * socket.leave("room1"); + * + * // leave multiple rooms + * socket.leave("room1").leave("room2"); + * }); + * + * @param {String} room + * @return a Promise or nothing, depending on the adapter + */ + leave(room) { + debug("leave room %s", room); + return this.adapter.del(this.id, room); + } + /** + * Leave all rooms. + * + * @private + */ + leaveAll() { + this.adapter.delAll(this.id); + } + /** + * Called by `Namespace` upon successful + * middleware execution (ie: authorization). + * Socket is added to namespace array before + * call to join, so adapters can access it. + * + * @private + */ + _onconnect() { + debug("socket connected - writing packet"); + this.connected = true; + this.join(this.id); + if (this.conn.protocol === 3) { + this.packet({ type: socket_io_parser_1.PacketType.CONNECT }); + } + else { + this.packet({ + type: socket_io_parser_1.PacketType.CONNECT, + data: { sid: this.id, pid: this.pid }, + }); + } + } + /** + * Called with each packet. Called by `Client`. + * + * @param {Object} packet + * @private + */ + _onpacket(packet) { + debug("got packet %j", packet); + switch (packet.type) { + case socket_io_parser_1.PacketType.EVENT: + this.onevent(packet); + break; + case socket_io_parser_1.PacketType.BINARY_EVENT: + this.onevent(packet); + break; + case socket_io_parser_1.PacketType.ACK: + this.onack(packet); + break; + case socket_io_parser_1.PacketType.BINARY_ACK: + this.onack(packet); + break; + case socket_io_parser_1.PacketType.DISCONNECT: + this.ondisconnect(); + break; + } + } + /** + * Called upon event packet. + * + * @param {Packet} packet - packet object + * @private + */ + onevent(packet) { + const args = packet.data || []; + debug("emitting event %j", args); + if (null != packet.id) { + debug("attaching ack callback to event"); + args.push(this.ack(packet.id)); + } + if (this._anyListeners && this._anyListeners.length) { + const listeners = this._anyListeners.slice(); + for (const listener of listeners) { + listener.apply(this, args); + } + } + this.dispatch(args); + } + /** + * Produces an ack callback to emit with an event. + * + * @param {Number} id - packet id + * @private + */ + ack(id) { + const self = this; + let sent = false; + return function () { + // prevent double callbacks + if (sent) + return; + const args = Array.prototype.slice.call(arguments); + debug("sending ack %j", args); + self.packet({ + id: id, + type: socket_io_parser_1.PacketType.ACK, + data: args, + }); + sent = true; + }; + } + /** + * Called upon ack packet. + * + * @private + */ + onack(packet) { + const ack = this.acks.get(packet.id); + if ("function" == typeof ack) { + debug("calling ack %s with %j", packet.id, packet.data); + ack.apply(this, packet.data); + this.acks.delete(packet.id); + } + else { + debug("bad ack %s", packet.id); + } + } + /** + * Called upon client disconnect packet. + * + * @private + */ + ondisconnect() { + debug("got disconnect packet"); + this._onclose("client namespace disconnect"); + } + /** + * Handles a client error. + * + * @private + */ + _onerror(err) { + if (this.listeners("error").length) { + this.emitReserved("error", err); + } + else { + console.error("Missing error handler on `socket`."); + console.error(err.stack); + } + } + /** + * Called upon closing. Called by `Client`. + * + * @param {String} reason + * @param description + * @throw {Error} optional error object + * + * @private + */ + _onclose(reason, description) { + if (!this.connected) + return this; + debug("closing socket - reason %s", reason); + this.emitReserved("disconnecting", reason, description); + if (this.server._opts.connectionStateRecovery && + RECOVERABLE_DISCONNECT_REASONS.has(reason)) { + debug("connection state recovery is enabled for sid %s", this.id); + this.adapter.persistSession({ + sid: this.id, + pid: this.pid, + rooms: [...this.rooms], + data: this.data, + }); + } + this._cleanup(); + this.nsp._remove(this); + this.client._remove(this); + this.connected = false; + this.emitReserved("disconnect", reason, description); + return; + } + /** + * Makes the socket leave all the rooms it was part of and prevents it from joining any other room + * + * @private + */ + _cleanup() { + this.leaveAll(); + this.join = noop; + } + /** + * Produces an `error` packet. + * + * @param {Object} err - error object + * + * @private + */ + _error(err) { + this.packet({ type: socket_io_parser_1.PacketType.CONNECT_ERROR, data: err }); + } + /** + * Disconnects this client. + * + * @example + * io.on("connection", (socket) => { + * // disconnect this socket (the connection might be kept alive for other namespaces) + * socket.disconnect(); + * + * // disconnect this socket and close the underlying connection + * socket.disconnect(true); + * }) + * + * @param {Boolean} close - if `true`, closes the underlying connection + * @return self + */ + disconnect(close = false) { + if (!this.connected) + return this; + if (close) { + this.client._disconnect(); + } + else { + this.packet({ type: socket_io_parser_1.PacketType.DISCONNECT }); + this._onclose("server namespace disconnect"); + } + return this; + } + /** + * Sets the compress flag. + * + * @example + * io.on("connection", (socket) => { + * socket.compress(false).emit("hello"); + * }); + * + * @param {Boolean} compress - if `true`, compresses the sending data + * @return {Socket} self + */ + compress(compress) { + this.flags.compress = compress; + return this; + } + /** + * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to + * receive messages (because of network slowness or other issues, or because they’re connected through long polling + * and is in the middle of a request-response cycle). + * + * @example + * io.on("connection", (socket) => { + * socket.volatile.emit("hello"); // the client may or may not receive it + * }); + * + * @return {Socket} self + */ + get volatile() { + this.flags.volatile = true; + return this; + } + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the + * sender. + * + * @example + * io.on("connection", (socket) => { + * // the “foo” event will be broadcast to all connected clients, except this socket + * socket.broadcast.emit("foo", "bar"); + * }); + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get broadcast() { + return this.newBroadcastOperator(); + } + /** + * Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node. + * + * @example + * io.on("connection", (socket) => { + * // the “foo” event will be broadcast to all connected clients on this node, except this socket + * socket.local.emit("foo", "bar"); + * }); + * + * @return a new {@link BroadcastOperator} instance for chaining + */ + get local() { + return this.newBroadcastOperator().local; + } + /** + * Sets a modifier for a subsequent event emission that the callback will be called with an error when the + * given number of milliseconds have elapsed without an acknowledgement from the client: + * + * @example + * io.on("connection", (socket) => { + * socket.timeout(5000).emit("my-event", (err) => { + * if (err) { + * // the client did not acknowledge the event in the given delay + * } + * }); + * }); + * + * @returns self + */ + timeout(timeout) { + this.flags.timeout = timeout; + return this; + } + /** + * Dispatch incoming event to socket listeners. + * + * @param {Array} event - event that will get emitted + * @private + */ + dispatch(event) { + debug("dispatching an event %j", event); + this.run(event, (err) => { + process.nextTick(() => { + if (err) { + return this._onerror(err); + } + if (this.connected) { + super.emitUntyped.apply(this, event); + } + else { + debug("ignore packet received after disconnection"); + } + }); + }); + } + /** + * Sets up socket middleware. + * + * @example + * io.on("connection", (socket) => { + * socket.use(([event, ...args], next) => { + * if (isUnauthorized(event)) { + * return next(new Error("unauthorized event")); + * } + * // do not forget to call next + * next(); + * }); + * + * socket.on("error", (err) => { + * if (err && err.message === "unauthorized event") { + * socket.disconnect(); + * } + * }); + * }); + * + * @param {Function} fn - middleware function (event, next) + * @return {Socket} self + */ + use(fn) { + this.fns.push(fn); + return this; + } + /** + * Executes the middleware for an incoming event. + * + * @param {Array} event - event that will get emitted + * @param {Function} fn - last fn call in the middleware + * @private + */ + run(event, fn) { + const fns = this.fns.slice(0); + if (!fns.length) + return fn(null); + function run(i) { + fns[i](event, function (err) { + // upon error, short-circuit + if (err) + return fn(err); + // if no middleware left, summon callback + if (!fns[i + 1]) + return fn(null); + // go on to next + run(i + 1); + }); + } + run(0); + } + /** + * Whether the socket is currently disconnected + */ + get disconnected() { + return !this.connected; + } + /** + * A reference to the request that originated the underlying Engine.IO Socket. + */ + get request() { + return this.client.request; + } + /** + * A reference to the underlying Client transport connection (Engine.IO Socket object). + * + * @example + * io.on("connection", (socket) => { + * console.log(socket.conn.transport.name); // prints "polling" or "websocket" + * + * socket.conn.once("upgrade", () => { + * console.log(socket.conn.transport.name); // prints "websocket" + * }); + * }); + */ + get conn() { + return this.client.conn; + } + /** + * Returns the rooms the socket is currently in. + * + * @example + * io.on("connection", (socket) => { + * console.log(socket.rooms); // Set { } + * + * socket.join("room1"); + * + * console.log(socket.rooms); // Set { , "room1" } + * }); + */ + get rooms() { + return this.adapter.socketRooms(this.id) || new Set(); + } + /** + * Adds a listener that will be fired when any event is received. The event name is passed as the first argument to + * the callback. + * + * @example + * io.on("connection", (socket) => { + * socket.onAny((event, ...args) => { + * console.log(`got event ${event}`); + * }); + * }); + * + * @param listener + */ + onAny(listener) { + this._anyListeners = this._anyListeners || []; + this._anyListeners.push(listener); + return this; + } + /** + * Adds a listener that will be fired when any event is received. The event name is passed as the first argument to + * the callback. The listener is added to the beginning of the listeners array. + * + * @param listener + */ + prependAny(listener) { + this._anyListeners = this._anyListeners || []; + this._anyListeners.unshift(listener); + return this; + } + /** + * Removes the listener that will be fired when any event is received. + * + * @example + * io.on("connection", (socket) => { + * const catchAllListener = (event, ...args) => { + * console.log(`got event ${event}`); + * } + * + * socket.onAny(catchAllListener); + * + * // remove a specific listener + * socket.offAny(catchAllListener); + * + * // or remove all listeners + * socket.offAny(); + * }); + * + * @param listener + */ + offAny(listener) { + if (!this._anyListeners) { + return this; + } + if (listener) { + const listeners = this._anyListeners; + for (let i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + return this; + } + } + } + else { + this._anyListeners = []; + } + return this; + } + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + */ + listenersAny() { + return this._anyListeners || []; + } + /** + * Adds a listener that will be fired when any event is sent. The event name is passed as the first argument to + * the callback. + * + * Note: acknowledgements sent to the client are not included. + * + * @example + * io.on("connection", (socket) => { + * socket.onAnyOutgoing((event, ...args) => { + * console.log(`sent event ${event}`); + * }); + * }); + * + * @param listener + */ + onAnyOutgoing(listener) { + this._anyOutgoingListeners = this._anyOutgoingListeners || []; + this._anyOutgoingListeners.push(listener); + return this; + } + /** + * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the + * callback. The listener is added to the beginning of the listeners array. + * + * @example + * io.on("connection", (socket) => { + * socket.prependAnyOutgoing((event, ...args) => { + * console.log(`sent event ${event}`); + * }); + * }); + * + * @param listener + */ + prependAnyOutgoing(listener) { + this._anyOutgoingListeners = this._anyOutgoingListeners || []; + this._anyOutgoingListeners.unshift(listener); + return this; + } + /** + * Removes the listener that will be fired when any event is sent. + * + * @example + * io.on("connection", (socket) => { + * const catchAllListener = (event, ...args) => { + * console.log(`sent event ${event}`); + * } + * + * socket.onAnyOutgoing(catchAllListener); + * + * // remove a specific listener + * socket.offAnyOutgoing(catchAllListener); + * + * // or remove all listeners + * socket.offAnyOutgoing(); + * }); + * + * @param listener - the catch-all listener + */ + offAnyOutgoing(listener) { + if (!this._anyOutgoingListeners) { + return this; + } + if (listener) { + const listeners = this._anyOutgoingListeners; + for (let i = 0; i < listeners.length; i++) { + if (listener === listeners[i]) { + listeners.splice(i, 1); + return this; + } + } + } + else { + this._anyOutgoingListeners = []; + } + return this; + } + /** + * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, + * e.g. to remove listeners. + */ + listenersAnyOutgoing() { + return this._anyOutgoingListeners || []; + } + /** + * Notify the listeners for each packet sent (emit or broadcast) + * + * @param packet + * + * @private + */ + notifyOutgoingListeners(packet) { + if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) { + const listeners = this._anyOutgoingListeners.slice(); + for (const listener of listeners) { + listener.apply(this, packet.data); + } + } + } + newBroadcastOperator() { + const flags = Object.assign({}, this.flags); + this.flags = {}; + return new broadcast_operator_1.BroadcastOperator(this.adapter, new Set(), new Set([this.id]), flags); + } +} +exports.Socket = Socket; diff --git a/software/flow/node_modules/socket.io/dist/typed-events.d.ts b/software/flow/node_modules/socket.io/dist/typed-events.d.ts new file mode 100644 index 0000000..86bd1b2 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/typed-events.d.ts @@ -0,0 +1,148 @@ +/// +import { EventEmitter } from "events"; +/** + * An events map is an interface that maps event names to their value, which + * represents the type of the `on` listener. + */ +export interface EventsMap { + [event: string]: any; +} +/** + * The default events map, used if no EventsMap is given. Using this EventsMap + * is equivalent to accepting all event names, and any data. + */ +export interface DefaultEventsMap { + [event: string]: (...args: any[]) => void; +} +/** + * Returns a union type containing all the keys of an event map. + */ +export declare type EventNames = keyof Map & (string | symbol); +/** The tuple type representing the parameters of an event listener */ +export declare type EventParams> = Parameters; +/** + * The event names that are either in ReservedEvents or in UserEvents + */ +export declare type ReservedOrUserEventNames = EventNames | EventNames; +/** + * Type of a listener of a user event or a reserved event. If `Ev` is in + * `ReservedEvents`, the reserved event listener is returned. + */ +export declare type ReservedOrUserListener> = FallbackToUntypedListener ? ReservedEvents[Ev] : Ev extends EventNames ? UserEvents[Ev] : never>; +/** + * Returns an untyped listener type if `T` is `never`; otherwise, returns `T`. + * + * This is a hack to mitigate https://github.com/socketio/socket.io/issues/3833. + * Needed because of https://github.com/microsoft/TypeScript/issues/41778 + */ +declare type FallbackToUntypedListener = [T] extends [never] ? (...args: any[]) => void | Promise : T; +/** + * Interface for classes that aren't `EventEmitter`s, but still expose a + * strictly typed `emit` method. + */ +export interface TypedEventBroadcaster { + emit>(ev: Ev, ...args: EventParams): boolean; +} +/** + * Strictly typed version of an `EventEmitter`. A `TypedEventEmitter` takes type + * parameters for mappings of event names to event data types, and strictly + * types method calls to the `EventEmitter` according to these event maps. + * + * @typeParam ListenEvents - `EventsMap` of user-defined events that can be + * listened to with `on` or `once` + * @typeParam EmitEvents - `EventsMap` of user-defined events that can be + * emitted with `emit` + * @typeParam ReservedEvents - `EventsMap` of reserved events, that can be + * emitted by socket.io with `emitReserved`, and can be listened to with + * `listen`. + */ +export declare abstract class StrictEventEmitter extends EventEmitter implements TypedEventBroadcaster { + /** + * Adds the `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + on>(ev: Ev, listener: ReservedOrUserListener): this; + /** + * Adds a one-time `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + once>(ev: Ev, listener: ReservedOrUserListener): this; + /** + * Emits an event. + * + * @param ev Name of the event + * @param args Values to send to listeners of this event + */ + emit>(ev: Ev, ...args: EventParams): boolean; + /** + * Emits a reserved event. + * + * This method is `protected`, so that only a class extending + * `StrictEventEmitter` can emit its own reserved events. + * + * @param ev Reserved event name + * @param args Arguments to emit along with the event + */ + protected emitReserved>(ev: Ev, ...args: EventParams): boolean; + /** + * Emits an event. + * + * This method is `protected`, so that only a class extending + * `StrictEventEmitter` can get around the strict typing. This is useful for + * calling `emit.apply`, which can be called as `emitUntyped.apply`. + * + * @param ev Event name + * @param args Arguments to emit along with the event + */ + protected emitUntyped(ev: string, ...args: any[]): boolean; + /** + * Returns the listeners listening to an event. + * + * @param event Event name + * @returns Array of listeners subscribed to `event` + */ + listeners>(event: Ev): ReservedOrUserListener[]; +} +export declare type Last = T extends [...infer H, infer L] ? L : any; +export declare type AllButLast = T extends [...infer H, infer L] ? H : any[]; +export declare type FirstArg = T extends (arg: infer Param) => infer Result ? Param : any; +export declare type SecondArg = T extends (err: Error, arg: infer Param) => infer Result ? Param : any; +declare type PrependTimeoutError = { + [K in keyof T]: T[K] extends (...args: infer Params) => infer Result ? (err: Error, ...args: Params) => Result : T[K]; +}; +declare type ExpectMultipleResponses = { + [K in keyof T]: T[K] extends (err: Error, arg: infer Param) => infer Result ? (err: Error, arg: Param[]) => Result : T[K]; +}; +/** + * Utility type to decorate the acknowledgement callbacks with a timeout error. + * + * This is needed because the timeout() flag breaks the symmetry between the sender and the receiver: + * + * @example + * interface Events { + * "my-event": (val: string) => void; + * } + * + * socket.on("my-event", (cb) => { + * cb("123"); // one single argument here + * }); + * + * socket.timeout(1000).emit("my-event", (err, val) => { + * // two arguments there (the "err" argument is not properly typed) + * }); + * + */ +export declare type DecorateAcknowledgements = { + [K in keyof E]: E[K] extends (...args: infer Params) => infer Result ? (...args: PrependTimeoutError) => Result : E[K]; +}; +export declare type DecorateAcknowledgementsWithTimeoutAndMultipleResponses = { + [K in keyof E]: E[K] extends (...args: infer Params) => infer Result ? (...args: ExpectMultipleResponses>) => Result : E[K]; +}; +export declare type DecorateAcknowledgementsWithMultipleResponses = { + [K in keyof E]: E[K] extends (...args: infer Params) => infer Result ? (...args: ExpectMultipleResponses) => Result : E[K]; +}; +export {}; diff --git a/software/flow/node_modules/socket.io/dist/typed-events.js b/software/flow/node_modules/socket.io/dist/typed-events.js new file mode 100644 index 0000000..f0526cf --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/typed-events.js @@ -0,0 +1,81 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StrictEventEmitter = void 0; +const events_1 = require("events"); +/** + * Strictly typed version of an `EventEmitter`. A `TypedEventEmitter` takes type + * parameters for mappings of event names to event data types, and strictly + * types method calls to the `EventEmitter` according to these event maps. + * + * @typeParam ListenEvents - `EventsMap` of user-defined events that can be + * listened to with `on` or `once` + * @typeParam EmitEvents - `EventsMap` of user-defined events that can be + * emitted with `emit` + * @typeParam ReservedEvents - `EventsMap` of reserved events, that can be + * emitted by socket.io with `emitReserved`, and can be listened to with + * `listen`. + */ +class StrictEventEmitter extends events_1.EventEmitter { + /** + * Adds the `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + on(ev, listener) { + return super.on(ev, listener); + } + /** + * Adds a one-time `listener` function as an event listener for `ev`. + * + * @param ev Name of the event + * @param listener Callback function + */ + once(ev, listener) { + return super.once(ev, listener); + } + /** + * Emits an event. + * + * @param ev Name of the event + * @param args Values to send to listeners of this event + */ + emit(ev, ...args) { + return super.emit(ev, ...args); + } + /** + * Emits a reserved event. + * + * This method is `protected`, so that only a class extending + * `StrictEventEmitter` can emit its own reserved events. + * + * @param ev Reserved event name + * @param args Arguments to emit along with the event + */ + emitReserved(ev, ...args) { + return super.emit(ev, ...args); + } + /** + * Emits an event. + * + * This method is `protected`, so that only a class extending + * `StrictEventEmitter` can get around the strict typing. This is useful for + * calling `emit.apply`, which can be called as `emitUntyped.apply`. + * + * @param ev Event name + * @param args Arguments to emit along with the event + */ + emitUntyped(ev, ...args) { + return super.emit(ev, ...args); + } + /** + * Returns the listeners listening to an event. + * + * @param event Event name + * @returns Array of listeners subscribed to `event` + */ + listeners(event) { + return super.listeners(event); + } +} +exports.StrictEventEmitter = StrictEventEmitter; diff --git a/software/flow/node_modules/socket.io/dist/uws.d.ts b/software/flow/node_modules/socket.io/dist/uws.d.ts new file mode 100644 index 0000000..b5377d4 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/uws.d.ts @@ -0,0 +1,3 @@ +export declare function patchAdapter(app: any): void; +export declare function restoreAdapter(): void; +export declare function serveFile(res: any, filepath: string): void; diff --git a/software/flow/node_modules/socket.io/dist/uws.js b/software/flow/node_modules/socket.io/dist/uws.js new file mode 100644 index 0000000..23eedf9 --- /dev/null +++ b/software/flow/node_modules/socket.io/dist/uws.js @@ -0,0 +1,135 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.serveFile = exports.restoreAdapter = exports.patchAdapter = void 0; +const socket_io_adapter_1 = require("socket.io-adapter"); +const fs_1 = require("fs"); +const debug_1 = __importDefault(require("debug")); +const debug = (0, debug_1.default)("socket.io:adapter-uws"); +const SEPARATOR = "\x1f"; // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text +const { addAll, del, broadcast } = socket_io_adapter_1.Adapter.prototype; +function patchAdapter(app /* : TemplatedApp */) { + socket_io_adapter_1.Adapter.prototype.addAll = function (id, rooms) { + const isNew = !this.sids.has(id); + addAll.call(this, id, rooms); + const socket = this.nsp.sockets.get(id); + if (!socket) { + return; + } + if (socket.conn.transport.name === "websocket") { + subscribe(this.nsp.name, socket, isNew, rooms); + return; + } + if (isNew) { + socket.conn.on("upgrade", () => { + const rooms = this.sids.get(id); + if (rooms) { + subscribe(this.nsp.name, socket, isNew, rooms); + } + }); + } + }; + socket_io_adapter_1.Adapter.prototype.del = function (id, room) { + del.call(this, id, room); + const socket = this.nsp.sockets.get(id); + if (socket && socket.conn.transport.name === "websocket") { + // @ts-ignore + const sessionId = socket.conn.id; + // @ts-ignore + const websocket = socket.conn.transport.socket; + const topic = `${this.nsp.name}${SEPARATOR}${room}`; + debug("unsubscribe connection %s from topic %s", sessionId, topic); + websocket.unsubscribe(topic); + } + }; + socket_io_adapter_1.Adapter.prototype.broadcast = function (packet, opts) { + const useFastPublish = opts.rooms.size <= 1 && opts.except.size === 0; + if (!useFastPublish) { + broadcast.call(this, packet, opts); + return; + } + const flags = opts.flags || {}; + const basePacketOpts = { + preEncoded: true, + volatile: flags.volatile, + compress: flags.compress, + }; + packet.nsp = this.nsp.name; + const encodedPackets = this.encoder.encode(packet); + const topic = opts.rooms.size === 0 + ? this.nsp.name + : `${this.nsp.name}${SEPARATOR}${opts.rooms.keys().next().value}`; + debug("fast publish to %s", topic); + // fast publish for clients connected with WebSocket + encodedPackets.forEach((encodedPacket) => { + const isBinary = typeof encodedPacket !== "string"; + // "4" being the message type in the Engine.IO protocol, see https://github.com/socketio/engine.io-protocol + app.publish(topic, isBinary ? encodedPacket : "4" + encodedPacket, isBinary); + }); + this.apply(opts, (socket) => { + if (socket.conn.transport.name !== "websocket") { + // classic publish for clients connected with HTTP long-polling + socket.client.writeToEngine(encodedPackets, basePacketOpts); + } + }); + }; +} +exports.patchAdapter = patchAdapter; +function subscribe(namespaceName, socket, isNew, rooms) { + // @ts-ignore + const sessionId = socket.conn.id; + // @ts-ignore + const websocket = socket.conn.transport.socket; + if (isNew) { + debug("subscribe connection %s to topic %s", sessionId, namespaceName); + websocket.subscribe(namespaceName); + } + rooms.forEach((room) => { + const topic = `${namespaceName}${SEPARATOR}${room}`; // '#' can be used as wildcard + debug("subscribe connection %s to topic %s", sessionId, topic); + websocket.subscribe(topic); + }); +} +function restoreAdapter() { + socket_io_adapter_1.Adapter.prototype.addAll = addAll; + socket_io_adapter_1.Adapter.prototype.del = del; + socket_io_adapter_1.Adapter.prototype.broadcast = broadcast; +} +exports.restoreAdapter = restoreAdapter; +const toArrayBuffer = (buffer) => { + const { buffer: arrayBuffer, byteOffset, byteLength } = buffer; + return arrayBuffer.slice(byteOffset, byteOffset + byteLength); +}; +// imported from https://github.com/kolodziejczak-sz/uwebsocket-serve +function serveFile(res /* : HttpResponse */, filepath) { + const { size } = (0, fs_1.statSync)(filepath); + const readStream = (0, fs_1.createReadStream)(filepath); + const destroyReadStream = () => !readStream.destroyed && readStream.destroy(); + const onError = (error) => { + destroyReadStream(); + throw error; + }; + const onDataChunk = (chunk) => { + const arrayBufferChunk = toArrayBuffer(chunk); + const lastOffset = res.getWriteOffset(); + const [ok, done] = res.tryEnd(arrayBufferChunk, size); + if (!done && !ok) { + readStream.pause(); + res.onWritable((offset) => { + const [ok, done] = res.tryEnd(arrayBufferChunk.slice(offset - lastOffset), size); + if (!done && ok) { + readStream.resume(); + } + return ok; + }); + } + }; + res.onAborted(destroyReadStream); + readStream + .on("data", onDataChunk) + .on("error", onError) + .on("end", destroyReadStream); +} +exports.serveFile = serveFile;