From 3081cff0652c81db0aa9a5a9865d25def544e6cb Mon Sep 17 00:00:00 2001 From: Code Date: Thu, 23 Jan 2025 07:22:43 +0100 Subject: [PATCH] esm ports --- packages/commons/dist/_glob.d.ts | 7 + packages/commons/dist/_glob.js | 93 ++ packages/commons/dist/_glob.js.map | 1 + packages/commons/dist/config.d.ts | 38 + packages/commons/dist/config.js | 49 + packages/commons/dist/config.js.map | 1 + packages/commons/dist/constants.d.ts | 8 + packages/commons/dist/constants.js | 13 + packages/commons/dist/constants.js.map | 1 + packages/commons/dist/fs.d.ts | 7 + packages/commons/dist/fs.js | 47 + packages/commons/dist/fs.js.map | 1 + packages/commons/dist/index.d.ts | 1 + packages/commons/dist/index.js | 2 + packages/commons/dist/index.js.map | 1 + packages/commons/dist/lib/fs.d.ts | 2 + packages/commons/dist/lib/fs.js | 18 + packages/commons/dist/lib/fs.js.map | 1 + packages/commons/dist/lib/index.d.ts | 2 + packages/commons/dist/lib/index.js | 3 + packages/commons/dist/lib/index.js.map | 1 + packages/commons/dist/lib/strings.d.ts | 3 + packages/commons/dist/lib/strings.js | 7 + packages/commons/dist/lib/strings.js.map | 1 + packages/commons/dist/logger.d.ts | 5 + packages/commons/dist/logger.js | 15 + packages/commons/dist/logger.js.map | 1 + packages/commons/dist/os.d.ts | 10 + packages/commons/dist/os.js | 13 + packages/commons/dist/os.js.map | 1 + packages/commons/dist/osr/component.d.ts | 56 + packages/commons/dist/osr/component.js | 2 + packages/commons/dist/osr/component.js.map | 1 + packages/commons/dist/osr/discourse.d.ts | 15 + packages/commons/dist/osr/discourse.js | 2 + packages/commons/dist/osr/discourse.js.map | 1 + packages/commons/dist/paths.d.ts | 1 + packages/commons/dist/paths.js | 2 + packages/commons/dist/paths.js.map | 1 + packages/commons/dist/profile.d.ts | 19 + packages/commons/dist/profile.js | 77 + packages/commons/dist/profile.js.map | 1 + packages/commons/dist/shemas/index.d.ts | 23 + packages/commons/dist/shemas/index.js | 204 +++ packages/commons/dist/shemas/index.js.map | 1 + packages/commons/dist/shemas/openapi.d.ts | 1 + packages/commons/dist/shemas/openapi.js | 22 + packages/commons/dist/shemas/openapi.js.map | 1 + packages/commons/dist/shemas/path.d.ts | 30 + packages/commons/dist/shemas/path.js | 239 +++ packages/commons/dist/shemas/path.js.map | 1 + packages/commons/dist/shemas/types.d.ts | 194 +++ packages/commons/dist/shemas/types.js | 140 ++ packages/commons/dist/shemas/types.js.map | 1 + packages/commons/dist/shemas/vfs.d.ts | 1 + packages/commons/dist/shemas/vfs.js | 3 + packages/commons/dist/shemas/vfs.js.map | 1 + packages/commons/dist/shemas/zod_map.d.ts | 46 + packages/commons/dist/shemas/zod_map.js | 102 ++ packages/commons/dist/shemas/zod_map.js.map | 1 + packages/commons/dist/types.d.ts | 264 +++ packages/commons/dist/types.js | 3 + packages/commons/dist/types.js.map | 1 + packages/commons/dist/types_cache.d.ts | 6 + packages/commons/dist/types_cache.js | 2 + packages/commons/dist/types_cache.js.map | 1 + packages/commons/dist/types_common.d.ts | 114 ++ packages/commons/dist/types_common.js | 2 + packages/commons/dist/types_common.js.map | 1 + packages/commons/dist/types_gui.d.ts | 296 ++++ packages/commons/dist/types_gui.js | 314 ++++ packages/commons/dist/types_gui.js.map | 1 + packages/commons/dist/types_kbot.d.ts | 192 +++ packages/commons/dist/types_kbot.js | 2 + packages/commons/dist/types_kbot.js.map | 1 + packages/commons/dist/uri.d.ts | 11 + packages/commons/dist/uri.js | 23 + packages/commons/dist/uri.js.map | 1 + packages/commons/dist/variables.d.ts | 12 + packages/commons/dist/variables.js | 39 + packages/commons/dist/variables.js.map | 1 + packages/commons/package.json | 34 +- packages/commons/src/_glob.ts | 96 ++ packages/commons/src/config.ts | 59 + packages/commons/src/constants.ts | 14 + packages/commons/src/fs.ts | 50 + packages/commons/src/lib/fs.ts | 16 + packages/commons/src/lib/index.ts | 3 + packages/commons/src/lib/strings.ts | 9 + packages/commons/src/logger.ts | 17 + packages/commons/src/os.ts | 10 + packages/commons/src/osr/component.ts | 102 ++ packages/commons/src/osr/discourse.ts | 15 + packages/commons/src/paths.ts | 0 packages/commons/src/profile.ts | 98 ++ packages/commons/src/shemas/index.ts | 10 +- packages/commons/src/shemas/path.ts | 15 +- packages/commons/src/types.ts | 365 +++++ packages/commons/src/types_cache.ts | 6 + packages/commons/src/types_common.ts | 129 ++ packages/commons/src/types_gui.ts | 304 ++++ packages/commons/src/types_kbot.ts | 192 +++ packages/commons/src/uri.ts | 36 + packages/commons/src/variables.ts | 40 + packages/commons/tsconfig.json | 8 +- packages/core/dist/arrays.d.ts | 287 ++++ packages/core/dist/arrays.js | 759 +++++++++ packages/core/dist/arrays.js.map | 1 + packages/core/dist/arraysFind.d.ts | 67 + packages/core/dist/arraysFind.js | 182 +++ packages/core/dist/arraysFind.js.map | 1 + packages/core/dist/aspects.d.ts | 87 + packages/core/dist/aspects.js | 188 +++ packages/core/dist/aspects.js.map | 1 + packages/core/dist/aspects_simple.d.ts | 68 + packages/core/dist/aspects_simple.js | 150 ++ packages/core/dist/aspects_simple.js.map | 1 + packages/core/dist/assert.d.ts | 26 + packages/core/dist/assert.js | 65 + packages/core/dist/assert.js.map | 1 + packages/core/dist/cache.d.ts | 46 + packages/core/dist/cache.js | 92 ++ packages/core/dist/cache.js.map | 1 + packages/core/dist/cancellation.d.ts | 30 + packages/core/dist/cancellation.js | 112 ++ packages/core/dist/cancellation.js.map | 1 + packages/core/dist/charCode.d.ts | 401 +++++ packages/core/dist/charCode.js | 410 +++++ packages/core/dist/charCode.js.map | 1 + packages/core/dist/collections.d.ts | 47 + packages/core/dist/collections.js | 114 ++ packages/core/dist/collections.js.map | 1 + packages/core/dist/constants.d.ts | 2 + packages/core/dist/constants.js | 6 + packages/core/dist/constants.js.map | 1 + packages/core/dist/equals.d.ts | 37 + packages/core/dist/equals.js | 122 ++ packages/core/dist/equals.js.map | 1 + packages/core/dist/errors.d.ts | 107 ++ packages/core/dist/errors.js | 243 +++ packages/core/dist/errors.js.map | 1 + packages/core/dist/event.d.ts | 570 +++++++ packages/core/dist/event.js | 1445 +++++++++++++++++ packages/core/dist/event.js.map | 1 + packages/core/dist/extpath.d.ts | 56 + packages/core/dist/extpath.js | 347 ++++ packages/core/dist/extpath.js.map | 1 + packages/core/dist/functional.d.ts | 4 + packages/core/dist/functional.js | 31 + packages/core/dist/functional.js.map | 1 + packages/core/dist/index.d.ts | 12 + packages/core/dist/index.js | 17 + packages/core/dist/index.js.map | 1 + packages/core/dist/iterator.d.ts | 74 + packages/core/dist/iterator.js | 224 +++ packages/core/dist/iterator.js.map | 1 + packages/core/dist/labels.d.ts | 81 + packages/core/dist/labels.js | 354 ++++ packages/core/dist/labels.js.map | 1 + packages/core/dist/lazy.d.ts | 22 + packages/core/dist/lazy.js | 45 + packages/core/dist/lazy.js.map | 1 + packages/core/dist/lifecycle.d.ts | 261 +++ packages/core/dist/lifecycle.js | 658 ++++++++ packages/core/dist/lifecycle.js.map | 1 + packages/core/dist/linkedList.d.ts | 15 + packages/core/dist/linkedList.js | 126 ++ packages/core/dist/linkedList.js.map | 1 + packages/core/dist/map.d.ts | 174 ++ packages/core/dist/map.js | 794 +++++++++ packages/core/dist/map.js.map | 1 + packages/core/dist/marshallingIds.d.ts | 24 + packages/core/dist/marshallingIds.js | 30 + packages/core/dist/marshallingIds.js.map | 1 + packages/core/dist/mime.d.ts | 13 + packages/core/dist/mime.js | 111 ++ packages/core/dist/mime.js.map | 1 + packages/core/dist/network.d.ts | 177 ++ packages/core/dist/network.js | 329 ++++ packages/core/dist/network.js.map | 1 + packages/core/dist/nls.d.ts | 142 ++ packages/core/dist/nls.js | 76 + packages/core/dist/nls.js.map | 1 + packages/core/dist/nls.messages.d.ts | 2 + packages/core/dist/nls.messages.js | 17 + packages/core/dist/nls.messages.js.map | 1 + packages/core/dist/objects.d.ts | 38 + packages/core/dist/objects.js | 249 +++ packages/core/dist/objects.js.map | 1 + packages/core/dist/observable.d.ts | 1 + packages/core/dist/observable.js | 7 + packages/core/dist/observable.js.map | 1 + .../core/dist/observableInternal/api.d.ts | 7 + packages/core/dist/observableInternal/api.js | 15 + .../core/dist/observableInternal/api.js.map | 1 + .../core/dist/observableInternal/autorun.d.ts | 73 + .../core/dist/observableInternal/autorun.js | 264 +++ .../dist/observableInternal/autorun.js.map | 1 + .../core/dist/observableInternal/base.d.ts | 257 +++ packages/core/dist/observableInternal/base.js | 278 ++++ .../core/dist/observableInternal/base.js.map | 1 + .../commonFacade/cancellation.d.ts | 2 + .../commonFacade/cancellation.js | 7 + .../commonFacade/cancellation.js.map | 1 + .../observableInternal/commonFacade/deps.d.ts | 5 + .../observableInternal/commonFacade/deps.js | 10 + .../commonFacade/deps.js.map | 1 + .../dist/observableInternal/debugName.d.ts | 32 + .../core/dist/observableInternal/debugName.js | 108 ++ .../dist/observableInternal/debugName.js.map | 1 + .../core/dist/observableInternal/derived.d.ts | 74 + .../core/dist/observableInternal/derived.js | 377 +++++ .../dist/observableInternal/derived.js.map | 1 + .../core/dist/observableInternal/index.d.ts | 8 + .../core/dist/observableInternal/index.js | 19 + .../core/dist/observableInternal/index.js.map | 1 + .../lazyObservableValue.d.ts | 25 + .../observableInternal/lazyObservableValue.js | 125 ++ .../lazyObservableValue.js.map | 1 + .../core/dist/observableInternal/logging.d.ts | 54 + .../core/dist/observableInternal/logging.js | 336 ++++ .../dist/observableInternal/logging.js.map | 1 + .../core/dist/observableInternal/promise.d.ts | 74 + .../core/dist/observableInternal/promise.js | 109 ++ .../dist/observableInternal/promise.js.map | 1 + .../core/dist/observableInternal/utils.d.ts | 109 ++ .../core/dist/observableInternal/utils.js | 548 +++++++ .../core/dist/observableInternal/utils.js.map | 1 + .../observableInternal/utilsCancellation.d.ts | 10 + .../observableInternal/utilsCancellation.js | 83 + .../utilsCancellation.js.map | 1 + packages/core/dist/path.d.ts | 39 + packages/core/dist/path.js | 1406 ++++++++++++++++ packages/core/dist/path.js.map | 1 + packages/core/dist/platform.d.ts | 99 ++ packages/core/dist/platform.js | 227 +++ packages/core/dist/platform.js.map | 1 + packages/core/dist/primitives.d.ts | 87 + packages/core/dist/primitives.js | 152 ++ packages/core/dist/primitives.js.map | 1 + packages/core/dist/process.d.ts | 27 + packages/core/dist/process.js | 65 + packages/core/dist/process.js.map | 1 + packages/core/dist/resources.d.ts | 187 +++ packages/core/dist/resources.js | 288 ++++ packages/core/dist/resources.js.map | 1 + packages/core/dist/sequence.d.ts | 19 + packages/core/dist/sequence.js | 15 + packages/core/dist/sequence.js.map | 1 + packages/core/dist/set.d.ts | 9 + packages/core/dist/set.js | 30 + packages/core/dist/set.js.map | 1 + packages/core/dist/stopwatch.d.ts | 10 + packages/core/dist/stopwatch.js | 32 + packages/core/dist/stopwatch.js.map | 1 + packages/core/dist/strings.d.ts | 259 +++ packages/core/dist/strings.js | 1100 +++++++++++++ packages/core/dist/strings.js.map | 1 + packages/core/dist/symbols.d.ts | 4 + packages/core/dist/symbols.js | 9 + packages/core/dist/symbols.js.map | 1 + packages/core/dist/types.d.ts | 151 ++ packages/core/dist/types.js | 200 +++ packages/core/dist/types.js.map | 1 + packages/core/dist/uint.d.ts | 31 + packages/core/dist/uint.js | 53 + packages/core/dist/uint.js.map | 1 + packages/core/dist/uri.d.ts | 163 ++ packages/core/dist/uri.js | 636 ++++++++ packages/core/dist/uri.js.map | 1 + packages/core/dist/utils.d.ts | 76 + packages/core/dist/utils.js | 379 +++++ packages/core/dist/utils.js.map | 1 + packages/core/dist/uuid.d.ts | 22 + packages/core/dist/uuid.js | 93 ++ packages/core/dist/uuid.js.map | 1 + packages/core/package.json | 8 + packages/fs/dist/append.d.ts | 8 + packages/fs/dist/append.js | 50 + packages/fs/dist/copy.d.ts | 15 + packages/fs/dist/copy.js | 621 +++++++ packages/fs/dist/dir.d.ts | 7 + packages/fs/dist/dir.js | 185 +++ packages/fs/dist/errors.d.ts | 7 + packages/fs/dist/errors.js | 41 + packages/fs/dist/exists.d.ts | 4 + packages/fs/dist/exists.js | 55 + packages/fs/dist/file.d.ts | 9 + packages/fs/dist/file.js | 148 ++ packages/fs/dist/find.d.ts | 15 + packages/fs/dist/find.js | 114 ++ packages/fs/dist/imports.d.ts | 10 + packages/fs/dist/imports.js | 8 + packages/fs/dist/index.d.ts | 61 + packages/fs/dist/index.js | 224 +++ packages/fs/dist/inspect.d.ts | 7 + packages/fs/dist/inspect.js | 135 ++ packages/fs/dist/inspect_tree.d.ts | 9 + packages/fs/dist/inspect_tree.js | 127 ++ packages/fs/dist/interfaces.d.ts | 460 ++++++ packages/fs/dist/interfaces.js | 163 ++ packages/fs/dist/iterator.d.ts | 4 + packages/fs/dist/iterator.js | 72 + packages/fs/dist/list.d.ts | 4 + packages/fs/dist/list.js | 62 + packages/fs/dist/main.d.ts | 2 + packages/fs/dist/main.js | 10 + packages/fs/dist/move.d.ts | 3 + packages/fs/dist/move.js | 106 ++ packages/fs/dist/promisify.d.ts | 15 + packages/fs/dist/promisify.js | 25 + packages/fs/dist/read.d.ts | 4 + packages/fs/dist/read.js | 89 + packages/fs/dist/remove.d.ts | 6 + packages/fs/dist/remove.js | 330 ++++ packages/fs/dist/rename.d.ts | 3 + packages/fs/dist/rename.js | 20 + packages/fs/dist/stats.d.ts | 3 + packages/fs/dist/stats.js | 4 + packages/fs/dist/streams.d.ts | 2 + packages/fs/dist/streams.js | 2 + packages/fs/dist/symlink.d.ts | 3 + packages/fs/dist/symlink.js | 51 + packages/fs/dist/util.d.ts | 1 + packages/fs/dist/util.js | 2 + packages/fs/dist/utils/dot.d.ts | 3 + packages/fs/dist/utils/dot.js | 9 + packages/fs/dist/utils/fs.d.ts | 1 + packages/fs/dist/utils/fs.js | 39 + packages/fs/dist/utils/matcher.d.ts | 6 + packages/fs/dist/utils/matcher.js | 65 + packages/fs/dist/utils/mime_match.d.ts | 10 + packages/fs/dist/utils/mime_match.js | 19 + packages/fs/dist/utils/mode.d.ts | 1 + packages/fs/dist/utils/mode.js | 11 + packages/fs/dist/utils/paths.d.ts | 6 + packages/fs/dist/utils/paths.js | 41 + packages/fs/dist/utils/platform.d.ts | 15 + packages/fs/dist/utils/platform.js | 42 + packages/fs/dist/utils/stats.d.ts | 18 + packages/fs/dist/utils/stats.js | 85 + packages/fs/dist/utils/strings.d.ts | 2 + packages/fs/dist/utils/strings.js | 15 + packages/fs/dist/utils/tree_walker.d.ts | 9 + packages/fs/dist/utils/tree_walker.js | 100 ++ packages/fs/dist/utils/validate.d.ts | 2 + packages/fs/dist/utils/validate.js | 96 ++ packages/fs/dist/utils/wildcard.d.ts | 1 + packages/fs/dist/utils/wildcard.js | 59 + packages/fs/dist/write.d.ts | 4 + packages/fs/dist/write.js | 85 + packages/fs/package.json | 14 + 352 files changed, 27615 insertions(+), 22 deletions(-) create mode 100644 packages/commons/dist/_glob.d.ts create mode 100644 packages/commons/dist/_glob.js create mode 100644 packages/commons/dist/_glob.js.map create mode 100644 packages/commons/dist/config.d.ts create mode 100644 packages/commons/dist/config.js create mode 100644 packages/commons/dist/config.js.map create mode 100644 packages/commons/dist/constants.d.ts create mode 100644 packages/commons/dist/constants.js create mode 100644 packages/commons/dist/constants.js.map create mode 100644 packages/commons/dist/fs.d.ts create mode 100644 packages/commons/dist/fs.js create mode 100644 packages/commons/dist/fs.js.map create mode 100644 packages/commons/dist/index.d.ts create mode 100644 packages/commons/dist/index.js create mode 100644 packages/commons/dist/index.js.map create mode 100644 packages/commons/dist/lib/fs.d.ts create mode 100644 packages/commons/dist/lib/fs.js create mode 100644 packages/commons/dist/lib/fs.js.map create mode 100644 packages/commons/dist/lib/index.d.ts create mode 100644 packages/commons/dist/lib/index.js create mode 100644 packages/commons/dist/lib/index.js.map create mode 100644 packages/commons/dist/lib/strings.d.ts create mode 100644 packages/commons/dist/lib/strings.js create mode 100644 packages/commons/dist/lib/strings.js.map create mode 100644 packages/commons/dist/logger.d.ts create mode 100644 packages/commons/dist/logger.js create mode 100644 packages/commons/dist/logger.js.map create mode 100644 packages/commons/dist/os.d.ts create mode 100644 packages/commons/dist/os.js create mode 100644 packages/commons/dist/os.js.map create mode 100644 packages/commons/dist/osr/component.d.ts create mode 100644 packages/commons/dist/osr/component.js create mode 100644 packages/commons/dist/osr/component.js.map create mode 100644 packages/commons/dist/osr/discourse.d.ts create mode 100644 packages/commons/dist/osr/discourse.js create mode 100644 packages/commons/dist/osr/discourse.js.map create mode 100644 packages/commons/dist/paths.d.ts create mode 100644 packages/commons/dist/paths.js create mode 100644 packages/commons/dist/paths.js.map create mode 100644 packages/commons/dist/profile.d.ts create mode 100644 packages/commons/dist/profile.js create mode 100644 packages/commons/dist/profile.js.map create mode 100644 packages/commons/dist/shemas/index.d.ts create mode 100644 packages/commons/dist/shemas/index.js create mode 100644 packages/commons/dist/shemas/index.js.map create mode 100644 packages/commons/dist/shemas/openapi.d.ts create mode 100644 packages/commons/dist/shemas/openapi.js create mode 100644 packages/commons/dist/shemas/openapi.js.map create mode 100644 packages/commons/dist/shemas/path.d.ts create mode 100644 packages/commons/dist/shemas/path.js create mode 100644 packages/commons/dist/shemas/path.js.map create mode 100644 packages/commons/dist/shemas/types.d.ts create mode 100644 packages/commons/dist/shemas/types.js create mode 100644 packages/commons/dist/shemas/types.js.map create mode 100644 packages/commons/dist/shemas/vfs.d.ts create mode 100644 packages/commons/dist/shemas/vfs.js create mode 100644 packages/commons/dist/shemas/vfs.js.map create mode 100644 packages/commons/dist/shemas/zod_map.d.ts create mode 100644 packages/commons/dist/shemas/zod_map.js create mode 100644 packages/commons/dist/shemas/zod_map.js.map create mode 100644 packages/commons/dist/types.d.ts create mode 100644 packages/commons/dist/types.js create mode 100644 packages/commons/dist/types.js.map create mode 100644 packages/commons/dist/types_cache.d.ts create mode 100644 packages/commons/dist/types_cache.js create mode 100644 packages/commons/dist/types_cache.js.map create mode 100644 packages/commons/dist/types_common.d.ts create mode 100644 packages/commons/dist/types_common.js create mode 100644 packages/commons/dist/types_common.js.map create mode 100644 packages/commons/dist/types_gui.d.ts create mode 100644 packages/commons/dist/types_gui.js create mode 100644 packages/commons/dist/types_gui.js.map create mode 100644 packages/commons/dist/types_kbot.d.ts create mode 100644 packages/commons/dist/types_kbot.js create mode 100644 packages/commons/dist/types_kbot.js.map create mode 100644 packages/commons/dist/uri.d.ts create mode 100644 packages/commons/dist/uri.js create mode 100644 packages/commons/dist/uri.js.map create mode 100644 packages/commons/dist/variables.d.ts create mode 100644 packages/commons/dist/variables.js create mode 100644 packages/commons/dist/variables.js.map create mode 100644 packages/commons/src/_glob.ts create mode 100644 packages/commons/src/config.ts create mode 100644 packages/commons/src/constants.ts create mode 100644 packages/commons/src/fs.ts create mode 100644 packages/commons/src/lib/fs.ts create mode 100644 packages/commons/src/lib/index.ts create mode 100644 packages/commons/src/lib/strings.ts create mode 100644 packages/commons/src/logger.ts create mode 100644 packages/commons/src/os.ts create mode 100644 packages/commons/src/osr/component.ts create mode 100644 packages/commons/src/osr/discourse.ts create mode 100644 packages/commons/src/paths.ts create mode 100644 packages/commons/src/profile.ts create mode 100644 packages/commons/src/types.ts create mode 100644 packages/commons/src/types_cache.ts create mode 100644 packages/commons/src/types_common.ts create mode 100644 packages/commons/src/types_gui.ts create mode 100644 packages/commons/src/types_kbot.ts create mode 100644 packages/commons/src/uri.ts create mode 100644 packages/commons/src/variables.ts create mode 100644 packages/core/dist/arrays.d.ts create mode 100644 packages/core/dist/arrays.js create mode 100644 packages/core/dist/arrays.js.map create mode 100644 packages/core/dist/arraysFind.d.ts create mode 100644 packages/core/dist/arraysFind.js create mode 100644 packages/core/dist/arraysFind.js.map create mode 100644 packages/core/dist/aspects.d.ts create mode 100644 packages/core/dist/aspects.js create mode 100644 packages/core/dist/aspects.js.map create mode 100644 packages/core/dist/aspects_simple.d.ts create mode 100644 packages/core/dist/aspects_simple.js create mode 100644 packages/core/dist/aspects_simple.js.map create mode 100644 packages/core/dist/assert.d.ts create mode 100644 packages/core/dist/assert.js create mode 100644 packages/core/dist/assert.js.map create mode 100644 packages/core/dist/cache.d.ts create mode 100644 packages/core/dist/cache.js create mode 100644 packages/core/dist/cache.js.map create mode 100644 packages/core/dist/cancellation.d.ts create mode 100644 packages/core/dist/cancellation.js create mode 100644 packages/core/dist/cancellation.js.map create mode 100644 packages/core/dist/charCode.d.ts create mode 100644 packages/core/dist/charCode.js create mode 100644 packages/core/dist/charCode.js.map create mode 100644 packages/core/dist/collections.d.ts create mode 100644 packages/core/dist/collections.js create mode 100644 packages/core/dist/collections.js.map create mode 100644 packages/core/dist/constants.d.ts create mode 100644 packages/core/dist/constants.js create mode 100644 packages/core/dist/constants.js.map create mode 100644 packages/core/dist/equals.d.ts create mode 100644 packages/core/dist/equals.js create mode 100644 packages/core/dist/equals.js.map create mode 100644 packages/core/dist/errors.d.ts create mode 100644 packages/core/dist/errors.js create mode 100644 packages/core/dist/errors.js.map create mode 100644 packages/core/dist/event.d.ts create mode 100644 packages/core/dist/event.js create mode 100644 packages/core/dist/event.js.map create mode 100644 packages/core/dist/extpath.d.ts create mode 100644 packages/core/dist/extpath.js create mode 100644 packages/core/dist/extpath.js.map create mode 100644 packages/core/dist/functional.d.ts create mode 100644 packages/core/dist/functional.js create mode 100644 packages/core/dist/functional.js.map create mode 100644 packages/core/dist/index.d.ts create mode 100644 packages/core/dist/index.js create mode 100644 packages/core/dist/index.js.map create mode 100644 packages/core/dist/iterator.d.ts create mode 100644 packages/core/dist/iterator.js create mode 100644 packages/core/dist/iterator.js.map create mode 100644 packages/core/dist/labels.d.ts create mode 100644 packages/core/dist/labels.js create mode 100644 packages/core/dist/labels.js.map create mode 100644 packages/core/dist/lazy.d.ts create mode 100644 packages/core/dist/lazy.js create mode 100644 packages/core/dist/lazy.js.map create mode 100644 packages/core/dist/lifecycle.d.ts create mode 100644 packages/core/dist/lifecycle.js create mode 100644 packages/core/dist/lifecycle.js.map create mode 100644 packages/core/dist/linkedList.d.ts create mode 100644 packages/core/dist/linkedList.js create mode 100644 packages/core/dist/linkedList.js.map create mode 100644 packages/core/dist/map.d.ts create mode 100644 packages/core/dist/map.js create mode 100644 packages/core/dist/map.js.map create mode 100644 packages/core/dist/marshallingIds.d.ts create mode 100644 packages/core/dist/marshallingIds.js create mode 100644 packages/core/dist/marshallingIds.js.map create mode 100644 packages/core/dist/mime.d.ts create mode 100644 packages/core/dist/mime.js create mode 100644 packages/core/dist/mime.js.map create mode 100644 packages/core/dist/network.d.ts create mode 100644 packages/core/dist/network.js create mode 100644 packages/core/dist/network.js.map create mode 100644 packages/core/dist/nls.d.ts create mode 100644 packages/core/dist/nls.js create mode 100644 packages/core/dist/nls.js.map create mode 100644 packages/core/dist/nls.messages.d.ts create mode 100644 packages/core/dist/nls.messages.js create mode 100644 packages/core/dist/nls.messages.js.map create mode 100644 packages/core/dist/objects.d.ts create mode 100644 packages/core/dist/objects.js create mode 100644 packages/core/dist/objects.js.map create mode 100644 packages/core/dist/observable.d.ts create mode 100644 packages/core/dist/observable.js create mode 100644 packages/core/dist/observable.js.map create mode 100644 packages/core/dist/observableInternal/api.d.ts create mode 100644 packages/core/dist/observableInternal/api.js create mode 100644 packages/core/dist/observableInternal/api.js.map create mode 100644 packages/core/dist/observableInternal/autorun.d.ts create mode 100644 packages/core/dist/observableInternal/autorun.js create mode 100644 packages/core/dist/observableInternal/autorun.js.map create mode 100644 packages/core/dist/observableInternal/base.d.ts create mode 100644 packages/core/dist/observableInternal/base.js create mode 100644 packages/core/dist/observableInternal/base.js.map create mode 100644 packages/core/dist/observableInternal/commonFacade/cancellation.d.ts create mode 100644 packages/core/dist/observableInternal/commonFacade/cancellation.js create mode 100644 packages/core/dist/observableInternal/commonFacade/cancellation.js.map create mode 100644 packages/core/dist/observableInternal/commonFacade/deps.d.ts create mode 100644 packages/core/dist/observableInternal/commonFacade/deps.js create mode 100644 packages/core/dist/observableInternal/commonFacade/deps.js.map create mode 100644 packages/core/dist/observableInternal/debugName.d.ts create mode 100644 packages/core/dist/observableInternal/debugName.js create mode 100644 packages/core/dist/observableInternal/debugName.js.map create mode 100644 packages/core/dist/observableInternal/derived.d.ts create mode 100644 packages/core/dist/observableInternal/derived.js create mode 100644 packages/core/dist/observableInternal/derived.js.map create mode 100644 packages/core/dist/observableInternal/index.d.ts create mode 100644 packages/core/dist/observableInternal/index.js create mode 100644 packages/core/dist/observableInternal/index.js.map create mode 100644 packages/core/dist/observableInternal/lazyObservableValue.d.ts create mode 100644 packages/core/dist/observableInternal/lazyObservableValue.js create mode 100644 packages/core/dist/observableInternal/lazyObservableValue.js.map create mode 100644 packages/core/dist/observableInternal/logging.d.ts create mode 100644 packages/core/dist/observableInternal/logging.js create mode 100644 packages/core/dist/observableInternal/logging.js.map create mode 100644 packages/core/dist/observableInternal/promise.d.ts create mode 100644 packages/core/dist/observableInternal/promise.js create mode 100644 packages/core/dist/observableInternal/promise.js.map create mode 100644 packages/core/dist/observableInternal/utils.d.ts create mode 100644 packages/core/dist/observableInternal/utils.js create mode 100644 packages/core/dist/observableInternal/utils.js.map create mode 100644 packages/core/dist/observableInternal/utilsCancellation.d.ts create mode 100644 packages/core/dist/observableInternal/utilsCancellation.js create mode 100644 packages/core/dist/observableInternal/utilsCancellation.js.map create mode 100644 packages/core/dist/path.d.ts create mode 100644 packages/core/dist/path.js create mode 100644 packages/core/dist/path.js.map create mode 100644 packages/core/dist/platform.d.ts create mode 100644 packages/core/dist/platform.js create mode 100644 packages/core/dist/platform.js.map create mode 100644 packages/core/dist/primitives.d.ts create mode 100644 packages/core/dist/primitives.js create mode 100644 packages/core/dist/primitives.js.map create mode 100644 packages/core/dist/process.d.ts create mode 100644 packages/core/dist/process.js create mode 100644 packages/core/dist/process.js.map create mode 100644 packages/core/dist/resources.d.ts create mode 100644 packages/core/dist/resources.js create mode 100644 packages/core/dist/resources.js.map create mode 100644 packages/core/dist/sequence.d.ts create mode 100644 packages/core/dist/sequence.js create mode 100644 packages/core/dist/sequence.js.map create mode 100644 packages/core/dist/set.d.ts create mode 100644 packages/core/dist/set.js create mode 100644 packages/core/dist/set.js.map create mode 100644 packages/core/dist/stopwatch.d.ts create mode 100644 packages/core/dist/stopwatch.js create mode 100644 packages/core/dist/stopwatch.js.map create mode 100644 packages/core/dist/strings.d.ts create mode 100644 packages/core/dist/strings.js create mode 100644 packages/core/dist/strings.js.map create mode 100644 packages/core/dist/symbols.d.ts create mode 100644 packages/core/dist/symbols.js create mode 100644 packages/core/dist/symbols.js.map create mode 100644 packages/core/dist/types.d.ts create mode 100644 packages/core/dist/types.js create mode 100644 packages/core/dist/types.js.map create mode 100644 packages/core/dist/uint.d.ts create mode 100644 packages/core/dist/uint.js create mode 100644 packages/core/dist/uint.js.map create mode 100644 packages/core/dist/uri.d.ts create mode 100644 packages/core/dist/uri.js create mode 100644 packages/core/dist/uri.js.map create mode 100644 packages/core/dist/utils.d.ts create mode 100644 packages/core/dist/utils.js create mode 100644 packages/core/dist/utils.js.map create mode 100644 packages/core/dist/uuid.d.ts create mode 100644 packages/core/dist/uuid.js create mode 100644 packages/core/dist/uuid.js.map create mode 100644 packages/fs/dist/append.d.ts create mode 100644 packages/fs/dist/append.js create mode 100644 packages/fs/dist/copy.d.ts create mode 100644 packages/fs/dist/copy.js create mode 100644 packages/fs/dist/dir.d.ts create mode 100644 packages/fs/dist/dir.js create mode 100644 packages/fs/dist/errors.d.ts create mode 100644 packages/fs/dist/errors.js create mode 100644 packages/fs/dist/exists.d.ts create mode 100644 packages/fs/dist/exists.js create mode 100644 packages/fs/dist/file.d.ts create mode 100644 packages/fs/dist/file.js create mode 100644 packages/fs/dist/find.d.ts create mode 100644 packages/fs/dist/find.js create mode 100644 packages/fs/dist/imports.d.ts create mode 100644 packages/fs/dist/imports.js create mode 100644 packages/fs/dist/index.d.ts create mode 100644 packages/fs/dist/index.js create mode 100644 packages/fs/dist/inspect.d.ts create mode 100644 packages/fs/dist/inspect.js create mode 100644 packages/fs/dist/inspect_tree.d.ts create mode 100644 packages/fs/dist/inspect_tree.js create mode 100644 packages/fs/dist/interfaces.d.ts create mode 100644 packages/fs/dist/interfaces.js create mode 100644 packages/fs/dist/iterator.d.ts create mode 100644 packages/fs/dist/iterator.js create mode 100644 packages/fs/dist/list.d.ts create mode 100644 packages/fs/dist/list.js create mode 100644 packages/fs/dist/main.d.ts create mode 100644 packages/fs/dist/main.js create mode 100644 packages/fs/dist/move.d.ts create mode 100644 packages/fs/dist/move.js create mode 100644 packages/fs/dist/promisify.d.ts create mode 100644 packages/fs/dist/promisify.js create mode 100644 packages/fs/dist/read.d.ts create mode 100644 packages/fs/dist/read.js create mode 100644 packages/fs/dist/remove.d.ts create mode 100644 packages/fs/dist/remove.js create mode 100644 packages/fs/dist/rename.d.ts create mode 100644 packages/fs/dist/rename.js create mode 100644 packages/fs/dist/stats.d.ts create mode 100644 packages/fs/dist/stats.js create mode 100644 packages/fs/dist/streams.d.ts create mode 100644 packages/fs/dist/streams.js create mode 100644 packages/fs/dist/symlink.d.ts create mode 100644 packages/fs/dist/symlink.js create mode 100644 packages/fs/dist/util.d.ts create mode 100644 packages/fs/dist/util.js create mode 100644 packages/fs/dist/utils/dot.d.ts create mode 100644 packages/fs/dist/utils/dot.js create mode 100644 packages/fs/dist/utils/fs.d.ts create mode 100644 packages/fs/dist/utils/fs.js create mode 100644 packages/fs/dist/utils/matcher.d.ts create mode 100644 packages/fs/dist/utils/matcher.js create mode 100644 packages/fs/dist/utils/mime_match.d.ts create mode 100644 packages/fs/dist/utils/mime_match.js create mode 100644 packages/fs/dist/utils/mode.d.ts create mode 100644 packages/fs/dist/utils/mode.js create mode 100644 packages/fs/dist/utils/paths.d.ts create mode 100644 packages/fs/dist/utils/paths.js create mode 100644 packages/fs/dist/utils/platform.d.ts create mode 100644 packages/fs/dist/utils/platform.js create mode 100644 packages/fs/dist/utils/stats.d.ts create mode 100644 packages/fs/dist/utils/stats.js create mode 100644 packages/fs/dist/utils/strings.d.ts create mode 100644 packages/fs/dist/utils/strings.js create mode 100644 packages/fs/dist/utils/tree_walker.d.ts create mode 100644 packages/fs/dist/utils/tree_walker.js create mode 100644 packages/fs/dist/utils/validate.d.ts create mode 100644 packages/fs/dist/utils/validate.js create mode 100644 packages/fs/dist/utils/wildcard.d.ts create mode 100644 packages/fs/dist/utils/wildcard.js create mode 100644 packages/fs/dist/write.d.ts create mode 100644 packages/fs/dist/write.js diff --git a/packages/commons/dist/_glob.d.ts b/packages/commons/dist/_glob.d.ts new file mode 100644 index 00000000..c615e5b9 --- /dev/null +++ b/packages/commons/dist/_glob.d.ts @@ -0,0 +1,7 @@ +import { GlobOptions } from 'glob'; +export declare const files: (cwd: any, glob: any, options?: any) => []; +export declare const filesEx: (cwd: any, glob: any, options?: GlobOptions) => []; +import { PATH_INFO } from '@/types_common.js'; +export declare const forward_slash: (path: any) => any; +export declare const pathInfoEx: (src: string, altToken?: boolean, globOptions?: GlobOptions) => PATH_INFO; +export declare const pathInfo: (src: string, altToken?: boolean, cwd?: string) => PATH_INFO; diff --git a/packages/commons/dist/_glob.js b/packages/commons/dist/_glob.js new file mode 100644 index 00000000..bb696087 --- /dev/null +++ b/packages/commons/dist/_glob.js @@ -0,0 +1,93 @@ +import * as path from 'path'; +// import * as isGlob from 'is-glob' +// import * as fg from 'fast-glob' +import { glob, globSync, hasMagic } from 'glob'; +import { REGEX_VAR, REGEX_VAR_ALT } from "@polymech/core/constants.js"; +import { sync as exists } from '@polymech/fs/exists'; +export const files = (cwd, glob, options) => globSync(glob, { ...{ dot: true, cwd, absolute: true, caseSensitiveMatch: false }, ...options || {} }); +export const filesEx = (cwd, glob, options) => globSync(glob, { ...{ dot: true, cwd, absolute: true, caseSensitiveMatch: false }, ...options || {} }); +import { substitute } from '@/variables.js'; +import { isFile, isFolder, getExtensions } from '@/fs.js'; +const globBase = require('glob-base'); +export const forward_slash = (path) => { + const isExtendedLengthPath = /^\\\\\?\\/.test(path); + const hasNonAscii = /[^\u0000-\u0080]+/.test(path); + if (isExtendedLengthPath || hasNonAscii) { + return path; + } + return path.replace(/\\/g, '/'); +}; +export const pathInfoEx = (src, altToken = false, globOptions = {}) => { + const srcParts = path.parse(src); + let variables = { + PATH: src + }; + variables.DIR = srcParts.dir; + variables.NAME = srcParts.name; + variables.FILE_NAME = srcParts.base; + variables.FILE_EXT = srcParts.ext.replace('.', ''); + variables.PATH = src; + variables.IS_FILE = isFile(src); + variables.IS_FOLDER = isFolder(src); + variables.IS_EXPRESSION = src.match(altToken ? REGEX_VAR_ALT : REGEX_VAR) != null; + if (!variables.IS_FOLDER && !variables.IS_FILE) { + variables.IS_GLOB = hasMagic(substitute(altToken, srcParts.base, {}, false)); + } + else { + variables.IS_GLOB = false; + } + if (variables.IS_GLOB) { + //important: use the forward slash since path.resolve will return backslashes on Windows + const glob_base = globBase(src); + variables.DIR = path.resolve(glob_base.base); + variables.FILE_NAME = glob_base.glob; + variables.GLOB = glob_base.glob; + variables.GLOB_EXTENSIONS = getExtensions(glob_base.glob); + globOptions = { + ...globOptions, + cwd: globOptions.cwd ? path.join(globOptions.cwd, glob_base.base) : null + }; + variables.FILES = glob.sync(glob_base.glob, globOptions); + } + else if (variables.IS_FILE && exists(src)) { + variables.FILES = [src]; + } + return variables; +}; +export const pathInfo = (src, altToken = false, cwd = null) => { + const srcParts = path.parse(src); + let variables = { + PATH: src + }; + variables.DIR = srcParts.dir; + variables.NAME = srcParts.name; + variables.FILE_NAME = srcParts.base; + variables.FILE_EXT = srcParts.ext.replace('.', ''); + variables.PATH = src; + variables.IS_FILE = isFile(src); + variables.IS_FOLDER = isFolder(src); + variables.IS_EXPRESSION = src.match(altToken ? REGEX_VAR_ALT : REGEX_VAR) != null; + if (!variables.IS_FOLDER && !variables.IS_FILE) { + variables.IS_GLOB = hasMagic(srcParts.base); + } + else { + variables.IS_GLOB = false; + } + if (variables.IS_GLOB) { + const glob_base = globBase(src); + variables.DIR = path.resolve(glob_base.base); + variables.FILE_NAME = glob_base.glob; + variables.GLOB = glob_base.glob; + variables.GLOB_EXTENSIONS = getExtensions(glob_base.glob); + variables.FILES = globSync(glob_base.glob, { + dot: true, + cwd: path.resolve(cwd || variables.DIR), + absolute: true + }); + } + else if (variables.IS_FILE && exists(src)) { + variables.FILES = [src]; + } + return variables; +}; +//# sourceMappingURL=_glob.js.map \ No newline at end of file diff --git a/packages/commons/dist/_glob.js.map b/packages/commons/dist/_glob.js.map new file mode 100644 index 00000000..b8839e5b --- /dev/null +++ b/packages/commons/dist/_glob.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_glob.js","sourceRoot":"","sources":["../src/_glob.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAC5B,oCAAoC;AACpC,kCAAkC;AAClC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAe,QAAQ,EAAG,MAAM,MAAM,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAA;AACtE,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAEpD,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,OAAa,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,kBAAkB,EAAE,KAAK,EAAE,EAAE,GAAG,OAAO,IAAI,EAAE,EAAE,CAAO,CAAA;AAC/J,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,OAAqB,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,kBAAkB,EAAE,KAAK,EAAE,EAAE,GAAG,OAAO,IAAI,EAAE,EAAE,CAAO,CAAA;AAEzK,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAC3C,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAGzD,MAAM,QAAQ,GAAG,OAAO,CAAC,WAAW,CAAC,CAAA;AAErC,MAAM,CAAC,MAAM,aAAa,GAAG,CAA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AG,IAAI,SAAS,CAAC,GAAG,CAAC;YACvC,QAAQ,EAAE,IAAI;SACjB,CAAC,CAAA;KACL;SAAM,IAAI,SAAS,CAAC,OAAO,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE;QACzC,SAAS,CAAC,KAAK,GAAG,CAAC,GAAG,CAAC,CAAA;KAC1B;IACD,OAAO,SAAS,CAAA;AACpB,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/config.d.ts b/packages/commons/dist/config.d.ts new file mode 100644 index 00000000..3f105fa3 --- /dev/null +++ b/packages/commons/dist/config.d.ts @@ -0,0 +1,38 @@ +export declare const API_PREFIX = "osr"; +export declare const API_PREFIX_NEXT = "polymech"; +export declare const HOME: (sub?: string) => string; +export declare const get_var: (key?: string) => string; +export declare const OSR_ROOT: (key?: string) => string; +export declare const OSR_SUB_DEFAULT: (key?: string) => string; +export declare const CONFIG_DEFAULT_PATH: (key?: string) => string; +export declare const OSR_TEMP: (key?: string) => string; +export declare const OSR_CACHE: (key?: string) => string; +export declare const OSR_PRIVATE: (key?: string) => string; +export declare const KB_ROOT: (key?: string) => string; +export declare const OSR_LIBRARY: (key?: string) => string; +export declare const OSR_LIBRARY_MACHINES: (key?: string) => string; +export declare const OSR_LIBRARY_DIRECTORY: (key?: string) => string; +export declare const PRODUCT_ROOT: (key?: string) => string; +export declare const OSR_CUSTOMER_DRIVE: (key?: string) => string; +export declare const OA_ROOT: (key?: string) => string; +export declare const OSR_USER_ASSETS: (key?: string) => string; +export declare const POLYMECH_ROOT: (key?: string) => string; +export declare const DEFAULT_ROOTS: { + OSR_ROOT: string; + OSR_TEMP: string; + PRODUCT_ROOT: string; + OA_ROOT: string; + KB_ROOT: string; + OSR_CACHE: string; + OSR_LIBRARY: string; + OSR_LIBRARY_MACHINES: string; + OSR_LIBRARY_DIRECTORY: string; + OSR_USER_ASSETS: string; + OSR_PRIVATE: string; + OSR_TEMPLATES: string; + OSR_CONTENT: string; + OSR_PROFILES: string; + OSR_CUSTOMER_DRIVE: string; + POLYMECH_ROOT: string; +}; +export declare const CONFIG_DEFAULT: (key?: string) => string | false | object; diff --git a/packages/commons/dist/config.js b/packages/commons/dist/config.js new file mode 100644 index 00000000..64b653e5 --- /dev/null +++ b/packages/commons/dist/config.js @@ -0,0 +1,49 @@ +import * as env from 'env-var'; +import { sync as read } from '@polymech/fs/read'; +import { sync as exists } from '@polymech/fs/exists'; +import * as path from 'path'; +export const API_PREFIX = 'osr'; +export const API_PREFIX_NEXT = 'polymech'; +export const HOME = (sub = '') => path.join(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], sub); +export const get_var = (key = '') => env.get(key).asString() || env.get(key.replace(/-/g, '_')).asString() || env.get(key.replace(/_/g, '-')).asString(); +export const OSR_ROOT = (key = 'OSR-ROOT') => get_var(key) || path.join(HOME('desktop'), API_PREFIX); +export const OSR_SUB_DEFAULT = (key = '') => get_var(key) || path.join(OSR_ROOT(), key); +export const CONFIG_DEFAULT_PATH = (key = 'OSR-CONFIG') => get_var(key) || path.join(HOME(`${API_PREFIX}`), '.config.json'); +export const OSR_TEMP = (key = 'OSR-TEMP') => get_var(key) || OSR_SUB_DEFAULT(`.${API_PREFIX}/temp`); +export const OSR_CACHE = (key = 'OSR-CACHE') => get_var(key) || OSR_SUB_DEFAULT(`.${API_PREFIX}/cache`); +export const OSR_PRIVATE = (key = 'OSR-PRIVATE') => get_var(key); +export const KB_ROOT = (key = 'OSR-KB') => get_var(key); +export const OSR_LIBRARY = (key = 'OSR-LIBRARY') => get_var(key); +export const OSR_LIBRARY_MACHINES = (key = 'OSR-LIBRARY-MACHINES') => get_var(key); +export const OSR_LIBRARY_DIRECTORY = (key = 'OSR-LIBRARY-DIRECTORY') => get_var(key); +export const PRODUCT_ROOT = (key = 'PRODUCT-ROOT') => get_var(key); +export const OSR_CUSTOMER_DRIVE = (key = 'OSR-CUSTOMER-DRIVE') => get_var(key); +export const OA_ROOT = (key = 'OA-ROOT') => get_var(key); +export const OSR_USER_ASSETS = (key = 'OSR-USER-ASSETS') => get_var(key); +export const POLYMECH_ROOT = (key = 'POLYMECH-ROOT') => get_var(key) || path.join(HOME('desktop'), API_PREFIX_NEXT); +export const DEFAULT_ROOTS = { + OSR_ROOT: OSR_ROOT(), + OSR_TEMP: OSR_TEMP(), + PRODUCT_ROOT: PRODUCT_ROOT(), + OA_ROOT: OA_ROOT(), + KB_ROOT: KB_ROOT(), + OSR_CACHE: OSR_CACHE(), + OSR_LIBRARY: OSR_LIBRARY(), + OSR_LIBRARY_MACHINES: OSR_LIBRARY_MACHINES(), + OSR_LIBRARY_DIRECTORY: OSR_LIBRARY_DIRECTORY(), + OSR_USER_ASSETS: OSR_USER_ASSETS(), + OSR_PRIVATE: OSR_PRIVATE(), + OSR_TEMPLATES: path.join(OSR_SUB_DEFAULT('osr-templates')), + OSR_CONTENT: path.join(OSR_SUB_DEFAULT('osr-content')), + OSR_PROFILES: path.join(OSR_SUB_DEFAULT('osr-profiles')), + OSR_CUSTOMER_DRIVE: OSR_CUSTOMER_DRIVE(), + POLYMECH_ROOT: POLYMECH_ROOT() +}; +export const CONFIG_DEFAULT = (key = 'OSR-CONFIG') => { + const cPath = path.resolve(CONFIG_DEFAULT_PATH(key)); + if (exists(cPath)) { + return read(cPath, 'json'); + } + return false; +}; +//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/packages/commons/dist/config.js.map b/packages/commons/dist/config.js.map new file mode 100644 index 00000000..442225f6 --- /dev/null +++ b/packages/commons/dist/config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,SAAS,CAAA;AAC9B,OAAO,EAAE,IAAI,IAAI,IAAI,EAAE,MAAM,mBAAmB,CAAA;AAChD,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,MAAM,qBAAqB,CAAA;AACpD,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAE5B,MAAM,CAA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AM,aAAa,GAAG,CAAC,MAAc,eAAe,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,eAAe,CAAC,CAAA;AAE3H,MAAM,CAAC,MAAM,aAAa,GAAG;IACzB,QAAQ,EAAE,QAAQ,EAAE;IACpB,QAAQ,EAAE,QAAQ,EAAE;IACpB,YAAY,EAAE,YAAY,EAAE;IAC5B,OAAO,EAAE,OAAO,EAAE;IAClB,OAAO,EAAE,OAAO,EAAE;IAClB,SAAS,EAAE,SAAS,EAAE;IACtB,WAAW,EAAE,WAAW,EAAE;IAC1B,oBAAoB,EAAE,oBAAoB,EAAE;IAC5C,qBAAqB,EAAE,qBAAqB,EAAE;IAC9C,eAAe,EAAE,eAAe,EAAE;IAClC,WAAW,EAAE,WAAW,EAAE;IAC1B,aAAa,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;IAC1D,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;IACtD,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,cAAc,CAAC,CAAC;IACxD,kBAAkB,EAAE,kBAAkB,EAAE;IACxC,aAAa,EAAE,aAAa,EAAE;CACjC,CAAA;AAED,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,MAAc,YAAY,EAAE,EAAE;IACzD,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC,CAAC;IACrD,IAAI,MAAM,CAAC,KAAK,CAAC,EAAE;QACf,OAAO,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;KAC9B;IACD,OAAO,KAAK,CAAC;AACjB,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/constants.d.ts b/packages/commons/dist/constants.d.ts new file mode 100644 index 00000000..cb13a759 --- /dev/null +++ b/packages/commons/dist/constants.d.ts @@ -0,0 +1,8 @@ +export declare const MODULE_NAME = "OSR-Commons"; +export declare const PROFILE_FILE_NAME = ".osrl.json"; +export declare const OA_LATEST = "${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}.json"; +export declare const OA_LATEST_INVALID = "${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_INVALID.json"; +export declare const OA_LATEST_CENSORED = "${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_CENSORED.json"; +export declare const OA_LATEST_MERGED = "${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_MERGED.json"; +export declare const PP_BAZAR_LATEST_INDEX = "${OSR_ROOT}/pp-bazar/${YYYY}/${MM}/index.json"; +export declare const PP_BAZAR_LATEST_INDEX_MERGED = "${OSR_ROOT}/pp-bazar/${YYYY}/${MM}/index_merged.json"; diff --git a/packages/commons/dist/constants.js b/packages/commons/dist/constants.js new file mode 100644 index 00000000..2bb677c2 --- /dev/null +++ b/packages/commons/dist/constants.js @@ -0,0 +1,13 @@ +export const MODULE_NAME = `OSR-Commons`; +export const PROFILE_FILE_NAME = `.osrl.json`; +//////////////////////////////////////// +// +// OA Migration +export const OA_LATEST = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}.json'; +export const OA_LATEST_INVALID = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_INVALID.json'; +export const OA_LATEST_CENSORED = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_CENSORED.json'; +export const OA_LATEST_MERGED = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_MERGED.json'; +// fecking bazar +export const PP_BAZAR_LATEST_INDEX = '${OSR_ROOT}/pp-bazar/${YYYY}/${MM}/index.json'; +export const PP_BAZAR_LATEST_INDEX_MERGED = '${OSR_ROOT}/pp-bazar/${YYYY}/${MM}/index_merged.json'; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/packages/commons/dist/constants.js.map b/packages/commons/dist/constants.js.map new file mode 100644 index 00000000..a1c0b10b --- /dev/null +++ b/packages/commons/dist/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,WAAW,GAAG,aAAa,CAAA;AACxC,MAAM,CAAC,MAAM,iBAAiB,GAAG,YAAY,CAAA;AAC7C,wCAAwC;AACxC,EAAE;AACF,gBAAgB;AAEhB,MAAM,CAAC,MAAM,SAAS,GAAG,iDAAiD,CAAA;AAC1E,MAAM,CAAC,MAAM,iBAAiB,GAAG,yDAAyD,CAAA;AAC1F,MAAM,CAAC,MAAM,kBAAkB,GAAG,0DAA0D,CAAA;AAC5F,MAAM,CAAC,MAAM,gBAAgB,GAAG,wDAAwD,CAAA;AAExF,gBAAgB;AAChB,MAAM,CAAC,MAAM,qBAAqB,GAAG,+CAA+C,CAAA;AACpF,MAAM,CAAC,MAAM,4BAA4B,GAAG,sDAAsD,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/fs.d.ts b/packages/commons/dist/fs.d.ts new file mode 100644 index 00000000..3b7d1845 --- /dev/null +++ b/packages/commons/dist/fs.d.ts @@ -0,0 +1,7 @@ +export declare const GLOB_GROUP_PATTERN: RegExp; +export declare const UNC_REGEX: RegExp; +export declare const WIN32_PATH_REGEX: RegExp; +export declare const getExtensions: (glob: string) => any[]; +export declare const isFile: (src: string) => boolean; +export declare const isFolder: (src: string) => boolean; +export declare const is_absolute: (fp: any) => boolean; diff --git a/packages/commons/dist/fs.js b/packages/commons/dist/fs.js new file mode 100644 index 00000000..06be3524 --- /dev/null +++ b/packages/commons/dist/fs.js @@ -0,0 +1,47 @@ +import * as fs from 'fs'; +// https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#namespaces +// https://github.com/isaacs/node-glob/blob/main/src/pattern.ts +export const GLOB_GROUP_PATTERN = /[!*+?@]\(.*\)/; +export const UNC_REGEX = /^[\\\/]{2,}[^\\\/]+[\\\/]+[^\\\/]+/; +export const WIN32_PATH_REGEX = /^([a-z]:)?[\\\/]/i; +import { is_windows } from './os.js'; +const parseGlob = require('parse-glob'); +export const getExtensions = (glob) => { + const match = glob.match(GLOB_GROUP_PATTERN); + if (match) { + return glob.substring((match.index || 0) + 2, glob.lastIndexOf(')')).split('|'); + } + else { + return [parseGlob(glob).path.ext]; + } +}; +export const isFile = (src) => { + let srcIsFile = false; + try { + srcIsFile = fs.lstatSync(src).isFile(); + } + catch (e) { } + return srcIsFile; +}; +export const isFolder = (src) => { + let srcIsFolder = false; + try { + srcIsFolder = fs.lstatSync(src).isDirectory(); + } + catch (e) { } + return srcIsFolder; +}; +const is_relative_win32 = (fp) => !fp.test(UNC_REGEX) && !WIN32_PATH_REGEX.test(fp); +const is_absolute_posix = (fp) => fp.charAt(0) === '/'; +const is_absolute_win32 = (fp) => { + if (/[a-z]/i.test(fp.charAt(0)) && fp.charAt(1) === ':' && fp.charAt(2) === '\\') { + return true; + } + // Microsoft Azure absolute filepath + if (fp.slice(0, 2) === '\\\\') { + return true; + } + return !is_relative_win32(fp); +}; +export const is_absolute = (fp) => is_windows() ? is_absolute_win32(fp) : is_absolute_posix(fp); +//# sourceMappingURL=fs.js.map \ No newline at end of file diff --git a/packages/commons/dist/fs.js.map b/packages/commons/dist/fs.js.map new file mode 100644 index 00000000..a3d007b2 --- /dev/null +++ b/packages/commons/dist/fs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fs.js","sourceRoot":"","sources":["../src/fs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAA;AAExB,kFAAkF;AAClF,+DAA+D;AAC/D,MAAM,CAAC,MAAM,kBAAkB,GAAG,eAAe,CAAA;AACjD,MAAM,CAAC,MAAM,SAAS,GAAG,oCAAoC,CAAA;AAC7D,MAAM,CAAC,MAAM,gBAAgB,GAAG,mBAAmB,CAAA;AAEnD,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAEpC,MAAM,SA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,CAAC,CAAC,CAAC,KAAK,GAAG,CAAA;AACtD,MAAM,iBAAiB,GAAG,CAAC,EAAE,EAAE,EAAE;IAC7B,IAAI,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE;QAC9E,OAAO,IAAI,CAAA;KACd;IACD,oCAAoC;IACpC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,MAAM,EAAE;QAC3B,OAAO,IAAI,CAAC;KACf;IACD,OAAO,CAAC,iBAAiB,CAAC,EAAE,CAAC,CAAA;AACjC,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,EAAE,EAAE,EAAE,CAAE,UAAU,EAAE,CAAC,CAAC,CAAC,iBAAiB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,EAAE,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/index.d.ts b/packages/commons/dist/index.d.ts new file mode 100644 index 00000000..509db186 --- /dev/null +++ b/packages/commons/dist/index.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/packages/commons/dist/index.js b/packages/commons/dist/index.js new file mode 100644 index 00000000..a65dc47d --- /dev/null +++ b/packages/commons/dist/index.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/commons/dist/index.js.map b/packages/commons/dist/index.js.map new file mode 100644 index 00000000..1ed2df62 --- /dev/null +++ b/packages/commons/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/commons/dist/lib/fs.d.ts b/packages/commons/dist/lib/fs.d.ts new file mode 100644 index 00000000..1e9f7d1a --- /dev/null +++ b/packages/commons/dist/lib/fs.d.ts @@ -0,0 +1,2 @@ +export declare const isFile: (src: string) => boolean; +export declare const isFolder: (src: string) => boolean; diff --git a/packages/commons/dist/lib/fs.js b/packages/commons/dist/lib/fs.js new file mode 100644 index 00000000..a14558c8 --- /dev/null +++ b/packages/commons/dist/lib/fs.js @@ -0,0 +1,18 @@ +import * as fs from 'fs'; +export const isFile = (src) => { + let srcIsFile = false; + try { + srcIsFile = fs.lstatSync(src).isFile(); + } + catch (e) { } + return srcIsFile; +}; +export const isFolder = (src) => { + let srcIsFolder = false; + try { + srcIsFolder = fs.lstatSync(src).isDirectory(); + } + catch (e) { } + return srcIsFolder; +}; +//# sourceMappingURL=fs.js.map \ No newline at end of file diff --git a/packages/commons/dist/lib/fs.js.map b/packages/commons/dist/lib/fs.js.map new file mode 100644 index 00000000..8eed6370 --- /dev/null +++ b/packages/commons/dist/lib/fs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fs.js","sourceRoot":"","sources":["../../src/lib/fs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAA;AAExB,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,GAAW,EAAE,EAAE;IAClC,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI;QACA,SAAS,GAAG,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAA;KACzC;IAAC,OAAO,CAAC,EAAE,GAAG;IACf,OAAO,SAAS,CAAA;AACpB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,GAAW,EAAE,EAAE;IACpC,IAAI,WAAW,GAAG,KAAK,CAAC;IACxB,IAAI;QACA,WAAW,GAAG,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,CAAA;KAChD;IAAC,OAAO,CAAC,EAAE,GAAG;IACf,OAAO,WAAW,CAAC;AACvB,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/lib/index.d.ts b/packages/commons/dist/lib/index.d.ts new file mode 100644 index 00000000..c78ab911 --- /dev/null +++ b/packages/commons/dist/lib/index.d.ts @@ -0,0 +1,2 @@ +export * from './strings.js'; +export * from './fs.js'; diff --git a/packages/commons/dist/lib/index.js b/packages/commons/dist/lib/index.js new file mode 100644 index 00000000..871353fc --- /dev/null +++ b/packages/commons/dist/lib/index.js @@ -0,0 +1,3 @@ +export * from './strings.js'; +export * from './fs.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/commons/dist/lib/index.js.map b/packages/commons/dist/lib/index.js.map new file mode 100644 index 00000000..bd667d32 --- /dev/null +++ b/packages/commons/dist/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/lib/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAA;AAC5B,cAAc,SAAS,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/lib/strings.d.ts b/packages/commons/dist/lib/strings.d.ts new file mode 100644 index 00000000..e4bc12a9 --- /dev/null +++ b/packages/commons/dist/lib/strings.d.ts @@ -0,0 +1,3 @@ +export declare const regexExEmojis: RegExp; +export declare const regexExEmojis2: RegExp; +export declare const regexExEmojis3: RegExp; diff --git a/packages/commons/dist/lib/strings.js b/packages/commons/dist/lib/strings.js new file mode 100644 index 00000000..5f25401e --- /dev/null +++ b/packages/commons/dist/lib/strings.js @@ -0,0 +1,7 @@ +export const regexExEmojis = /((?:\ud83c\udde8\ud83c\uddf3|\ud83c\uddfa\ud83c\uddf8|\ud83c\uddf7\ud83c\uddfa|\ud83c\uddf0\ud83c\uddf7|\ud83c\uddef\ud83c\uddf5|\ud83c\uddee\ud83c\uddf9|\ud83c\uddec\ud83c\udde7|\ud83c\uddeb\ud83c\uddf7|\ud83c\uddea\ud83c\uddf8|\ud83c\udde9\ud83c\uddea|\u0039\ufe0f?\u20e3|\u0038\ufe0f?\u20e3|\u0037\ufe0f?\u20e3|\u0036\ufe0f?\u20e3|\u0035\ufe0f?\u20e3|\u0034\ufe0f?\u20e3|\u0033\ufe0f?\u20e3|\u0032\ufe0f?\u20e3|\u0031\ufe0f?\u20e3|\u0030\ufe0f?\u20e3|\u0023\ufe0f?\u20e3|\ud83d\udeb3|\ud83d\udeb1|\ud83d\udeb0|\ud83d\udeaf|\ud83d\udeae|\ud83d\udea6|\ud83d\udea3|\ud83d\udea1|\ud83d\udea0|\ud83d\ude9f|\ud83d\ude9e|\ud83d\ude9d|\ud83d\ude9c|\ud83d\ude9b|\ud83d\ude98|\ud83d\ude96|\ud83d\ude94|\ud83d\ude90|\ud83d\ude8e|\ud83d\ude8d|\ud83d\ude8b|\ud83d\ude8a|\ud83d\ude88|\ud83d\ude86|\ud83d\ude82|\ud83d\ude81|\ud83d\ude36|\ud83d\ude34|\ud83d\ude2f|\ud83d\ude2e|\ud83d\ude2c|\ud83d\ude27|\ud83d\ude26|\ud83d\ude1f|\ud83d\ude1b|\ud83d\ude19|\ud83d\ude17|\ud83d\ude15|\ud83d\ude11|\ud83d\ude10|\ud83d\ude0e|\ud83d\ude08|\ud83d\ude07|\ud83d\ude00|\ud83d\udd67|\ud83d\udd66|\ud83d\udd65|\ud83d\udd64|\ud83d\udd63|\ud83d\udd62|\ud83d\udd61|\ud83d\udd60|\ud83d\udd5f|\ud83d\udd5e|\ud83d\udd5d|\ud83d\udd5c|\ud83d\udd2d|\ud83d\udd2c|\ud83d\udd15|\ud83d\udd09|\ud83d\udd08|\ud83d\udd07|\ud83d\udd06|\ud83d\udd05|\ud83d\udd04|\ud83d\udd02|\ud83d\udd01|\ud83d\udd00|\ud83d\udcf5|\ud83d\udcef|\ud83d\udced|\ud83d\udcec|\ud83d\udcb7|\ud83d\udcb6|\ud83d\udcad|\ud83d\udc6d|\ud83d\udc6c|\ud83d\udc65|\ud83d\udc2a|\ud83d\udc16|\ud83d\udc15|\ud83d\udc13|\ud83d\udc10|\ud83d\udc0f|\ud83d\udc0b|\ud83d\udc0a|\ud83d\udc09|\ud83d\udc08|\ud83d\udc07|\ud83d\udc06|\ud83d\udc05|\ud83d\udc04|\ud83d\udc03|\ud83d\udc02|\ud83d\udc01|\ud83d\udc00|\ud83c\udfe4|\ud83c\udfc9|\ud83c\udfc7|\ud83c\udf7c|\ud83c\udf50|\ud83c\udf4b|\ud83c\udf33|\ud83c\udf32|\ud83c\udf1e|\ud83c\udf1d|\ud83c\udf1c|\ud83c\udf1a|\ud83c\udf18|\ud83c\udccf|\ud83c\udd8e|\ud83c\udd91|\ud83c\udd92|\ud83c\udd93|\ud83c\udd94|\ud83c\udd95|\ud83c\udd96|\ud83c\udd97|\ud83c\udd98|\ud83c\udd99|\ud83c\udd9a|\ud83d\udc77|\ud83d\udec5|\ud83d\udec4|\ud83d\udec3|\ud83d\udec2|\ud83d\udec1|\ud83d\udebf|\ud83d\udeb8|\ud83d\udeb7|\ud83d\udeb5|\ud83c\ude01|\ud83c\ude32|\ud83c\ude33|\ud83c\ude34|\ud83c\ude35|\ud83c\ude36|\ud83c\ude38|\ud83c\ude39|\ud83c\ude3a|\ud83c\ude50|\ud83c\ude51|\ud83c\udf00|\ud83c\udf01|\ud83c\udf02|\ud83c\udf03|\ud83c\udf04|\ud83c\udf05|\ud83c\udf06|\ud83c\udf07|\ud83c\udf08|\ud83c\udf09|\ud83c\udf0a|\ud83c\udf0b|\ud83c\udf0c|\ud83c\udf0f|\ud83c\udf11|\ud83c\udf13|\ud83c\udf14|\ud83c\udf15|\ud83c\udf19|\ud83c\udf1b|\ud83c\udf1f|\ud83c\udf20|\ud83c\udf30|\ud83c\udf31|\ud83c\udf34|\ud83c\udf35|\ud83c\udf37|\ud83c\udf38|\ud83c\udf39|\ud83c\udf3a|\ud83c\udf3b|\ud83c\udf3c|\ud83c\udf3d|\ud83c\udf3e|\ud83c\udf3f|\ud83c\udf40|\ud83c\udf41|\ud83c\udf42|\ud83c\udf43|\ud83c\udf44|\ud83c\udf45|\ud83c\udf46|\ud83c\udf47|\ud83c\udf48|\ud83c\udf49|\ud83c\udf4a|\ud83c\udf4c|\ud83c\udf4d|\ud83c\udf4e|\ud83c\udf4f|\ud83c\udf51|\ud83c\udf52|\ud83c\udf53|\ud83c\udf54|\ud83c\udf55|\ud83c\udf56|\ud83c\udf57|\ud83c\udf58|\ud83c\udf59|\ud83c\udf5a|\ud83c\udf5b|\ud83c\udf5c|\ud83c\udf5d|\ud83c\udf5e|\ud83c\udf5f|\ud83c\udf60|\ud83c\udf61|\ud83c\udf62|\ud83c\udf63|\ud83c\udf64|\ud83c\udf65|\ud83c\udf66|\ud83c\udf67|\ud83c\udf68|\ud83c\udf69|\ud83c\udf6a|\ud83c\udf6b|\ud83c\udf6c|\ud83c\udf6d|\ud83c\udf6e|\ud83c\udf6f|\ud83c\udf70|\ud83c\udf71|\ud83c\udf72|\ud83c\udf73|\ud83c\udf74|\ud83c\udf75|\ud83c\udf76|\ud83c\udf77|\ud83c\udf78|\ud83c\udf79|\ud83c\udf7a|\ud83c\udf7b|\ud83c\udf80|\ud83c\udf81|\ud83c\udf82|\ud83c\udf83|\ud83c\udf84|\ud83c\udf85|\ud83c\udf86|\ud83c\udf87|\ud83c\udf88|\ud83c\udf89|\ud83c\udf8a|\ud83c\udf8b|\ud83c\udf8c|\ud83c\udf8d|\ud83c\udf8e|\ud83c\udf8f|\ud83c\udf90|\ud83c\udf91|\ud83c\udf92|\ud83c\udf93|\ud83c\udfa0|\ud83c\udfa1|\ud83c\udfa2|\ud83c\udfa3|\ud83c\udfa4|\ud83c\udfa5|\ud83c\udfa6|\ud83c\udfa7|\ud83c\udfa8|\ud83c\udfa9|\ud83c\udfaa|\ud83c\udfab|\ud83c\udfac|\ud83c\udfad|\ud83c\udfae|\ud83c\udfaf|\ud83c\udfb0|\ud83c\udfb1|\ud83c\udfb2|\ud83c\udfb3|\ud83c\udfb4|\ud83c\udfb5|\ud83c\udfb6|\ud83c\udfb7|\ud83c\udfb8|\ud83c\udfb9|\ud83c\udfba|\ud83c\udfbb|\ud83c\udfbc|\ud83c\udfbd|\ud83c\udfbe|\ud83c\udfbf|\ud83c\udfc0|\ud83c\udfc1|\ud83c\udfc2|\ud83c\udfc3|\ud83c\udfc4|\ud83c\udfc6|\ud83c\udfc8|\ud83c\udfca|\ud83c\udfe0|\ud83c\udfe1|\ud83c\udfe2|\ud83c\udfe3|\ud83c\udfe5|\ud83c\udfe6|\ud83c\udfe7|\ud83c\udfe8|\ud83c\udfe9|\ud83c\udfea|\ud83c\udfeb|\ud83c\udfec|\ud83c\udfed|\ud83c\udfee|\ud83c\udfef|\ud83c\udff0|\ud83d\udc0c|\ud83d\udc0d|\ud83d\udc0e|\ud83d\udc11|\ud83d\udc12|\ud83d\udc14|\ud83d\udc17|\ud83d\udc18|\ud83d\udc19|\ud83d\udc1a|\ud83d\udc1b|\ud83d\udc1c|\ud83d\udc1d|\ud83d\udc1e|\ud83d\udc1f|\ud83d\udc20|\ud83d\udc21|\ud83d\udc22|\ud83d\udc23|\ud83d\udc24|\ud83d\udc25|\ud83d\udc26|\ud83d\udc27|\ud83d\udc28|\ud83d\udc29|\ud83d\udc2b|\ud83d\udc2c|\ud83d\udc2d|\ud83d\udc2e|\ud83d\udc2f|\ud83d\udc30|\ud83d\udc31|\ud83d\udc32|\ud83d\udc33|\ud83d\udc34|\ud83d\udc35|\ud83d\udc36|\ud83d\udc37|\ud83d\udc38|\ud83d\udc39|\ud83d\udc3a|\ud83d\udc3b|\ud83d\udc3c|\ud83d\udc3d|\ud83d\udc3e|\ud83d\udc40|\ud83d\udc42|\ud83d\udc43|\ud83d\udc44|\ud83d\udc45|\ud83d\udc46|\ud83d\udc47|\ud83d\udc48|\ud83d\udc49|\ud83d\udc4a|\ud83d\udc4b|\ud83d\udc4c|\ud83d\udc4d|\ud83d\udc4e|\ud83d\udc4f|\ud83d\udc50|\ud83d\udc51|\ud83d\udc52|\ud83d\udc53|\ud83d\udc54|\ud83d\udc55|\ud83d\udc56|\ud83d\udc57|\ud83d\udc58|\ud83d\udc59|\ud83d\udc5a|\ud83d\udc5b|\ud83d\udc5c|\ud83d\udc5d|\ud83d\udc5e|\ud83d\udc5f|\ud83d\udc60|\ud83d\udc61|\ud83d\udc62|\ud83d\udc63|\ud83d\udc64|\ud83d\udc66|\ud83d\udc67|\ud83d\udc68|\ud83d\udc69|\ud83d\udc6a|\ud83d\udc6b|\ud83d\udc6e|\ud83d\udc6f|\ud83d\udc70|\ud83d\udc71|\ud83d\udc72|\ud83d\udc73|\ud83d\udc74|\ud83d\udc75|\ud83d\udc76|\ud83d\udeb4|\ud83d\udc78|\ud83d\udc79|\ud83d\udc7a|\ud83d\udc7b|\ud83d\udc7c|\ud83d\udc7d|\ud83d\udc7e|\ud83d\udc7f|\ud83d\udc80|\ud83d\udc81|\ud83d\udc82|\ud83d\udc83|\ud83d\udc84|\ud83d\udc85|\ud83d\udc86|\ud83d\udc87|\ud83d\udc88|\ud83d\udc89|\ud83d\udc8a|\ud83d\udc8b|\ud83d\udc8c|\ud83d\udc8d|\ud83d\udc8e|\ud83d\udc8f|\ud83d\udc90|\ud83d\udc91|\ud83d\udc92|\ud83d\udc93|\ud83d\udc94|\ud83d\udc95|\ud83d\udc96|\ud83d\udc97|\ud83d\udc98|\ud83d\udc99|\ud83d\udc9a|\ud83d\udc9b|\ud83d\udc9c|\ud83d\udc9d|\ud83d\udc9e|\ud83d\udc9f|\ud83d\udca0|\ud83d\udca1|\ud83d\udca2|\ud83d\udca3|\ud83d\udca4|\ud83d\udca5|\ud83d\udca6|\ud83d\udca7|\ud83d\udca8|\ud83d\udca9|\ud83d\udcaa|\ud83d\udcab|\ud83d\udcac|\ud83d\udcae|\ud83d\udcaf|\ud83d\udcb0|\ud83d\udcb1|\ud83d\udcb2|\ud83d\udcb3|\ud83d\udcb4|\ud83d\udcb5|\ud83d\udcb8|\ud83d\udcb9|\ud83d\udcba|\ud83d\udcbb|\ud83d\udcbc|\ud83d\udcbd|\ud83d\udcbe|\ud83d\udcbf|\ud83d\udcc0|\ud83d\udcc1|\ud83d\udcc2|\ud83d\udcc3|\ud83d\udcc4|\ud83d\udcc5|\ud83d\udcc6|\ud83d\udcc7|\ud83d\udcc8|\ud83d\udcc9|\ud83d\udcca|\ud83d\udccb|\ud83d\udccc|\ud83d\udccd|\ud83d\udcce|\ud83d\udccf|\ud83d\udcd0|\ud83d\udcd1|\ud83d\udcd2|\ud83d\udcd3|\ud83d\udcd4|\ud83d\udcd5|\ud83d\udcd6|\ud83d\udcd7|\ud83d\udcd8|\ud83d\udcd9|\ud83d\udcda|\ud83d\udcdb|\ud83d\udcdc|\ud83d\udcdd|\ud83d\udcde|\ud83d\udcdf|\ud83d\udce0|\ud83d\udce1|\ud83d\udce2|\ud83d\udce3|\ud83d\udce4|\ud83d\udce5|\ud83d\udce6|\ud83d\udce7|\ud83d\udce8|\ud83d\udce9|\ud83d\udcea|\ud83d\udceb|\ud83d\udcee|\ud83d\udcf0|\ud83d\udcf1|\ud83d\udcf2|\ud83d\udcf3|\ud83d\udcf4|\ud83d\udcf6|\ud83d\udcf7|\ud83d\udcf9|\ud83d\udcfa|\ud83d\udcfb|\ud83d\udcfc|\ud83d\udd03|\ud83d\udd0a|\ud83d\udd0b|\ud83d\udd0c|\ud83d\udd0d|\ud83d\udd0e|\ud83d\udd0f|\ud83d\udd10|\ud83d\udd11|\ud83d\udd12|\ud83d\udd13|\ud83d\udd14|\ud83d\udd16|\ud83d\udd17|\ud83d\udd18|\ud83d\udd19|\ud83d\udd1a|\ud83d\udd1b|\ud83d\udd1c|\ud83d\udd1d|\ud83d\udd1e|\ud83d\udd1f|\ud83d\udd20|\ud83d\udd21|\ud83d\udd22|\ud83d\udd23|\ud83d\udd24|\ud83d\udd25|\ud83d\udd26|\ud83d\udd27|\ud83d\udd28|\ud83d\udd29|\ud83d\udd2a|\ud83d\udd2b|\ud83d\udd2e|\ud83d\udd2f|\ud83d\udd30|\ud83d\udd31|\ud83d\udd32|\ud83d\udd33|\ud83d\udd34|\ud83d\udd35|\ud83d\udd36|\ud83d\udd37|\ud83d\udd38|\ud83d\udd39|\ud83d\udd3a|\ud83d\udd3b|\ud83d\udd3c|\ud83d\udd3d|\ud83d\udd50|\ud83d\udd51|\ud83d\udd52|\ud83d\udd53|\ud83d\udd54|\ud83d\udd55|\ud83d\udd56|\ud83d\udd57|\ud83d\udd58|\ud83d\udd59|\ud83d\udd5a|\ud83d\udd5b|\ud83d\uddfb|\ud83d\uddfc|\ud83d\uddfd|\ud83d\uddfe|\ud83d\uddff|\ud83d\ude01|\ud83d\ude02|\ud83d\ude03|\ud83d\ude04|\ud83d\ude05|\ud83d\ude06|\ud83d\ude09|\ud83d\ude0a|\ud83d\ude0b|\ud83d\ude0c|\ud83d\ude0d|\ud83d\ude0f|\ud83d\ude12|\ud83d\ude13|\ud83d\ude14|\ud83d\ude16|\ud83d\ude18|\ud83d\ude1a|\ud83d\ude1c|\ud83d\ude1d|\ud83d\ude1e|\ud83d\ude20|\ud83d\ude21|\ud83d\ude22|\ud83d\ude23|\ud83d\ude24|\ud83d\ude25|\ud83d\ude28|\ud83d\ude29|\ud83d\ude2a|\ud83d\ude2b|\ud83d\ude2d|\ud83d\ude30|\ud83d\ude31|\ud83d\ude32|\ud83d\ude33|\ud83d\ude35|\ud83d\ude37|\ud83d\ude38|\ud83d\ude39|\ud83d\ude3a|\ud83d\ude3b|\ud83d\ude3c|\ud83d\ude3d|\ud83d\ude3e|\ud83d\ude3f|\ud83d\ude40|\ud83d\ude45|\ud83d\ude46|\ud83d\ude47|\ud83d\ude48|\ud83d\ude49|\ud83d\ude4a|\ud83d\ude4b|\ud83d\ude4c|\ud83d\ude4d|\ud83d\ude4e|\ud83d\ude4f|\ud83d\ude80|\ud83d\ude83|\ud83d\ude84|\ud83d\ude85|\ud83d\ude87|\ud83d\ude89|\ud83d\ude8c|\ud83d\ude8f|\ud83d\ude91|\ud83d\ude92|\ud83d\ude93|\ud83d\ude95|\ud83d\ude97|\ud83d\ude99|\ud83d\ude9a|\ud83d\udea2|\ud83d\udea4|\ud83d\udea5|\ud83d\udea7|\ud83d\udea8|\ud83d\udea9|\ud83d\udeaa|\ud83d\udeab|\ud83d\udeac|\ud83d\udead|\ud83d\udeb2|\ud83d\udeb6|\ud83d\udeb9|\ud83d\udeba|\ud83d\udebb|\ud83d\udebc|\ud83d\udebd|\ud83d\udebe|\ud83d\udec0|\ud83c\udde6|\ud83c\udde7|\ud83c\udde8|\ud83c\udde9|\ud83c\uddea|\ud83c\uddeb|\ud83c\uddec|\ud83c\udded|\ud83c\uddee|\ud83c\uddef|\ud83c\uddf0|\ud83c\uddf1|\ud83c\uddf2|\ud83c\uddf3|\ud83c\uddf4|\ud83c\uddf5|\ud83c\uddf6|\ud83c\uddf7|\ud83c\uddf8|\ud83c\uddf9|\ud83c\uddfa|\ud83c\uddfb|\ud83c\uddfc|\ud83c\uddfd|\ud83c\uddfe|\ud83c\uddff|\ud83c\udf0d|\ud83c\udf0e|\ud83c\udf10|\ud83c\udf12|\ud83c\udf16|\ud83c\udf17|\ue50a|\u27b0|\u2797|\u2796|\u2795|\u2755|\u2754|\u2753|\u274e|\u274c|\u2728|\u270b|\u270a|\u2705|\u26ce|\u23f3|\u23f0|\u23ec|\u23eb|\u23ea|\u23e9|\u27bf|\u00a9|\u00ae)|(?:(?:\ud83c\udc04|\ud83c\udd70|\ud83c\udd71|\ud83c\udd7e|\ud83c\udd7f|\ud83c\ude02|\ud83c\ude1a|\ud83c\ude2f|\ud83c\ude37|\u3299|\u303d|\u3030|\u2b55|\u2b50|\u2b1c|\u2b1b|\u2b07|\u2b06|\u2b05|\u2935|\u2934|\u27a1|\u2764|\u2757|\u2747|\u2744|\u2734|\u2733|\u2716|\u2714|\u2712|\u270f|\u270c|\u2709|\u2708|\u2702|\u26fd|\u26fa|\u26f5|\u26f3|\u26f2|\u26ea|\u26d4|\u26c5|\u26c4|\u26be|\u26bd|\u26ab|\u26aa|\u26a1|\u26a0|\u2693|\u267f|\u267b|\u3297|\u2666|\u2665|\u2663|\u2660|\u2653|\u2652|\u2651|\u2650|\u264f|\u264e|\u264d|\u264c|\u264b|\u264a|\u2649|\u2648|\u263a|\u261d|\u2615|\u2614|\u2611|\u260e|\u2601|\u2600|\u25fe|\u25fd|\u25fc|\u25fb|\u25c0|\u25b6|\u25ab|\u25aa|\u24c2|\u231b|\u231a|\u21aa|\u21a9|\u2199|\u2198|\u2197|\u2196|\u2195|\u2194|\u2139|\u2122|\u2049|\u203c|\u2668)([\uFE0E\uFE0F]?)))/g; +// Alternative syntax using RegExp constructor +export const regexExEmojis2 = new RegExp('((?:\\ud83c\\udde8\\ud83c\\uddf3|\\ud83c\\uddfa\\ud83c\\uddf8|\\ud83c\\uddf7\\ud83c\\uddfa|\\ud83c\\uddf0\\ud83c\\uddf7|\\ud83c\\uddef\\ud83c\\uddf5|\\ud83c\\uddee\\ud83c\\uddf9|\\ud83c\\uddec\\ud83c\\udde7|\\ud83c\\uddeb\\ud83c\\uddf7|\\ud83c\\uddea\\ud83c\\uddf8|\\ud83c\\udde9\\ud83c\\uddea|\\u0039\\ufe0f?\\u20e3|\\u0038\\ufe0f?\\u20e3|\\u0037\\ufe0f?\\u20e3|\\u0036\\ufe0f?\\u20e3|\\u0035\\ufe0f?\\u20e3|\\u0034\\ufe0f?\\u20e3|\\u0033\\ufe0f?\\u20e3|\\u0032\\ufe0f?\\u20e3|\\u0031\\ufe0f?\\u20e3|\\u0030\\ufe0f?\\u20e3|\\u0023\\ufe0f?\\u20e3|\\ud83d\\udeb3|\\ud83d\\udeb1|\\ud83d\\udeb0|\\ud83d\\udeaf|\\ud83d\\udeae|\\ud83d\\udea6|\\ud83d\\udea3|\\ud83d\\udea1|\\ud83d\\udea0|\\ud83d\\ude9f|\\ud83d\\ude9e|\\ud83d\\ude9d|\\ud83d\\ude9c|\\ud83d\\ude9b|\\ud83d\\ude98|\\ud83d\\ude96|\\ud83d\\ude94|\\ud83d\\ude90|\\ud83d\\ude8e|\\ud83d\\ude8d|\\ud83d\\ude8b|\\ud83d\\ude8a|\\ud83d\\ude88|\\ud83d\\ude86|\\ud83d\\ude82|\\ud83d\\ude81|\\ud83d\\ude36|\\ud83d\\ude34|\\ud83d\\ude2f|\\ud83d\\ude2e|\\ud83d\\ude2c|\\ud83d\\ude27|\\ud83d\\ude26|\\ud83d\\ude1f|\\ud83d\\ude1b|\\ud83d\\ude19|\\ud83d\\ude17|\\ud83d\\ude15|\\ud83d\\ude11|\\ud83d\\ude10|\\ud83d\\ude0e|\\ud83d\\ude08|\\ud83d\\ude07|\\ud83d\\ude00|\\ud83d\\udd67|\\ud83d\\udd66|\\ud83d\\udd65|\\ud83d\\udd64|\\ud83d\\udd63|\\ud83d\\udd62|\\ud83d\\udd61|\\ud83d\\udd60|\\ud83d\\udd5f|\\ud83d\\udd5e|\\ud83d\\udd5d|\\ud83d\\udd5c|\\ud83d\\udd2d|\\ud83d\\udd2c|\\ud83d\\udd15|\\ud83d\\udd09|\\ud83d\\udd08|\\ud83d\\udd07|\\ud83d\\udd06|\\ud83d\\udd05|\\ud83d\\udd04|\\ud83d\\udd02|\\ud83d\\udd01|\\ud83d\\udd00|\\ud83d\\udcf5|\\ud83d\\udcef|\\ud83d\\udced|\\ud83d\\udcec|\\ud83d\\udcb7|\\ud83d\\udcb6|\\ud83d\\udcad|\\ud83d\\udc6d|\\ud83d\\udc6c|\\ud83d\\udc65|\\ud83d\\udc2a|\\ud83d\\udc16|\\ud83d\\udc15|\\ud83d\\udc13|\\ud83d\\udc10|\\ud83d\\udc0f|\\ud83d\\udc0b|\\ud83d\\udc0a|\\ud83d\\udc09|\\ud83d\\udc08|\\ud83d\\udc07|\\ud83d\\udc06|\\ud83d\\udc05|\\ud83d\\udc04|\\ud83d\\udc03|\\ud83d\\udc02|\\ud83d\\udc01|\\ud83d\\udc00|\\ud83c\\udfe4|\\ud83c\\udfc9|\\ud83c\\udfc7|\\ud83c\\udf7c|\\ud83c\\udf50|\\ud83c\\udf4b|\\ud83c\\udf33|\\ud83c\\udf32|\\ud83c\\udf1e|\\ud83c\\udf1d|\\ud83c\\udf1c|\\ud83c\\udf1a|\\ud83c\\udf18|\\ud83c\\udccf|\\ud83c\\udd8e|\\ud83c\\udd91|\\ud83c\\udd92|\\ud83c\\udd93|\\ud83c\\udd94|\\ud83c\\udd95|\\ud83c\\udd96|\\ud83c\\udd97|\\ud83c\\udd98|\\ud83c\\udd99|\\ud83c\\udd9a|\\ud83d\\udc77|\\ud83d\\udec5|\\ud83d\\udec4|\\ud83d\\udec3|\\ud83d\\udec2|\\ud83d\\udec1|\\ud83d\\udebf|\\ud83d\\udeb8|\\ud83d\\udeb7|\\ud83d\\udeb5|\\ud83c\\ude01|\\ud83c\\ude32|\\ud83c\\ude33|\\ud83c\\ude34|\\ud83c\\ude35|\\ud83c\\ude36|\\ud83c\\ude38|\\ud83c\\ude39|\\ud83c\\ude3a|\\ud83c\\ude50|\\ud83c\\ude51|\\ud83c\\udf00|\\ud83c\\udf01|\\ud83c\\udf02|\\ud83c\\udf03|\\ud83c\\udf04|\\ud83c\\udf05|\\ud83c\\udf06|\\ud83c\\udf07|\\ud83c\\udf08|\\ud83c\\udf09|\\ud83c\\udf0a|\\ud83c\\udf0b|\\ud83c\\udf0c|\\ud83c\\udf0f|\\ud83c\\udf11|\\ud83c\\udf13|\\ud83c\\udf14|\\ud83c\\udf15|\\ud83c\\udf19|\\ud83c\\udf1b|\\ud83c\\udf1f|\\ud83c\\udf20|\\ud83c\\udf30|\\ud83c\\udf31|\\ud83c\\udf34|\\ud83c\\udf35|\\ud83c\\udf37|\\ud83c\\udf38|\\ud83c\\udf39|\\ud83c\\udf3a|\\ud83c\\udf3b|\\ud83c\\udf3c|\\ud83c\\udf3d|\\ud83c\\udf3e|\\ud83c\\udf3f|\\ud83c\\udf40|\\ud83c\\udf41|\\ud83c\\udf42|\\ud83c\\udf43|\\ud83c\\udf44|\\ud83c\\udf45|\\ud83c\\udf46|\\ud83c\\udf47|\\ud83c\\udf48|\\ud83c\\udf49|\\ud83c\\udf4a|\\ud83c\\udf4c|\\ud83c\\udf4d|\\ud83c\\udf4e|\\ud83c\\udf4f|\\ud83c\\udf51|\\ud83c\\udf52|\\ud83c\\udf53|\\ud83c\\udf54|\\ud83c\\udf55|\\ud83c\\udf56|\\ud83c\\udf57|\\ud83c\\udf58|\\ud83c\\udf59|\\ud83c\\udf5a|\\ud83c\\udf5b|\\ud83c\\udf5c|\\ud83c\\udf5d|\\ud83c\\udf5e|\\ud83c\\udf5f|\\ud83c\\udf60|\\ud83c\\udf61|\\ud83c\\udf62|\\ud83c\\udf63|\\ud83c\\udf64|\\ud83c\\udf65|\\ud83c\\udf66|\\ud83c\\udf67|\\ud83c\\udf68|\\ud83c\\udf69|\\ud83c\\udf6a|\\ud83c\\udf6b|\\ud83c\\udf6c|\\ud83c\\udf6d|\\ud83c\\udf6e|\\ud83c\\udf6f|\\ud83c\\udf70|\\ud83c\\udf71|\\ud83c\\udf72|\\ud83c\\udf73|\\ud83c\\udf74|\\ud83c\\udf75|\\ud83c\\udf76|\\ud83c\\udf77|\\ud83c\\udf78|\\ud83c\\udf79|\\ud83c\\udf7a|\\ud83c\\udf7b|\\ud83c\\udf80|\\ud83c\\udf81|\\ud83c\\udf82|\\ud83c\\udf83|\\ud83c\\udf84|\\ud83c\\udf85|\\ud83c\\udf86|\\ud83c\\udf87|\\ud83c\\udf88|\\ud83c\\udf89|\\ud83c\\udf8a|\\ud83c\\udf8b|\\ud83c\\udf8c|\\ud83c\\udf8d|\\ud83c\\udf8e|\\ud83c\\udf8f|\\ud83c\\udf90|\\ud83c\\udf91|\\ud83c\\udf92|\\ud83c\\udf93|\\ud83c\\udfa0|\\ud83c\\udfa1|\\ud83c\\udfa2|\\ud83c\\udfa3|\\ud83c\\udfa4|\\ud83c\\udfa5|\\ud83c\\udfa6|\\ud83c\\udfa7|\\ud83c\\udfa8|\\ud83c\\udfa9|\\ud83c\\udfaa|\\ud83c\\udfab|\\ud83c\\udfac|\\ud83c\\udfad|\\ud83c\\udfae|\\ud83c\\udfaf|\\ud83c\\udfb0|\\ud83c\\udfb1|\\ud83c\\udfb2|\\ud83c\\udfb3|\\ud83c\\udfb4|\\ud83c\\udfb5|\\ud83c\\udfb6|\\ud83c\\udfb7|\\ud83c\\udfb8|\\ud83c\\udfb9|\\ud83c\\udfba|\\ud83c\\udfbb|\\ud83c\\udfbc|\\ud83c\\udfbd|\\ud83c\\udfbe|\\ud83c\\udfbf|\\ud83c\\udfc0|\\ud83c\\udfc1|\\ud83c\\udfc2|\\ud83c\\udfc3|\\ud83c\\udfc4|\\ud83c\\udfc6|\\ud83c\\udfc8|\\ud83c\\udfca|\\ud83c\\udfe0|\\ud83c\\udfe1|\\ud83c\\udfe2|\\ud83c\\udfe3|\\ud83c\\udfe5|\\ud83c\\udfe6|\\ud83c\\udfe7|\\ud83c\\udfe8|\\ud83c\\udfe9|\\ud83c\\udfea|\\ud83c\\udfeb|\\ud83c\\udfec|\\ud83c\\udfed|\\ud83c\\udfee|\\ud83c\\udfef|\\ud83c\\udff0|\\ud83d\\udc0c|\\ud83d\\udc0d|\\ud83d\\udc0e|\\ud83d\\udc11|\\ud83d\\udc12|\\ud83d\\udc14|\\ud83d\\udc17|\\ud83d\\udc18|\\ud83d\\udc19|\\ud83d\\udc1a|\\ud83d\\udc1b|\\ud83d\\udc1c|\\ud83d\\udc1d|\\ud83d\\udc1e|\\ud83d\\udc1f|\\ud83d\\udc20|\\ud83d\\udc21|\\ud83d\\udc22|\\ud83d\\udc23|\\ud83d\\udc24|\\ud83d\\udc25|\\ud83d\\udc26|\\ud83d\\udc27|\\ud83d\\udc28|\\ud83d\\udc29|\\ud83d\\udc2b|\\ud83d\\udc2c|\\ud83d\\udc2d|\\ud83d\\udc2e|\\ud83d\\udc2f|\\ud83d\\udc30|\\ud83d\\udc31|\\ud83d\\udc32|\\ud83d\\udc33|\\ud83d\\udc34|\\ud83d\\udc35|\\ud83d\\udc36|\\ud83d\\udc37|\\ud83d\\udc38|\\ud83d\\udc39|\\ud83d\\udc3a|\\ud83d\\udc3b|\\ud83d\\udc3c|\\ud83d\\udc3d|\\ud83d\\udc3e|\\ud83d\\udc40|\\ud83d\\udc42|\\ud83d\\udc43|\\ud83d\\udc44|\\ud83d\\udc45|\\ud83d\\udc46|\\ud83d\\udc47|\\ud83d\\udc48|\\ud83d\\udc49|\\ud83d\\udc4a|\\ud83d\\udc4b|\\ud83d\\udc4c|\\ud83d\\udc4d|\\ud83d\\udc4e|\\ud83d\\udc4f|\\ud83d\\udc50|\\ud83d\\udc51|\\ud83d\\udc52|\\ud83d\\udc53|\\ud83d\\udc54|\\ud83d\\udc55|\\ud83d\\udc56|\\ud83d\\udc57|\\ud83d\\udc58|\\ud83d\\udc59|\\ud83d\\udc5a|\\ud83d\\udc5b|\\ud83d\\udc5c|\\ud83d\\udc5d|\\ud83d\\udc5e|\\ud83d\\udc5f|\\ud83d\\udc60|\\ud83d\\udc61|\\ud83d\\udc62|\\ud83d\\udc63|\\ud83d\\udc64|\\ud83d\\udc66|\\ud83d\\udc67|\\ud83d\\udc68|\\ud83d\\udc69|\\ud83d\\udc6a|\\ud83d\\udc6b|\\ud83d\\udc6e|\\ud83d\\udc6f|\\ud83d\\udc70|\\ud83d\\udc71|\\ud83d\\udc72|\\ud83d\\udc73|\\ud83d\\udc74|\\ud83d\\udc75|\\ud83d\\udc76|\\ud83d\\udeb4|\\ud83d\\udc78|\\ud83d\\udc79|\\ud83d\\udc7a|\\ud83d\\udc7b|\\ud83d\\udc7c|\\ud83d\\udc7d|\\ud83d\\udc7e|\\ud83d\\udc7f|\\ud83d\\udc80|\\ud83d\\udc81|\\ud83d\\udc82|\\ud83d\\udc83|\\ud83d\\udc84|\\ud83d\\udc85|\\ud83d\\udc86|\\ud83d\\udc87|\\ud83d\\udc88|\\ud83d\\udc89|\\ud83d\\udc8a|\\ud83d\\udc8b|\\ud83d\\udc8c|\\ud83d\\udc8d|\\ud83d\\udc8e|\\ud83d\\udc8f|\\ud83d\\udc90|\\ud83d\\udc91|\\ud83d\\udc92|\\ud83d\\udc93|\\ud83d\\udc94|\\ud83d\\udc95|\\ud83d\\udc96|\\ud83d\\udc97|\\ud83d\\udc98|\\ud83d\\udc99|\\ud83d\\udc9a|\\ud83d\\udc9b|\\ud83d\\udc9c|\\ud83d\\udc9d|\\ud83d\\udc9e|\\ud83d\\udc9f|\\ud83d\\udca0|\\ud83d\\udca1|\\ud83d\\udca2|\\ud83d\\udca3|\\ud83d\\udca4|\\ud83d\\udca5|\\ud83d\\udca6|\\ud83d\\udca7|\\ud83d\\udca8|\\ud83d\\udca9|\\ud83d\\udcaa|\\ud83d\\udcab|\\ud83d\\udcac|\\ud83d\\udcae|\\ud83d\\udcaf|\\ud83d\\udcb0|\\ud83d\\udcb1|\\ud83d\\udcb2|\\ud83d\\udcb3|\\ud83d\\udcb4|\\ud83d\\udcb5|\\ud83d\\udcb8|\\ud83d\\udcb9|\\ud83d\\udcba|\\ud83d\\udcbb|\\ud83d\\udcbc|\\ud83d\\udcbd|\\ud83d\\udcbe|\\ud83d\\udcbf|\\ud83d\\udcc0|\\ud83d\\udcc1|\\ud83d\\udcc2|\\ud83d\\udcc3|\\ud83d\\udcc4|\\ud83d\\udcc5|\\ud83d\\udcc6|\\ud83d\\udcc7|\\ud83d\\udcc8|\\ud83d\\udcc9|\\ud83d\\udcca|\\ud83d\\udccb|\\ud83d\\udccc|\\ud83d\\udccd|\\ud83d\\udcce|\\ud83d\\udccf|\\ud83d\\udcd0|\\ud83d\\udcd1|\\ud83d\\udcd2|\\ud83d\\udcd3|\\ud83d\\udcd4|\\ud83d\\udcd5|\\ud83d\\udcd6|\\ud83d\\udcd7|\\ud83d\\udcd8|\\ud83d\\udcd9|\\ud83d\\udcda|\\ud83d\\udcdb|\\ud83d\\udcdc|\\ud83d\\udcdd|\\ud83d\\udcde|\\ud83d\\udcdf|\\ud83d\\udce0|\\ud83d\\udce1|\\ud83d\\udce2|\\ud83d\\udce3|\\ud83d\\udce4|\\ud83d\\udce5|\\ud83d\\udce6|\\ud83d\\udce7|\\ud83d\\udce8|\\ud83d\\udce9|\\ud83d\\udcea|\\ud83d\\udceb|\\ud83d\\udcee|\\ud83d\\udcf0|\\ud83d\\udcf1|\\ud83d\\udcf2|\\ud83d\\udcf3|\\ud83d\\udcf4|\\ud83d\\udcf6|\\ud83d\\udcf7|\\ud83d\\udcf9|\\ud83d\\udcfa|\\ud83d\\udcfb|\\ud83d\\udcfc|\\ud83d\\udd03|\\ud83d\\udd0a|\\ud83d\\udd0b|\\ud83d\\udd0c|\\ud83d\\udd0d|\\ud83d\\udd0e|\\ud83d\\udd0f|\\ud83d\\udd10|\\ud83d\\udd11|\\ud83d\\udd12|\\ud83d\\udd13|\\ud83d\\udd14|\\ud83d\\udd16|\\ud83d\\udd17|\\ud83d\\udd18|\\ud83d\\udd19|\\ud83d\\udd1a|\\ud83d\\udd1b|\\ud83d\\udd1c|\\ud83d\\udd1d|\\ud83d\\udd1e|\\ud83d\\udd1f|\\ud83d\\udd20|\\ud83d\\udd21|\\ud83d\\udd22|\\ud83d\\udd23|\\ud83d\\udd24|\\ud83d\\udd25|\\ud83d\\udd26|\\ud83d\\udd27|\\ud83d\\udd28|\\ud83d\\udd29|\\ud83d\\udd2a|\\ud83d\\udd2b|\\ud83d\\udd2e|\\ud83d\\udd2f|\\ud83d\\udd30|\\ud83d\\udd31|\\ud83d\\udd32|\\ud83d\\udd33|\\ud83d\\udd34|\\ud83d\\udd35|\\ud83d\\udd36|\\ud83d\\udd37|\\ud83d\\udd38|\\ud83d\\udd39|\\ud83d\\udd3a|\\ud83d\\udd3b|\\ud83d\\udd3c|\\ud83d\\udd3d|\\ud83d\\udd50|\\ud83d\\udd51|\\ud83d\\udd52|\\ud83d\\udd53|\\ud83d\\udd54|\\ud83d\\udd55|\\ud83d\\udd56|\\ud83d\\udd57|\\ud83d\\udd58|\\ud83d\\udd59|\\ud83d\\udd5a|\\ud83d\\udd5b|\\ud83d\\uddfb|\\ud83d\\uddfc|\\ud83d\\uddfd|\\ud83d\\uddfe|\\ud83d\\uddff|\\ud83d\\ude01|\\ud83d\\ude02|\\ud83d\\ude03|\\ud83d\\ude04|\\ud83d\\ude05|\\ud83d\\ude06|\\ud83d\\ude09|\\ud83d\\ude0a|\\ud83d\\ude0b|\\ud83d\\ude0c|\\ud83d\\ude0d|\\ud83d\\ude0f|\\ud83d\\ude12|\\ud83d\\ude13|\\ud83d\\ude14|\\ud83d\\ude16|\\ud83d\\ude18|\\ud83d\\ude1a|\\ud83d\\ude1c|\\ud83d\\ude1d|\\ud83d\\ude1e|\\ud83d\\ude20|\\ud83d\\ude21|\\ud83d\\ude22|\\ud83d\\ude23|\\ud83d\\ude24|\\ud83d\\ude25|\\ud83d\\ude28|\\ud83d\\ude29|\\ud83d\\ude2a|\\ud83d\\ude2b|\\ud83d\\ude2d|\\ud83d\\ude30|\\ud83d\\ude31|\\ud83d\\ude32|\\ud83d\\ude33|\\ud83d\\ude35|\\ud83d\\ude37|\\ud83d\\ude38|\\ud83d\\ude39|\\ud83d\\ude3a|\\ud83d\\ude3b|\\ud83d\\ude3c|\\ud83d\\ude3d|\\ud83d\\ude3e|\\ud83d\\ude3f|\\ud83d\\ude40|\\ud83d\\ude45|\\ud83d\\ude46|\\ud83d\\ude47|\\ud83d\\ude48|\\ud83d\\ude49|\\ud83d\\ude4a|\\ud83d\\ude4b|\\ud83d\\ude4c|\\ud83d\\ude4d|\\ud83d\\ude4e|\\ud83d\\ude4f|\\ud83d\\ude80|\\ud83d\\ude83|\\ud83d\\ude84|\\ud83d\\ude85|\\ud83d\\ude87|\\ud83d\\ude89|\\ud83d\\ude8c|\\ud83d\\ude8f|\\ud83d\\ude91|\\ud83d\\ude92|\\ud83d\\ude93|\\ud83d\\ude95|\\ud83d\\ude97|\\ud83d\\ude99|\\ud83d\\ude9a|\\ud83d\\udea2|\\ud83d\\udea4|\\ud83d\\udea5|\\ud83d\\udea7|\\ud83d\\udea8|\\ud83d\\udea9|\\ud83d\\udeaa|\\ud83d\\udeab|\\ud83d\\udeac|\\ud83d\\udead|\\ud83d\\udeb2|\\ud83d\\udeb6|\\ud83d\\udeb9|\\ud83d\\udeba|\\ud83d\\udebb|\\ud83d\\udebc|\\ud83d\\udebd|\\ud83d\\udebe|\\ud83d\\udec0|\\ud83c\\udde6|\\ud83c\\udde7|\\ud83c\\udde8|\\ud83c\\udde9|\\ud83c\\uddea|\\ud83c\\uddeb|\\ud83c\\uddec|\\ud83c\\udded|\\ud83c\\uddee|\\ud83c\\uddef|\\ud83c\\uddf0|\\ud83c\\uddf1|\\ud83c\\uddf2|\\ud83c\\uddf3|\\ud83c\\uddf4|\\ud83c\\uddf5|\\ud83c\\uddf6|\\ud83c\\uddf7|\\ud83c\\uddf8|\\ud83c\\uddf9|\\ud83c\\uddfa|\\ud83c\\uddfb|\\ud83c\\uddfc|\\ud83c\\uddfd|\\ud83c\\uddfe|\\ud83c\\uddff|\\ud83c\\udf0d|\\ud83c\\udf0e|\\ud83c\\udf10|\\ud83c\\udf12|\\ud83c\\udf16|\\ud83c\\udf17|\\ue50a|\\u27b0|\\u2797|\\u2796|\\u2795|\\u2755|\\u2754|\\u2753|\\u274e|\\u274c|\\u2728|\\u270b|\\u270a|\\u2705|\\u26ce|\\u23f3|\\u23f0|\\u23ec|\\u23eb|\\u23ea|\\u23e9|\\u27bf|\\u00a9|\\u00ae)|(?:(?:\\ud83c\\udc04|\\ud83c\\udd70|\\ud83c\\udd71|\\ud83c\\udd7e|\\ud83c\\udd7f|\\ud83c\\ude02|\\ud83c\\ude1a|\\ud83c\\ude2f|\\ud83c\\ude37|\\u3299|\\u303d|\\u3030|\\u2b55|\\u2b50|\\u2b1c|\\u2b1b|\\u2b07|\\u2b06|\\u2b05|\\u2935|\\u2934|\\u27a1|\\u2764|\\u2757|\\u2747|\\u2744|\\u2734|\\u2733|\\u2716|\\u2714|\\u2712|\\u270f|\\u270c|\\u2709|\\u2708|\\u2702|\\u26fd|\\u26fa|\\u26f5|\\u26f3|\\u26f2|\\u26ea|\\u26d4|\\u26c5|\\u26c4|\\u26be|\\u26bd|\\u26ab|\\u26aa|\\u26a1|\\u26a0|\\u2693|\\u267f|\\u267b|\\u3297|\\u2666|\\u2665|\\u2663|\\u2660|\\u2653|\\u2652|\\u2651|\\u2650|\\u264f|\\u264e|\\u264d|\\u264c|\\u264b|\\u264a|\\u2649|\\u2648|\\u263a|\\u261d|\\u2615|\\u2614|\\u2611|\\u260e|\\u2601|\\u2600|\\u25fe|\\u25fd|\\u25fc|\\u25fb|\\u25c0|\\u25b6|\\u25ab|\\u25aa|\\u24c2|\\u231b|\\u231a|\\u21aa|\\u21a9|\\u2199|\\u2198|\\u2197|\\u2196|\\u2195|\\u2194|\\u2139|\\u2122|\\u2049|\\u203c|\\u2668)([\\uFE0E\\uFE0F]?)))', 'g'); +// https://mths.be/emoji +export const regexExEmojis3 = /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E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DEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC08\uDC26](?:\u200D\u2B1B)?|[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC2\uDECE-\uDEDB\uDEE0-\uDEE8]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; +const regexExEmojis4 = /([#0-9]\u20E3)|[\xA9\xAE\u203C\u2047-\u2049\u2122\u2139\u3030\u303D\u3297\u3299][\uFE00-\uFEFF]?|[\u2190-\u21FF][\uFE00-\uFEFF]?|[\u2300-\u23FF][\uFE00-\uFEFF]?|[\u2460-\u24FF][\uFE00-\uFEFF]?|[\u25A0-\u25FF][\uFE00-\uFEFF]?|[\u2600-\u27BF][\uFE00-\uFEFF]?|[\u2900-\u297F][\uFE00-\uFEFF]?|[\u2B00-\u2BF0][\uFE00-\uFEFF]?|(?:\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDEFF])[\uFE00-\uFEFF]?/g; +//# sourceMappingURL=strings.js.map \ No newline at end of file diff --git a/packages/commons/dist/lib/strings.js.map b/packages/commons/dist/lib/strings.js.map new file mode 100644 index 00000000..efec9a9b --- /dev/null +++ b/packages/commons/dist/lib/strings.js.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.js","sourceRoot":"","sources":["../../src/lib/strings.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,aAAa,GAAG,0mVAA0mV,CAAC;AAExoV,8CAA8C;AAC9C,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,MAAM,CAAC,ouYAAouY,EAAE,GAAG,CAAC,CAAA;AAEnxY,wBAAwB;AACxB,MAAM,CAAC,MAAM,cAAc,GAAG,62WAA62W,CAAC;AAE54W,MAAM,cAAc,GAAG,mYAAmY,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/logger.d.ts b/packages/commons/dist/logger.d.ts new file mode 100644 index 00000000..b9b3bbfc --- /dev/null +++ b/packages/commons/dist/logger.d.ts @@ -0,0 +1,5 @@ +import { Logger } from "tslog"; +export declare function createLogger(name: string, options?: any): Logger; +export declare const defaultLogger: Logger; +export { MODULE_NAME } from './constants.js'; +export declare const logger: Logger; diff --git a/packages/commons/dist/logger.js b/packages/commons/dist/logger.js new file mode 100644 index 00000000..45e0046f --- /dev/null +++ b/packages/commons/dist/logger.js @@ -0,0 +1,15 @@ +import { Logger } from "tslog"; +export function createLogger(name, options) { + return new Logger({ + name, + type: 'pretty', + ...options, + }); +} +export const defaultLogger = createLogger('DefaultLogger', { + minLevel: 1 +}); +import { MODULE_NAME } from './constants.js'; +export { MODULE_NAME } from './constants.js'; +export const logger = createLogger(MODULE_NAME, {}); +//# sourceMappingURL=logger.js.map \ No newline at end of file diff --git a/packages/commons/dist/logger.js.map b/packages/commons/dist/logger.js.map new file mode 100644 index 00000000..bec77130 --- /dev/null +++ b/packages/commons/dist/logger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,MAAM,EAAE,MAAM,OAAO,CAAA;AAE/C,MAAM,UAAU,YAAY,CAAC,IAAY,EAAE,OAAa;IACpD,OAAO,IAAI,MAAM,CAAC;QACd,IAAI;QACJ,IAAI,EAAE,QAAQ;QACd,GAAG,OAAO;KACb,CAAC,CAAA;AACN,CAAC;AACD,MAAM,CAAC,MAAM,aAAa,GAAG,YAAY,CAAC,eAAe,EAAE;IACvD,QAAQ,EAAE,CAAC;CACd,CAAC,CAAA;AAEF,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAE5C,MAAM,CAAC,MAAM,MAAM,GAAG,YAAY,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/os.d.ts b/packages/commons/dist/os.d.ts new file mode 100644 index 00000000..aee17e11 --- /dev/null +++ b/packages/commons/dist/os.d.ts @@ -0,0 +1,10 @@ +export declare enum EPlatform { + Linux = "linux", + Windows = "win32", + OSX = "darwin" +} +export declare enum EArch { + x64 = "64", + x32 = "32" +} +export declare const is_windows: () => boolean; diff --git a/packages/commons/dist/os.js b/packages/commons/dist/os.js new file mode 100644 index 00000000..10efaa47 --- /dev/null +++ b/packages/commons/dist/os.js @@ -0,0 +1,13 @@ +export var EPlatform; +(function (EPlatform) { + EPlatform["Linux"] = "linux"; + EPlatform["Windows"] = "win32"; + EPlatform["OSX"] = "darwin"; +})(EPlatform = EPlatform || (EPlatform = {})); +export var EArch; +(function (EArch) { + EArch["x64"] = "64"; + EArch["x32"] = "32"; +})(EArch = EArch || (EArch = {})); +export const is_windows = () => process && (process.platform === 'win32'); +//# sourceMappingURL=os.js.map \ No newline at end of file diff --git a/packages/commons/dist/os.js.map b/packages/commons/dist/os.js.map new file mode 100644 index 00000000..bd002ee5 --- /dev/null +++ b/packages/commons/dist/os.js.map @@ -0,0 +1 @@ +{"version":3,"file":"os.js","sourceRoot":"","sources":["../src/os.ts"],"names":[],"mappings":"AAAA,MAAM,CAAN,IAAY,SAIX;AAJD,WAAY,SAAS;IACpB,4BAAe,CAAA;IACf,8BAAiB,CAAA;IACjB,2BAAc,CAAA;AACf,CAAC,EAJW,SAAS,GAAT,SAAS,KAAT,SAAS,QAIpB;AACD,MAAM,CAAN,IAAY,KAGX;AAHD,WAAY,KAAK;IAChB,mBAAU,CAAA;IACV,mBAAU,CAAA;AACX,CAAC,EAHW,KAAK,GAAL,KAAK,KAAL,KAAK,QAGhB;AACD,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/osr/component.d.ts b/packages/commons/dist/osr/component.d.ts new file mode 100644 index 00000000..25b9a396 --- /dev/null +++ b/packages/commons/dist/osr/component.d.ts @@ -0,0 +1,56 @@ +import { IDiscourseUploadImage } from './discourse.js'; +export interface IDiscourseItemCommons { + forum?: string | boolean; + forumTitle?: string; + forumCategory?: number; + forumTags?: string | string[]; + forumPostId?: number; + forumTopicId?: number; + forumUserId?: number; + forumUserName?: string; + forumPostHash?: string; + forumUploads?: Record; +} +export interface IComponentConfig extends IDiscourseItemCommons { + cart_id?: string; + code: string; + price?: number; + cscartCats?: number[]; + cscartId?: number; + vendorId?: number; + version?: string; + status?: string; + authors: IAuthor[]; + replaced_by?: string; + alternatives?: string[]; + flags?: number; + howto_categories?: string | string[]; + sourceLanguage?: string; + last_sync_ts?: number; + download?: boolean; + edrawings?: string; + name: string; + showDimensions?: boolean; + showParts?: boolean; + slug: string; + score?: number; + Preview3d?: boolean; + keywords?: string; + meta_keywords?: string; + steps?: any; + /** + * @deprecated + */ + category: string; + product_dimensions?: string; + production?: IProduction; +} +export interface IAuthor { + name: string; + url: string; +} +export interface IProduction { + "fusion-folder": string; + "nc-folder": string; + cam: IAuthor[]; +} diff --git a/packages/commons/dist/osr/component.js b/packages/commons/dist/osr/component.js new file mode 100644 index 00000000..0405a223 --- /dev/null +++ b/packages/commons/dist/osr/component.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=component.js.map \ No newline at end of file diff --git a/packages/commons/dist/osr/component.js.map b/packages/commons/dist/osr/component.js.map new file mode 100644 index 00000000..348b3c0d --- /dev/null +++ b/packages/commons/dist/osr/component.js.map @@ -0,0 +1 @@ +{"version":3,"file":"component.js","sourceRoot":"","sources":["../../src/osr/component.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/commons/dist/osr/discourse.d.ts b/packages/commons/dist/osr/discourse.d.ts new file mode 100644 index 00000000..32073832 --- /dev/null +++ b/packages/commons/dist/osr/discourse.d.ts @@ -0,0 +1,15 @@ +export interface IDiscourseUploadImage { + id: number; + url: string; + original_filename: string; + filesize: number; + width: number; + height: number; + thumbnail_width: number; + thumbnail_height: number; + extension: string; + short_url: string; + short_path: string; + retain_hours: any; + human_filesize: string; +} diff --git a/packages/commons/dist/osr/discourse.js b/packages/commons/dist/osr/discourse.js new file mode 100644 index 00000000..d6b28d73 --- /dev/null +++ b/packages/commons/dist/osr/discourse.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=discourse.js.map \ No newline at end of file diff --git a/packages/commons/dist/osr/discourse.js.map b/packages/commons/dist/osr/discourse.js.map new file mode 100644 index 00000000..36e7826f --- /dev/null +++ b/packages/commons/dist/osr/discourse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"discourse.js","sourceRoot":"","sources":["../../src/osr/discourse.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/commons/dist/paths.d.ts b/packages/commons/dist/paths.d.ts new file mode 100644 index 00000000..509db186 --- /dev/null +++ b/packages/commons/dist/paths.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/packages/commons/dist/paths.js b/packages/commons/dist/paths.js new file mode 100644 index 00000000..068ddf8f --- /dev/null +++ b/packages/commons/dist/paths.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=paths.js.map \ No newline at end of file diff --git a/packages/commons/dist/paths.js.map b/packages/commons/dist/paths.js.map new file mode 100644 index 00000000..8cc16045 --- /dev/null +++ b/packages/commons/dist/paths.js.map @@ -0,0 +1 @@ +{"version":3,"file":"paths.js","sourceRoot":"","sources":["../src/paths.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/commons/dist/profile.d.ts b/packages/commons/dist/profile.d.ts new file mode 100644 index 00000000..3bbcfb66 --- /dev/null +++ b/packages/commons/dist/profile.d.ts @@ -0,0 +1,19 @@ +interface EnvVariables { + [key: string]: string; +} +interface EnvConfig { + includes: string[]; + variables: EnvVariables; +} +export interface IProfile { + includes: string[]; + variables: EnvVariables; + env: { + [key: string]: EnvConfig; + }; +} +export declare const resolveConfig: (config: any) => any; +export declare const parseProfile: (profilePath: string, profile: IProfile, options?: { + env: string; +}, rel?: string) => IProfile; +export {}; diff --git a/packages/commons/dist/profile.js b/packages/commons/dist/profile.js new file mode 100644 index 00000000..4e9c9079 --- /dev/null +++ b/packages/commons/dist/profile.js @@ -0,0 +1,77 @@ +import * as path from 'path'; +import { REGEX_VAR } from "@polymech/core/constants.js"; +import { sync as read } from '@polymech/fs/read'; +import { sync as exists } from '@polymech/fs/exists'; +import { isString } from '@polymech/core/types.js'; +import { resolve, substitute } from './variables.js'; +const _resolve = (config) => { + for (const key in config) { + if (config[key] && typeof config[key] == 'string') { + const resolved = substitute(false, config[key], config); + config[key] = resolved; + } + } + return config; +}; +// @todo: Implement the function `resolveConfig` +export const resolveConfig = (config) => { + config = _resolve(config); + config = _resolve(config); + return config; +}; +export const parseProfile = (profilePath, profile, options = { env: 'default' }, rel) => { + profilePath = path.resolve(resolve(profilePath, false, profile.variables)); + if (!exists(profilePath)) { + return; + } + const _profile = read(profilePath, 'json') || { includes: [], variables: {} }; + _profile.includes = _profile.includes || []; + _profile.variables = _profile.variables || {}; + if (options.env && _profile.env && _profile.env[options.env] && _profile.env[options.env].includes) { + profile.includes = [ + ...profile.includes, + ..._profile.includes, + ..._profile.env[options.env].includes + ]; + } + else { + profile.includes = [ + ...profile.includes, + ..._profile.includes + ]; + } + if (options.env && _profile.env && _profile.env[options.env] && _profile.env[options.env].variables) { + profile.variables = { + ...profile.variables, + ..._profile.variables, + ..._profile.env[options.env].variables + }; + } + for (const k in _profile.variables) { + if (isString(_profile.variables[k])) { + _profile.variables[k] = substitute(false, _profile.variables[k], profile.variables); + } + } + profile.variables = { ...profile.variables, ..._profile.variables, ..._profile.env[options.env]?.variables || {} }; + for (const k in profile.variables) { + if (isString(profile.variables[k])) { + profile.variables[k] = substitute(false, profile.variables[k], profile.variables); + } + } + profile.includes = Array.from(new Set(profile.includes)); + profile.includes = [ + ...profile.includes.map((i) => { + if (!path.isAbsolute(i) && rel && !i.match(REGEX_VAR)) { + return path.resolve(`${rel}/${i}`); + } + let ret = resolve(i, false, profile.variables); + ret = path.resolve(substitute(false, ret, profile.variables)); + return ret; + }) + ]; + profile.includes = profile.includes.filter((include) => include !== null && + include !== ''); + profile.includes = Array.from(new Set(profile.includes)); + return profile; +}; +//# sourceMappingURL=profile.js.map \ No newline at end of file diff --git a/packages/commons/dist/profile.js.map b/packages/commons/dist/profile.js.map new file mode 100644 index 00000000..ac2df460 --- /dev/null +++ b/packages/commons/dist/profile.js.map @@ -0,0 +1 @@ +{"version":3,"file":"profile.js","sourceRoot":"","sources":["../src/profile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAC5B,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAA;AACvD,OAAO,EAAE,IAAI,IAAI,IAAI,EAAE,MAAM,mBAAmB,CAAA;AAChD,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,MAAM,qBAAqB,CAAA;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAA;AAClD,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AAoBpD,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,EAAE;IACxB,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE;QACtB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diff --git a/packages/commons/dist/shemas/index.d.ts b/packages/commons/dist/shemas/index.d.ts new file mode 100644 index 00000000..bf265d65 --- /dev/null +++ b/packages/commons/dist/shemas/index.d.ts @@ -0,0 +1,23 @@ +import * as CLI from 'yargs'; +import { z, ZodTypeAny, ZodObject } from 'zod'; +export * from './path.js'; +export * from './zod_map.js'; +export declare const generate_interfaces: (schemas: ZodObject[], dst: string) => void; +export declare const enumerateHelpStrings: (schema: ZodTypeAny, path: string[], logger: any) => void; +export declare const yargsDefaults: (yargs: CLI.Argv) => any; +export declare const getInnerSchema: (schema: ZodTypeAny) => ZodTypeAny; +export declare const getInnerType: (type: ZodTypeAny) => any; +export declare const getDefaultValue: (schema: ZodTypeAny) => any; +export declare const getFieldDefaultValue: (schema: ZodTypeAny) => any | undefined; +export declare const getDescription: (schema: ZodTypeAny) => string | undefined; +export declare const toYargs: (yargs: CLI.Argv, zodSchema: ZodObject, options?: { + onKey?: (yargs: CLI.Argv, key: string, options: any) => any; +}) => CLI.Argv; +export declare const WRITERS: { + '.json': (data: any, file: string, name: string, options: {}) => void; +}; +export declare const writer: (file: string) => any; +export declare const write: (schemas: ZodObject[], file: string, name: string, options: {}) => void; +export declare const combineValidatorsOr: (validators: z.ZodTypeAny[]) => z.ZodEffects; +export declare const combineValidatorsOrUsingZod: (validators: z.ZodTypeAny[]) => z.ZodTypeAny; +export declare const combineValidatorsOrUsingZod2: (validators: z.ZodTypeAny[]) => z.ZodTypeAny; diff --git a/packages/commons/dist/shemas/index.js b/packages/commons/dist/shemas/index.js new file mode 100644 index 00000000..5ba0d804 --- /dev/null +++ b/packages/commons/dist/shemas/index.js @@ -0,0 +1,204 @@ +import * as path from 'path'; +import { z, ZodObject, ZodEffects, ZodOptional, ZodDefault } from 'zod'; +import { sync as writeFS } from '@polymech/fs/write'; +import { zodToTs, printNode } from 'zod-to-ts'; +import { zodToJsonSchema } from "zod-to-json-schema"; +import { logger } from '@/logger.js'; +export * from './path.js'; +export * from './zod_map.js'; +export const generate_interfaces = (schemas, dst) => { + const types = schemas.map(schema => `export interface ${schema.description || 'IOptions'} ${printNode(zodToTs(schema).node)}`); + writeFS(dst, types.join('\n')); +}; +export const enumerateHelpStrings = (schema, path = [], logger) => { + if (schema instanceof ZodObject) { + for (const key in schema.shape) { + const nestedSchema = schema.shape[key]; + enumerateHelpStrings(nestedSchema, [...path, key], logger); + } + } + else { + const description = schema._def.description; + if (description) { + logger.debug(`\t ${path.join('.')}: ${description}`); + } + } +}; +export const yargsDefaults = (yargs) => yargs.parserConfiguration({ "camel-case-expansion": false }); +export const getInnerSchema = (schema) => { + while (schema instanceof ZodEffects) { + schema = schema._def.schema; + } + return schema; +}; +export const getInnerType = (type) => { + while (type instanceof ZodOptional) { + type = type._def.innerType; + } + while (type._def.typeName === 'ZodDefault' || type._def.typeName === 'ZodOptional') { + type = type._def.innerType; + } + return type._def.typeName; +}; +export const getDefaultValue = (schema) => { + if (schema instanceof ZodDefault) { + return schema._def.defaultValue(); + } + return undefined; +}; +export const getFieldDefaultValue = (schema) => { + if (!schema) { + return undefined; + } + if (schema._def.typeName === 'ZodDefault') { + return schema._def.defaultValue(); + } + if (schema instanceof ZodOptional) { + return getFieldDefaultValue(schema.unwrap()); + } + if (schema instanceof ZodEffects) { + return getFieldDefaultValue(schema._def.schema); + } + if (typeof schema._def) { + return getFieldDefaultValue(schema._def.schema); + } + return undefined; +}; +export const getDescription = (schema) => { + if (!schema) { + return undefined; + } + if (schema._def.description) { + return schema._def.description; + } + if (schema instanceof ZodOptional) { + return getDescription(schema.unwrap()); + } + if (schema instanceof ZodEffects) { + return getDescription(schema._def.schema); + } + if (typeof schema._def) { + return getDescription(schema._def.schema); + } + return undefined; +}; +export const toYargs = (yargs, zodSchema, options) => { + yargsDefaults(yargs); + try { + const shape = zodSchema.shape; + for (const key in shape) { + const zodField = shape[key]; + const innerDef = getInnerSchema(zodField); + if (!innerDef) { + continue; + } + let type; + const inner_type = getInnerType(innerDef); + let descriptionExtra = ''; + switch (inner_type) { + case 'ZodString': + type = 'string'; + break; + case 'ZodBoolean': + type = 'boolean'; + break; + case 'ZodNumber': + type = 'number'; + break; + case 'ZodOptional': + case 'ZodEnum': + type = getInnerType(innerDef); + if (innerDef._def.typeName === 'ZodEnum') { + descriptionExtra = `\n\t ${innerDef._def.values.join(' \n\t ')}`; + } + break; + } + const defaultValue = getFieldDefaultValue(zodField); + let handled = false; + const args = { + type, + default: defaultValue, + describe: `${zodField._def.description || ''} ${descriptionExtra}`.trim() + }; + if (options?.onKey) { + handled = options.onKey(yargs, key, args); + } + if (!handled) { + yargs.option(key, args); + } + } + return yargs; + } + catch (error) { + logger.error('Error processing schema:', error); + return yargs; + } +}; +///////////////////////////////////////////////////////// +// +// Schema Writers +// +const extension = (file) => path.parse(file).ext; +const json = (data, file, name, options) => writeFS(file, data.map((s) => zodToJsonSchema(s, name))); +export const WRITERS = { + '.json': json +}; +export const writer = (file) => WRITERS[extension(file)]; +export const write = (schemas, file, name, options) => { + if (!WRITERS[extension(file)]) { + logger.error(`No writer found for file extension: ${extension(file)} : file: ${file}`); + return; + } + logger.debug(`Writing schema to ${file} : ${name}`); + try { + writer(file)(schemas, file, name, options); + } + catch (e) { + logger.trace(`Error writing schema to ${file} : ${name}`, e, e.stack, e.message); + } +}; +//////////////////////////////////////////////////////////////////// +// +// Schema Combinators +export const combineValidatorsOr = (validators) => { + return z.string().refine((value) => { + const errors = []; + const isValid = validators.some((validator) => { + try { + validator.parse(value); + return true; + } + catch (err) { + errors.push(err.errors); + return false; + } + }); + if (!isValid) { + throw new z.ZodError(errors.flat()); + } + return true; + }, 'Invalid value for all provided validators'); +}; +export const combineValidatorsOrUsingZod = (validators) => { + return validators.reduce((acc, validator) => acc.or(validator)); +}; +export const combineValidatorsOrUsingZod2 = (validators) => { + return validators.reduce((acc, validator) => { + return acc.or(validator).refine((value) => { + try { + acc.parse(value); + return true; + } + catch (errAcc) { + try { + validator.parse(value); + return true; + } + catch (errValidator) { + throw new z.ZodError([...errAcc.errors, ...errValidator.errors]); + } + } + }); + }); +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/commons/dist/shemas/index.js.map b/packages/commons/dist/shemas/index.js.map new file mode 100644 index 00000000..9e7bcded --- /dev/null +++ b/packages/commons/dist/shemas/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/shemas/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAE5B,OAAO,EAAE,CAAC,EAAc,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,KAAK,CAAA;AACnF,OAAO,EAAE,IAAI,IAAI,OAAO,EAAE,MAAM,oBAAoB,CAAA;AACpD,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAEpD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,cAAc,WAAW,CAAA;AACzB,cAAc,cAAc,CAAA;AAW5B,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,OAAyB,EAAE,GAAW,EAAE,EAAE;IAC1E,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,oBAAoB,MAAM,CAAC,WAAW,IAAI,UAAU,IAAI,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IAC9H,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAA;AAClC,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,MAAkB,EAAE,OAAiB,EAAE,EAAE,MAAW,EAAQ,EAAE;IAC/F,IAAI,MAAM,YAAY,SAAS,EAAE;QAC7B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,KAAK,EAAE;YAC5B,MA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E;IACtE,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;AACpE,CAAC,CAAC;AACF,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,UAA0B,EAAE,EAAE;IACvE,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,SAAS,EAAE,EAAE;QACxC,OAAO,GAAG,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACtC,IAAI;gBACA,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBACjB,OAAO,IAAI,CAAC;aACf;YAAC,OAAO,MAAM,EAAE;gBACb,IAAI;oBACA,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;oBACvB,OAAO,IAAI,CAAC;iBACf;gBAAC,OAAO,YAAY,EAAE;oBACnB,MAAM,IAAI,CAAC,CAAC,QAAQ,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC;iBACpE;aACJ;QACL,CAAC,CAAC,CAAA;IACN,CAAC,CAAC,CAAA;AACN,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/shemas/openapi.d.ts b/packages/commons/dist/shemas/openapi.d.ts new file mode 100644 index 00000000..509db186 --- /dev/null +++ b/packages/commons/dist/shemas/openapi.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/packages/commons/dist/shemas/openapi.js b/packages/commons/dist/shemas/openapi.js new file mode 100644 index 00000000..244dadf3 --- /dev/null +++ b/packages/commons/dist/shemas/openapi.js @@ -0,0 +1,22 @@ +export {}; +/* +export const openapi = (data: ZodObject[], file: string, name: string, options: {}) => { + const registry = new OpenAPIRegistry() + data.forEach((s) => registry.register(s.description, s)) + const generator = new OpenApiGeneratorV3(registry.definitions) + const component = generator.generateComponents() + // const content = stringifyYAML(component) + return component +} +*/ +/* +const yaml = (data: ZodObject[], file: string, name: string, options: {}) => { + const registry = new OpenAPIRegistry() + data.forEach((s) => registry.register(s.description, s)) + const generator = new OpenApiGeneratorV3(registry.definitions) + const component = generator.generateComponents() + logger.debug(`Writing schema to ${file} : ${name}`,component) + writeFS(file,stringifyYAML(component)) +} +*/ +//# sourceMappingURL=openapi.js.map \ No newline at end of file diff --git a/packages/commons/dist/shemas/openapi.js.map b/packages/commons/dist/shemas/openapi.js.map new file mode 100644 index 00000000..6fe20046 --- /dev/null +++ b/packages/commons/dist/shemas/openapi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"openapi.js","sourceRoot":"","sources":["../../src/shemas/openapi.ts"],"names":[],"mappings":";AAAA;;;;;;;;;EASE;AACF;;;;;;;;;EASE"} \ No newline at end of file diff --git a/packages/commons/dist/shemas/path.d.ts b/packages/commons/dist/shemas/path.d.ts new file mode 100644 index 00000000..a7c00e9f --- /dev/null +++ b/packages/commons/dist/shemas/path.d.ts @@ -0,0 +1,30 @@ +import { z, ZodTypeAny } from 'zod'; +export declare enum E_PATH { + ENSURE_PATH_EXISTS = 1, + INVALID_INPUT = 2, + ENSURE_DIRECTORY_WRITABLE = 3, + ENSURE_FILE_IS_JSON = 4, + ENSURE_PATH_IS_ABSOLUTE = 5, + ENSURE_PATH_IS_RELATIVE = 6, + GET_PATH_INFO = 7 +} +export declare const Transformers: Record; +export declare const TransformersDescription: { + description: string; + fn: any; +}[]; +export declare const extendSchema: (baseSchema: z.ZodObject, extend: Record) => z.ZodObject, "strip", z.ZodTypeAny, { + [x: string]: any; +}, { + [x: string]: any; +}>; +export declare const ENSURE_DIRECTORY_WRITABLE: (inputPath: string, ctx: any, variables: Record) => string; +export declare const IS_VALID_STRING: (inputPath: string) => boolean; +export declare const ENSURE_PATH_EXISTS: (inputPath: string, ctx: any, variables: Record) => string; +export declare const test: () => z.ZodObject, "strip", z.ZodTypeAny, { + [x: string]: any; +}, { + [x: string]: any; +}>; +export declare const Templates: Record; +export declare const extend: (baseSchema: ZodTypeAny, template: any, variables?: Record) => z.ZodTypeAny; diff --git a/packages/commons/dist/shemas/path.js b/packages/commons/dist/shemas/path.js new file mode 100644 index 00000000..8e548037 --- /dev/null +++ b/packages/commons/dist/shemas/path.js @@ -0,0 +1,239 @@ +import { z } from 'zod'; +import * as path from 'path'; +import { accessSync, constants, lstatSync, existsSync } from 'fs'; +import { isString } from '@polymech/core/primitives.js'; +import { logger } from '@/logger.js'; +import { sync as exists } from '@polymech/fs/exists'; +import { sync as read } from '@polymech/fs/read'; +import { DEFAULT_VARS, resolve, resolveVariables } from '@/variables.js'; +import { getDescription } from '@/shemas/index.js'; +import { isFile } from '@/lib/fs.js'; +const DefaultPathSchemaBase = z.string().describe('Path to a file or directory'); +const PathErrorMessages = { + INVALID_INPUT: 'INVALID_INPUT: ${inputPath}', + PATH_DOES_NOT_EXIST: 'Path does not exist ${inputPath} = ${resolvedPath}', + DIRECTORY_NOT_WRITABLE: 'Directory is not writable ${inputPath} = ${resolvedPath}', + NOT_A_DIRECTORY: 'Path is not a directory or does not exist ${inputPath} = ${resolvedPath}', + NOT_A_JSON_FILE: 'File is not a JSON file or does not exist ${inputPath} = ${resolvedPath}', + PATH_NOT_ABSOLUTE: 'Path is not absolute ${inputPath} = ${resolvedPath}', + PATH_NOT_RELATIVE: 'Path is not relative ${inputPath} = ${resolvedPath}', +}; +export var E_PATH; +(function (E_PATH) { + E_PATH[E_PATH["ENSURE_PATH_EXISTS"] = 1] = "ENSURE_PATH_EXISTS"; + E_PATH[E_PATH["INVALID_INPUT"] = 2] = "INVALID_INPUT"; + E_PATH[E_PATH["ENSURE_DIRECTORY_WRITABLE"] = 3] = "ENSURE_DIRECTORY_WRITABLE"; + E_PATH[E_PATH["ENSURE_FILE_IS_JSON"] = 4] = "ENSURE_FILE_IS_JSON"; + E_PATH[E_PATH["ENSURE_PATH_IS_ABSOLUTE"] = 5] = "ENSURE_PATH_IS_ABSOLUTE"; + E_PATH[E_PATH["ENSURE_PATH_IS_RELATIVE"] = 6] = "ENSURE_PATH_IS_RELATIVE"; + E_PATH[E_PATH["GET_PATH_INFO"] = 7] = "GET_PATH_INFO"; +})(E_PATH = E_PATH || (E_PATH = {})); +export const Transformers = { + resolve: (val, variables = {}) => { + if (!val) { + return null; + } + return { + resolved: path.resolve(resolve(val, false, variables)), + source: val + }; + }, + json: (val, variables = {}) => { + if (!val) { + return null; + } + const resolved = path.resolve(resolve(isString(val) ? val : val.source, false, variables)); + return { + resolved, + source: val, + value: read(resolved, 'json') + }; + }, + string: (val, variables = {}) => { + if (!val) { + return null; + } + let src = isString(val) ? val : val.source; + src = resolve(src, false, variables); + const resolved = path.resolve(src); + if (!exists(resolved) || !isFile(resolved)) { + return { + resolved, + source: val, + value: null + }; + } + else { + let value = null; + try { + value = read(resolved, 'string'); + } + catch (e) { + logger.error('Failed to read file', { resolved, source: val, error: e.message }); + } + return { + resolved, + source: val, + value + }; + } + } +}; +export const TransformersDescription = [ + { + description: 'RESOLVE_PATH', + fn: Transformers.resolve + }, + { + description: 'READ_JSON', + fn: Transformers.json + }, + { + description: 'READ_STRING', + fn: Transformers.string + } +]; +const extendType = (type, extend, variables = {}) => { + if (Array.isArray(extend.refine)) { + for (const refine of extend.refine) { + type = type.refine(refine); + } + } + else { + type = type.refine(extend.refine); + } + if (Array.isArray(extend.transform)) { + for (const transform of extend.transform) { + type = type.transform((val) => transform(val, variables)); + } + } + else { + type = type.transform(extend.transform); + } + return type; +}; +const extendTypeDescription = (type, extension, variables = {}) => { + const description = getDescription(type) || ''; + let transformerDescriptions = 'Transformers:\n'; + if (Array.isArray(extension.transform)) { + for (const transform of extension.transform) { + transformerDescriptions += transformerDescription(transform) + '\n'; + } + } + else { + transformerDescriptions += transformerDescription(extension.transform) + '\n'; + } + type = type.describe(description + '\n' + transformerDescriptions); + return type; +}; +const transformerDescription = (fn) => { + const description = TransformersDescription.find((t) => t.fn === fn); + return description ? description.description : 'Unknown'; +}; +export const extendSchema = (baseSchema, extend) => { + const baseShape = baseSchema.shape; + const extendedShape = { ...baseShape }; + for (const [key, refines] of Object.entries(extend)) { + if (!baseShape[key]) + continue; + let fieldSchema = baseShape[key]; + if (Array.isArray(refines.refine)) { + for (const refine of refines.refine) { + fieldSchema = fieldSchema.superRefine(refine); + } + } + else { + fieldSchema = fieldSchema.superRefine(refines); + } + if (Array.isArray(refines.transform)) { + for (const transform of refines.transform) { + fieldSchema = fieldSchema.transform((val) => transform(val)); + } + } + else { + fieldSchema = fieldSchema.transform(refines.transform); + } + extendedShape[key] = fieldSchema; + } + return z.object(extendedShape); +}; +export const ENSURE_DIRECTORY_WRITABLE = (inputPath, ctx, variables) => { + const resolvedPath = path.resolve(resolve(inputPath, false, variables)); + const parts = path.parse(resolvedPath); + if (resolvedPath && existsSync(parts.dir) && lstatSync(parts.dir).isDirectory()) { + try { + accessSync(resolvedPath, constants.W_OK); + return resolvedPath; + } + catch (e) { + ctx.addIssue({ + code: E_PATH.ENSURE_DIRECTORY_WRITABLE, + message: resolveVariables(PathErrorMessages.DIRECTORY_NOT_WRITABLE, false, { inputPath, resolvedPath }) + }); + return z.NEVER; + } + } + else { + ctx.addIssue({ + code: E_PATH.ENSURE_DIRECTORY_WRITABLE, + message: resolveVariables(PathErrorMessages.NOT_A_DIRECTORY, false, { inputPath, resolvedPath }) + }); + return z.NEVER; + } +}; +export const IS_VALID_STRING = (inputPath) => { + return isString(inputPath); +}; +export const ENSURE_PATH_EXISTS = (inputPath, ctx, variables) => { + if (!inputPath || !ctx) { + return z.NEVER; + } + if (!isString(inputPath)) { + ctx.addIssue({ + code: E_PATH.INVALID_INPUT, + message: resolveVariables(PathErrorMessages.INVALID_INPUT, false, {}) + }); + return z.NEVER; + } + const resolvedPath = path.resolve(resolve(inputPath, false, variables)); + if (!exists(resolvedPath)) { + ctx.addIssue({ + code: E_PATH.ENSURE_PATH_EXISTS, + message: resolveVariables(PathErrorMessages.PATH_DOES_NOT_EXIST, false, { inputPath, resolvedPath }) + }); + return z.NEVER; + } + return resolvedPath; +}; +export const test = () => { + const BaseCompilerOptions = () => z.object({ + root: DefaultPathSchemaBase.default(`${process.cwd()}`) + }); + const ret = extendSchema(BaseCompilerOptions(), { + root: { + refine: [ + (val, ctx) => ENSURE_DIRECTORY_WRITABLE(val, ctx, DEFAULT_VARS({ exampleVar: 'exampleValue' })), + (val, ctx) => ENSURE_PATH_EXISTS(val, ctx, DEFAULT_VARS({ exampleVar: 'exampleValue' })) + ], + transform: [ + (val) => path.resolve(resolve(val, false, DEFAULT_VARS({ exampleVar: 'exampleValue' }))) + ] + } + }); + return ret; +}; +export const Templates = { + json: { + refine: [IS_VALID_STRING, ENSURE_PATH_EXISTS], + transform: [Transformers.resolve, Transformers.json] + }, + string: { + refine: [ENSURE_PATH_EXISTS], + transform: [Transformers.resolve, Transformers.string] + } +}; +export const extend = (baseSchema, template, variables = {}) => { + const type = extendType(baseSchema, template, variables); + return extendTypeDescription(type, template, variables); +}; +//# sourceMappingURL=path.js.map \ No newline at end of file diff --git a/packages/commons/dist/shemas/path.js.map b/packages/commons/dist/shemas/path.js.map new file mode 100644 index 00000000..01ef004e --- /dev/null +++ b/packages/commons/dist/shemas/path.js.map @@ -0,0 +1 @@ +{"version":3,"file":"path.js","sourceRoot":"","sources":["../../src/shemas/path.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAc,MAAM,KAAK,CAAA;AACnC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAC5B,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,IAAI,CAAA;AAEjE,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAA;AAEvD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEpC,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,MAAM,qBAAqB,CAAA;AACpD,OAAO,EAAE,IAAI,IAAI,IAAI,EAAE,MAAM,mBA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MAAM,MAAM,GAAG,CAAC,UAAsB,EAAE,QAAa,EAAE,YAAoC,EAAE,EAAE,EAAE;IACpG,MAAM,IAAI,GAAG,UAAU,CAAC,UAAU,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAA;IACxD,OAAO,qBAAqB,CAAC,IAAI,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAA;AAC3D,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/shemas/types.d.ts b/packages/commons/dist/shemas/types.d.ts new file mode 100644 index 00000000..7268497a --- /dev/null +++ b/packages/commons/dist/shemas/types.d.ts @@ -0,0 +1,194 @@ +export declare enum FLAG { + /** + * Instruct for no additional extra processing + * @constant + * @type int + */ + NONE = 0, + /** + * Will instruct the pre/post processor to base-64 decode or encode + * @constant + * @type int + */ + BASE_64 = 1, + /** + * Post/Pre process the value with a user function + * @constant + * @type int + */ + USE_FUNCTION = 2, + /** + * Replace variables with local scope's variables during the post/pre process + * @constant + * @type int + */ + REPLACE_VARIABLES = 4, + /** + * Replace variables with local scope's variables during the post/pre process but evaluate the whole string + * as Javascript + * @constant + * @type int + */ + REPLACE_VARIABLES_EVALUATED = 8, + /** + * Will instruct the pre/post processor to escpape evaluated or replaced variables or expressions + * @constant + * @type int + */ + ESCAPE = 16, + /** + * Will instruct the pre/post processor to replace block calls with oridinary vanilla script + * @constant + * @type int + */ + REPLACE_BLOCK_CALLS = 32, + /** + * Will instruct the pre/post processor to remove variable delimitters/placeholders from the final string + * @constant + * @type int + */ + REMOVE_DELIMTTERS = 64, + /** + * Will instruct the pre/post processor to remove "[" ,"]" , "(" , ")" , "{", "}" , "*" , "+" , "." + * @constant + * @type int + */ + ESCAPE_SPECIAL_CHARS = 128, + /** + * Will instruct the pre/post processor to use regular expressions over string substitution + * @constant + * @type int + */ + USE_REGEX = 256, + /** + * Will instruct the pre/post processor to use Filtrex (custom bison parser, needs xexpression) over string substitution + * @constant + * @type int + */ + USE_FILTREX = 512, + /** + * Cascade entry. There are cases where #USE_FUNCTION is not enough or we'd like to avoid further type checking. + * @constant + * @type int + */ + CASCADE = 1024, + /** + * Cascade entry. There are cases where #USE_FUNCTION is not enough or we'd like to avoid further type checking. + * @constant + * @type int + */ + EXPRESSION = 2048, + /** + * Dont parse anything + * @constant + * @type int + */ + DONT_PARSE = 4096, + /** + * Convert to hex + * @constant + * @type int + */ + TO_HEX = 8192, + /** + * Convert to hex + * @constant + * @type int + */ + REPLACE_HEX = 16384, + /** + * Wait for finish + * @constant + * @type int + */ + WAIT = 32768, + /** + * Wait for finish + * @constant + * @type int + */ + DONT_ESCAPE = 65536, + /** + * Flag to mark the maximum core bit mask, after here its user land + * @constant + * @type int + */ + END = 131072 +} +export declare enum EType { + Number = "Number", + String = "String", + Boolean = "Boolean", + Date = "Date", + TimeStamp = "TimeStamp", + Duration = "Duration", + Url = "Url", + UrlScheme = "Url-Scheme", + Asset = "Asset", + Symbol = "Symbol", + Value = "Value", + Values = "Values", + Attribute = "Attribute", + Parameter = "Parameter", + Operation = "Operation", + ParameterOperation = "ParameterOperation", + Template = "Template", + Arguments = "Arguments" +} +export type TVector2D = [number, number]; +export type TVector3D = [number, number, number]; +export type TBBox = [TVector3D, TVector3D]; +export type TQuaternion = [number, number, number, number]; +export type TFlags = Record; +export type TExpression = string | [string | RegExp, { + [key: string]: any; +}]; +export type TOptions = { + flags?: TFlags | { + [key: string]: any; + }; +}; +export interface IUrlScheme { + url: string; + options?: { + [key: string]: any; + }; +} +export interface IAsset { + urlScheme: IUrlScheme; + options?: { + [key: string]: any; + }; +} +export type TSelector = TExpression | [TExpression, { + [key: string]: any; +}]; +export interface ITypeInfo { + type: string; + symbol: bigint; +} +export interface IRef { + key: string | string; + struct: { + [key: string]: any; + }; +} +export interface IAttribute { + type: ITypeInfo; + value: bigint; +} +export interface IParameter { + type: ITypeInfo; + value: bigint; +} +export interface IParameterOperation { + param1: bigint; + param2: bigint; + operation: bigint; +} +export type TTemplate = string | [ITypeInfo | TSelector, { + [key: string]: any; +}]; +export type TArguments = { + [key: string]: any; +} | any[]; diff --git a/packages/commons/dist/shemas/types.js b/packages/commons/dist/shemas/types.js new file mode 100644 index 00000000..917b0b07 --- /dev/null +++ b/packages/commons/dist/shemas/types.js @@ -0,0 +1,140 @@ +export var FLAG; +(function (FLAG) { + /** + * Instruct for no additional extra processing + * @constant + * @type int + */ + FLAG[FLAG["NONE"] = 0] = "NONE"; + /** + * Will instruct the pre/post processor to base-64 decode or encode + * @constant + * @type int + */ + FLAG[FLAG["BASE_64"] = 1] = "BASE_64"; + /** + * Post/Pre process the value with a user function + * @constant + * @type int + */ + FLAG[FLAG["USE_FUNCTION"] = 2] = "USE_FUNCTION"; + /** + * Replace variables with local scope's variables during the post/pre process + * @constant + * @type int + */ + FLAG[FLAG["REPLACE_VARIABLES"] = 4] = "REPLACE_VARIABLES"; + /** + * Replace variables with local scope's variables during the post/pre process but evaluate the whole string + * as Javascript + * @constant + * @type int + */ + FLAG[FLAG["REPLACE_VARIABLES_EVALUATED"] = 8] = "REPLACE_VARIABLES_EVALUATED"; + /** + * Will instruct the pre/post processor to escpape evaluated or replaced variables or expressions + * @constant + * @type int + */ + FLAG[FLAG["ESCAPE"] = 16] = "ESCAPE"; + /** + * Will instruct the pre/post processor to replace block calls with oridinary vanilla script + * @constant + * @type int + */ + FLAG[FLAG["REPLACE_BLOCK_CALLS"] = 32] = "REPLACE_BLOCK_CALLS"; + /** + * Will instruct the pre/post processor to remove variable delimitters/placeholders from the final string + * @constant + * @type int + */ + FLAG[FLAG["REMOVE_DELIMTTERS"] = 64] = "REMOVE_DELIMTTERS"; + /** + * Will instruct the pre/post processor to remove "[" ,"]" , "(" , ")" , "{", "}" , "*" , "+" , "." + * @constant + * @type int + */ + FLAG[FLAG["ESCAPE_SPECIAL_CHARS"] = 128] = "ESCAPE_SPECIAL_CHARS"; + /** + * Will instruct the pre/post processor to use regular expressions over string substitution + * @constant + * @type int + */ + FLAG[FLAG["USE_REGEX"] = 256] = "USE_REGEX"; + /** + * Will instruct the pre/post processor to use Filtrex (custom bison parser, needs xexpression) over string substitution + * @constant + * @type int + */ + FLAG[FLAG["USE_FILTREX"] = 512] = "USE_FILTREX"; + /** + * Cascade entry. There are cases where #USE_FUNCTION is not enough or we'd like to avoid further type checking. + * @constant + * @type int + */ + FLAG[FLAG["CASCADE"] = 1024] = "CASCADE"; + /** + * Cascade entry. There are cases where #USE_FUNCTION is not enough or we'd like to avoid further type checking. + * @constant + * @type int + */ + FLAG[FLAG["EXPRESSION"] = 2048] = "EXPRESSION"; + /** + * Dont parse anything + * @constant + * @type int + */ + FLAG[FLAG["DONT_PARSE"] = 4096] = "DONT_PARSE"; + /** + * Convert to hex + * @constant + * @type int + */ + FLAG[FLAG["TO_HEX"] = 8192] = "TO_HEX"; + /** + * Convert to hex + * @constant + * @type int + */ + FLAG[FLAG["REPLACE_HEX"] = 16384] = "REPLACE_HEX"; + /** + * Wait for finish + * @constant + * @type int + */ + FLAG[FLAG["WAIT"] = 32768] = "WAIT"; + /** + * Wait for finish + * @constant + * @type int + */ + FLAG[FLAG["DONT_ESCAPE"] = 65536] = "DONT_ESCAPE"; + /** + * Flag to mark the maximum core bit mask, after here its user land + * @constant + * @type int + */ + FLAG[FLAG["END"] = 131072] = "END"; +})(FLAG = FLAG || (FLAG = {})); +export var EType; +(function (EType) { + EType["Number"] = "Number"; + EType["String"] = "String"; + EType["Boolean"] = "Boolean"; + EType["Date"] = "Date"; + EType["TimeStamp"] = "TimeStamp"; + EType["Duration"] = "Duration"; + EType["Url"] = "Url"; + EType["UrlScheme"] = "Url-Scheme"; + EType["Asset"] = "Asset"; + EType["Symbol"] = "Symbol"; + EType["Value"] = "Value"; + EType["Values"] = "Values"; + EType["Attribute"] = "Attribute"; + EType["Parameter"] = "Parameter"; + EType["Operation"] = "Operation"; + EType["ParameterOperation"] = "ParameterOperation"; + EType["Template"] = "Template"; + EType["Arguments"] = "Arguments"; +})(EType = EType || (EType = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/packages/commons/dist/shemas/types.js.map b/packages/commons/dist/shemas/types.js.map new file mode 100644 index 00000000..5f8034d1 --- /dev/null +++ b/packages/commons/dist/shemas/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/shemas/types.ts"],"names":[],"mappings":"AAAA,MAAM,CAAN,IAAY,IAoHX;AApHD,WAAY,IAAI;IACf;;;;OAIG;IACH,+BAAiB,CAAA;IACjB;;;;OAIG;IACH,qCAAoB,CAAA;IACpB;;;;OAIG;IACH,+CAAyB,CAAA;IACzB;;;;OAIG;IACH,yDAA8B,CAAA;IAC9B;;;;;OAKG;IACH,6EAAwC,CAAA;IACxC;;;;OAIG;IACH,oCAAmB,CAAA;IACnB;;;;OAIG;IACH,8DAAgC,CAAA;IAChC;;;;OAIG;IACH,0DAA8B,CAAA;IAC9B;;;;OAIG;IACH,iEAAiC,CAAA;IACjC;;;;OAIG;IACH,2CAAsB,CAAA;IACtB;;;;OAIG;IACH,+CAAwB,CAAA;IACxB;;;;OAIG;IACH,wCAAoB,CAAA;IACpB;;;;OAIG;IACH,8CAAuB,CAAA;IACvB;;;;OAIG;IACH,8CAAwB,CAAA;IACxB;;;;OAIG;IACH,sCAAoB,CAAA;IACpB;;;;OAIG;IACH,iDAAyB,CAAA;IACzB;;;;OAIG;IACH,mCAAkB,CAAA;IAClB;;;;OAIG;IACH,iDAAyB,CAAA;IACzB;;;;OAIG;IACH,kCAAiB,CAAA;AAClB,CAAC,EApHW,IAAI,GAAJ,IAAI,KAAJ,IAAI,QAoHf;AAED,MAAM,CAAN,IAAY,KAoBX;AApBD,WAAY,KAAK;IAEb,0BAAiB,CAAA;IACjB,0BAAiB,CAAA;IACjB,4BAAmB,CAAA;IACnB,sBAAa,CAAA;IACb,gCAAuB,CAAA;IACvB,8BAAqB,CAAA;IACrB,oBAAW,CAAA;IACX,iCAAwB,CAAA;IACxB,wBAAe,CAAA;IACf,0BAAiB,CAAA;IACjB,wBAAe,CAAA;IACf,0BAAiB,CAAA;IACjB,gCAAuB,CAAA;IACvB,gCAAuB,CAAA;IACvB,gCAAuB,CAAA;IACvB,kDAAyC,CAAA;IACzC,8BAAqB,CAAA;IACrB,gCAAuB,CAAA;AAC3B,CAAC,EApBW,KAAK,GAAL,KAAK,KAAL,KAAK,QAoBhB"} \ No newline at end of file diff --git a/packages/commons/dist/shemas/vfs.d.ts b/packages/commons/dist/shemas/vfs.d.ts new file mode 100644 index 00000000..509db186 --- /dev/null +++ b/packages/commons/dist/shemas/vfs.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/packages/commons/dist/shemas/vfs.js b/packages/commons/dist/shemas/vfs.js new file mode 100644 index 00000000..8a485af0 --- /dev/null +++ b/packages/commons/dist/shemas/vfs.js @@ -0,0 +1,3 @@ +export {}; +//import { zodToJsonSchema } from "zod-to-json-schema" +//# sourceMappingURL=vfs.js.map \ No newline at end of file diff --git a/packages/commons/dist/shemas/vfs.js.map b/packages/commons/dist/shemas/vfs.js.map new file mode 100644 index 00000000..6d3b7bf6 --- /dev/null +++ b/packages/commons/dist/shemas/vfs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"vfs.js","sourceRoot":"","sources":["../../src/shemas/vfs.ts"],"names":[],"mappings":";AAAA,sDAAsD"} \ No newline at end of file diff --git a/packages/commons/dist/shemas/zod_map.d.ts b/packages/commons/dist/shemas/zod_map.d.ts new file mode 100644 index 00000000..ab947947 --- /dev/null +++ b/packages/commons/dist/shemas/zod_map.d.ts @@ -0,0 +1,46 @@ +import { ZodObject, ZodTypeAny } from 'zod'; +/** + * Manages a collection of Zod schema properties + * and combines them into a single Zod object schema. + * + * @template MetaType The type of metadata you want to store for each field. + * Defaults to Record if not provided. + */ +export declare class ZodMetaMap> { + private fieldMap; + /** + * Adds a Zod schema under a specific key (property name), + * optionally attaching typed metadata. + * + * @param key - The name of the property in the root object. + * @param schema - The Zod schema for that property. + * @param metadata - Optional metadata object (type MetaType). + */ + add(key: string, schema: T, metadata?: MetaType): this; + /** + * Builds and returns a root Zod object + * that combines all properties which were added. + */ + root(): ZodObject>; + /** + * Retrieves the metadata for a specific key, if any. + */ + getMetadata(key: string): MetaType | undefined; + /** + * Static factory method: creates a SchemaMetaManager + * while letting you optionally specify the MetaType. + * + * Usage: + * const manager = SchemaMetaManager.create(); + */ + static create>(): ZodMetaMap; + /** + * Returns a basic UiSchema object that RJSF can use to render form controls. + * + * - Adds a top-level "ui:submitButtonOptions" (example). + * - For each field, we set `ui:title` (uppercase key), + * `ui:description` (from Zod's .describe() if available), + * and a naive placeholder from the default value (if parse(undefined) succeeds). + */ + getUISchema(): Record; +} diff --git a/packages/commons/dist/shemas/zod_map.js b/packages/commons/dist/shemas/zod_map.js new file mode 100644 index 00000000..54f1562e --- /dev/null +++ b/packages/commons/dist/shemas/zod_map.js @@ -0,0 +1,102 @@ +import { z } from 'zod'; +/** + * Manages a collection of Zod schema properties + * and combines them into a single Zod object schema. + * + * @template MetaType The type of metadata you want to store for each field. + * Defaults to Record if not provided. + */ +export class ZodMetaMap { + fieldMap = new Map(); + /** + * Adds a Zod schema under a specific key (property name), + * optionally attaching typed metadata. + * + * @param key - The name of the property in the root object. + * @param schema - The Zod schema for that property. + * @param metadata - Optional metadata object (type MetaType). + */ + add(key, schema, metadata) { + this.fieldMap.set(key, { schema, metadata }); + return this; + } + /** + * Builds and returns a root Zod object + * that combines all properties which were added. + */ + root() { + const shape = {}; + for (const [key, { schema }] of this.fieldMap.entries()) { + shape[key] = schema; + } + return z.object(shape); + } + /** + * Retrieves the metadata for a specific key, if any. + */ + getMetadata(key) { + return this.fieldMap.get(key)?.metadata; + } + /** + * Static factory method: creates a SchemaMetaManager + * while letting you optionally specify the MetaType. + * + * Usage: + * const manager = SchemaMetaManager.create(); + */ + static create() { + return new ZodMetaMap(); + } + /** + * Returns a basic UiSchema object that RJSF can use to render form controls. + * + * - Adds a top-level "ui:submitButtonOptions" (example). + * - For each field, we set `ui:title` (uppercase key), + * `ui:description` (from Zod's .describe() if available), + * and a naive placeholder from the default value (if parse(undefined) succeeds). + */ + getUISchema() { + // Start with some top-level UI schema config (optional) + const uiSchema = { + 'ui:submitButtonOptions': { + props: { + disabled: false, + className: 'btn btn-info', + }, + norender: false, + submitText: 'Submit', + }, + }; + for (const [key, { schema }] of this.fieldMap.entries()) { + let fieldUi = {}; + // Use the Zod description if available + // (Accessing `._def.description` is private/hacky, but commonly done.) + const sAny = schema; + if (sAny?._def?.description) { + fieldUi['ui:description'] = sAny._def.description; + } + // RJSF usually reads 'title' from JSON schema. But if you want + // to override it in UI schema, you can do so: + fieldUi['ui:title'] = key[0].toUpperCase() + key.substr(1).toLowerCase(); + // If the Zod schema allows a default, we can parse(undefined) to get it. + try { + const defaultVal = schema.parse(undefined); + // There's no official 'ui:default' in RJSF, but you could do a placeholder: + fieldUi['ui:placeholder'] = defaultVal; + } + catch { + // no default + } + if (key == 'path') { + debugger; + } + fieldUi = { + ...fieldUi, + ...this.getMetadata(key), + }; + uiSchema[key] = fieldUi; + } + return uiSchema; + } +} +//# sourceMappingURL=zod_map.js.map \ No newline at end of file diff --git a/packages/commons/dist/shemas/zod_map.js.map b/packages/commons/dist/shemas/zod_map.js.map new file mode 100644 index 00000000..696d1617 --- /dev/null +++ b/packages/commons/dist/shemas/zod_map.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zod_map.js","sourceRoot":"","sources":["../../src/shemas/zod_map.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAyB,MAAM,KAAK,CAAC;AAE/C;;;;;;GAMG;AACH,MAAM,OAAO,UAAU;IACX,QAAQ,GAAG,IAAI,GAAG,EAGvB,CAAC;IAEJ;;;;;;;OAOG;IACH,GAAG,CAAuB,GAAW,EAAE,MAAS,EAAE,QAAmB;QACjE,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC7C,OAAO,IAAI,CAAC;IAChB,CAAC;IAED;;;OAGG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AW,EAAE,CAAA;YAExE,yEAAyE;YACzE,IAAI;gBACA,MAAM,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;gBAC3C,4EAA4E;gBAC5E,OAAO,CAAC,gBAAgB,CAAC,GAAG,UAAU,CAAC;aAC1C;YAAC,MAAM;gBACJ,aAAa;aAChB;YACD,IAAG,GAAG,IAAE,MAAM,EAAC;gBACX,QAAQ,CAAA;aACX;YACD,OAAO,GAAG;gBACN,GAAG,OAAO;gBACV,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC;aAC3B,CAAA;YACD,QAAQ,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC;SAC3B;QACD,OAAO,QAAQ,CAAC;IACpB,CAAC;CACJ"} \ No newline at end of file diff --git a/packages/commons/dist/types.d.ts b/packages/commons/dist/types.d.ts new file mode 100644 index 00000000..edf0ce66 --- /dev/null +++ b/packages/commons/dist/types.d.ts @@ -0,0 +1,264 @@ +export interface IConvertedFileMeta { + photoData: Blob; + objectUrl: string; + name: string; + type: string; +} +export interface IUploadedFileMeta { + downloadUrl: string; + contentType?: string | null; + fullPath: string; + name: string; + type: string; + size: number; + timeCreated: string; + updated: string; + data: any; +} +export type IModerationStatus = 'draft' | 'awaiting-moderation' | 'rejected' | 'accepted'; +export interface IModerable { + moderation: IModerationStatus; + _createdBy?: string; + _id?: string; +} +export type ISODateString = string; +export interface IUserState { + user?: IUser; +} +export interface IUser { + _authID: string; + _lastActive?: ISODateString; + userName: string; + displayName: string; + moderation: IModerationStatus; + verified: boolean; + badges?: IUserBadges; + coverImages: IUploadedFileMeta[] | IConvertedFileMeta[]; + links: IExternalLink[]; + userRoles?: string[]; + about?: string | null; + DHSite_id?: number; + DHSite_mention_name?: string; + country?: string | null; + year?: ISODateString; + stats?: IUserStats; + /** keep a map of all howto ids that a user has voted as useful */ + votedUsefulHowtos?: { + [howtoId: string]: boolean; + }; + /** keep a map of all Research ids that a user has voted as useful */ + votedUsefulResearch?: { + [researchId: string]: boolean; + }; + notifications?: INotification[]; +} +interface IUserBadges { + verified: boolean; +} +interface IExternalLink { + url: string; + label: 'email' | 'website' | 'discord' | 'bazar' | 'forum' | 'social media' | 'facebook' | 'instagram' | 'github' | 'linkedin' | 'map' | 'forum' | 'marketplace' | 'other' | 'other-2'; +} +/** + * Track the ids and moderation status as summary for user stats + */ +interface IUserStats { + userCreatedHowtos: { + [id: string]: IModerationStatus; + }; + userCreatedResearch: { + [id: string]: IModerationStatus; + }; + userCreatedEvents: { + [id: string]: IModerationStatus; + }; +} +export type IUserDB = IUser; +export interface INotification { + _id: string; + _created: string; + triggeredBy: { + displayName: string; + userId: string; + }; + relevantUrl?: string; + type: NotificationType; + read: boolean; +} +export type NotificationType = 'new_comment' | 'howto_useful' | 'new_comment_research' | 'research_useful'; +export type PlasticTypeLabel = 'pet' | 'hdpe' | 'pvc' | 'ldpe' | 'pp' | 'ps' | 'other'; +export type MachineBuilderXpLabel = 'electronics' | 'machining' | 'welding' | 'assembling' | 'mould-making' | 'development'; +export type WorkspaceType = 'shredder' | 'sheetpress' | 'extrusion' | 'injection' | 'mix' | 'machine shop' | 'service' | 'educational' | 'supplier' | '3dprint'; +export type TOSR_User_Type = 'Precious Plastic' | 'OSR-Plastic' | 'Unknown' | 'User Contact' | 'Crawler' | 'Fablab' | 'OSE' | 'Meetup'; +export interface IPlasticType { + label: PlasticTypeLabel; + number: string; + imageSrc?: string; +} +export interface IProfileType { + label: string; + imageSrc?: string; + cleanImageSrc?: string; + cleanImageVerifiedSrc?: string; + textLabel?: string; +} +export interface IWorkspaceType { + label: WorkspaceType; + imageSrc?: string; + textLabel?: string; + subText?: string; +} +export interface IMAchineBuilderXp { + label: MachineBuilderXpLabel; +} +export interface IOpeningHours { + day: string; + openFrom: string; + openTo: string; +} +/** + * PP users can have a bunch of custom meta fields depending on profile type + */ +export interface IUserPP extends IUser { + profileType: string; + workspaceType?: WorkspaceType | null; + mapPinDescription?: string | null; + openingHours?: IOpeningHours[]; + collectedPlasticTypes?: PlasticTypeLabel[] | null; + machineBuilderXp?: IMAchineBuilderXp[] | null; + isExpert?: boolean | null; + isV4Member?: boolean | null; +} +export type IUserPPDB = IUserPP; +export interface IGeoLocation { + lng: number; + lat: number; +} +export interface IOA_UserDetail { + lastActive: Date; + profilePicUrl: string; + shortDescription: string; + heroImageUrl: string; + name: string; + profileUrl: string; +} +export interface IGeo_Administrative { + name: string; + description: string; + isoName: string; + order: number; + adminLevel: number; + isoCode: string; + wikidataId: string; + geonameId: number; +} +export interface IGeo_Informative { + name: string; + description: string; + order: number; + isoCode: string; + wikidataId: string; + geonameId: number; +} +export interface IGeo_LocalityInfo { + administrative: IGeo_Administrative[]; + informative: IGeo_Informative[]; +} +export interface IGeo { + latitude: number; + longitude: number; + continent: string; + lookupSource: string; + continentCode: string; + localityLanguageRequested: string; + city: string; + countryName: string; + postcode: string; + countryCode: string; + principalSubdivision: string; + principalSubdivisionCode: string; + plusCode: string; + locality: string; + localityInfo: IGeo_LocalityInfo; +} +export interface IUrl { + name: string; + url: string; +} +export interface IOA_Service { + welding: boolean; + assembling: boolean; + machining: boolean; + electronics: boolean; + molds: boolean; +} +export interface IImage { + url: string; +} +export interface IOSRUserData { + urls: IUrl[]; + description: string; + services: IOA_Service[]; + title: string; + images: IImage[]; + jsError?: boolean; +} +export interface I_OSR_USER { + _created: Date; + location: IGeoLocation; + _modified: Date; + _id: string; + detail: IOA_UserDetail; + type: string; + _deleted: boolean; + moderation: string; + geo: IGeo; + data: IOSRUserData; +} +export interface I_USER_SHORT { + name: string; + email: string; + bazar: string; + web: string; + social: string; + censored: string; + lastActive: Date; + ig: string; +} +export type IProduct = { + slug: string; + name: string; + category: string; + code: string; + forum?: string; + forumCategory?: string; + version?: string; + cart_id?: string; +}; +export interface IDiscourseUser { + id: number; + username: string; + name: string; + avatar_template: string; + active: boolean; + admin: boolean; + moderator: boolean; + last_seen_at: any; + last_emailed_at: string; + created_at: string; + last_seen_age: any; + last_emailed_age: number; + created_at_age: number; + trust_level: number; + manual_locked_trust_level: any; + flag_level: number; + title: any; + time_read: number; + staged: boolean; + days_visited: number; + posts_read_count: number; + topics_entered: number; + post_count: number; +} +export * from './osr/component.js'; +export * from './types_kbot.js'; diff --git a/packages/commons/dist/types.js b/packages/commons/dist/types.js new file mode 100644 index 00000000..777332cc --- /dev/null +++ b/packages/commons/dist/types.js @@ -0,0 +1,3 @@ +export * from './osr/component.js'; +export * from './types_kbot.js'; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/packages/commons/dist/types.js.map b/packages/commons/dist/types.js.map new file mode 100644 index 00000000..a0a28a39 --- /dev/null +++ b/packages/commons/dist/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAyWE,cAAc,oBAAoB,CAAA;AAClC,cAAc,iBAAiB,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/types_cache.d.ts b/packages/commons/dist/types_cache.d.ts new file mode 100644 index 00000000..6d45e813 --- /dev/null +++ b/packages/commons/dist/types_cache.d.ts @@ -0,0 +1,6 @@ +export interface IOptionsCache { + skip?: boolean; + clear?: boolean; + namespace?: string; + cacheRoot?: string; +} diff --git a/packages/commons/dist/types_cache.js b/packages/commons/dist/types_cache.js new file mode 100644 index 00000000..6fbfe68f --- /dev/null +++ b/packages/commons/dist/types_cache.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types_cache.js.map \ No newline at end of file diff --git a/packages/commons/dist/types_cache.js.map b/packages/commons/dist/types_cache.js.map new file mode 100644 index 00000000..9afd1ef1 --- /dev/null +++ b/packages/commons/dist/types_cache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types_cache.js","sourceRoot":"","sources":["../src/types_cache.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/commons/dist/types_common.d.ts b/packages/commons/dist/types_common.d.ts new file mode 100644 index 00000000..c2b7a042 --- /dev/null +++ b/packages/commons/dist/types_common.d.ts @@ -0,0 +1,114 @@ +export interface GeoPos { + lon: number; + lat: number; +} +export interface PATH_INFO { + DIR?: string; + NAME?: string; + FILE_NAME?: string; + FILE_EXT?: string; + PATH?: string; + IS_FILE?: boolean; + IS_FOLDER?: boolean; + IS_EXPRESSION?: boolean; + IS_GLOB?: boolean; + path: string; + GLOB: string; + GLOB_EXTENSIONS: string[]; + FILES: string[]; +} +export interface IDeeplConfig { + auth_key: string; + free_api: boolean; +} +export interface IIgConfig { + username: string; + password: string; +} +export interface ICsCartConfigMySQL { + host: string; + user: string; + database: string; + password: string; +} +export interface ICsCartConfig { + token: string; + url: string; + username: string; + siteUrl?: string; + timeout?: number; + language?: string; + userToken?: string; + mysql?: ICsCartConfigMySQL; +} +export interface IGiteaConfig { + token: string; + url: string; +} +export interface IDiscourseConfig { + host: string; + key: string; + username: string; + rateLimitConcurrency: number; +} +export interface IScaleserp { + key: string; +} +export interface IOSRConfig { + deepl: IDeeplConfig; + ig: IIgConfig; + cscart: ICsCartConfig; + discourse: IDiscourseConfig; + discourse_admin: IDiscourseConfig; + instagram: IIgConfig; + urls: any; + scaleserp?: IScaleserp; + gitea?: IGiteaConfig; +} +export interface SRC_VARIABLES { + SRC_PATH: string; + SRC_DIR: string; + SRC_NAME: string; + SRC_FILE_NAME: string; + SRC_FILE_EXT: string; + SRC_IS_FILE: boolean; + SRC_IS_FOLDER: boolean; + SRC_IS_EXPRESSION: boolean; + SRC_IS_GLOB: boolean; + SRC_GLOB: string; + SRC_GLOB_EXTENSIONS: string[]; + SRC_FILES: string[]; +} +export interface DST_VARIABLES { + DST_PATH: string; + DST_DIR: string; + DST_NAME: string; + DST_FILE_NAME: string; + DST_FILE_EXT: string; + DST_IS_FILE: boolean; + DST_IS_FOLDER: boolean; + DST_IS_EXPRESSION: boolean; + DST_IS_GLOB: boolean; + DST_GLOB: string; + DST_GLOB_EXTENSIONS: string[]; + DST_FILES: string[]; +} +export type PATH_VARIABLES = SRC_VARIABLES & DST_VARIABLES; +export interface IOptionsBase { + variables: PATH_VARIABLES; +} +export interface PATH_INFO { + DIR?: string; + FILE_EXT?: string; + FILE_NAME?: string; + FILES: string[]; + GLOB_EXTENSIONS: string[]; + GLOB: string; + IS_EXPRESSION?: boolean; + IS_FILE?: boolean; + IS_FOLDER?: boolean; + IS_GLOB?: boolean; + NAME?: string; + path: string; + PATH?: string; +} diff --git a/packages/commons/dist/types_common.js b/packages/commons/dist/types_common.js new file mode 100644 index 00000000..42c4931e --- /dev/null +++ b/packages/commons/dist/types_common.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types_common.js.map \ No newline at end of file diff --git a/packages/commons/dist/types_common.js.map b/packages/commons/dist/types_common.js.map new file mode 100644 index 00000000..d9e6110f --- /dev/null +++ b/packages/commons/dist/types_common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types_common.js","sourceRoot":"","sources":["../src/types_common.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/commons/dist/types_gui.d.ts b/packages/commons/dist/types_gui.d.ts new file mode 100644 index 00000000..e76f1e94 --- /dev/null +++ b/packages/commons/dist/types_gui.d.ts @@ -0,0 +1,296 @@ +/** + * Flags to describe a block's execution behavior. + * + * @enum {integer} module=xide/types/RUN_FLAGS + * @memberOf module=xide/types + */ +export declare enum RUN_FLAGS { + /** + * The block can execute child blocks. + * @constant + * @type int + */ + CHILDREN = 32, + /** + * Block is waiting for a message => EXECUTION_STATE==RUNNING + * @constant + * @type int + */ + WAIT = 32768 +} +/** + * Flags to describe a block's execution state. + * + * @enum {integer} module=xide/types/EXECUTION_STATE + * @memberOf module=xide/types + */ +export declare enum EXECUTION_STATE { + /** + * The block is doing nothing and also has done nothing. The is the default state + * @constant + * @type int + */ + NONE = 0, + /** + * The block is running. + * @constant + * @type int + */ + RUNNING = 1, + /** + * The block is an error state. + * @constant + * @type int + */ + ERROR = 2, + /** + * The block is in an paused state. + * @constant + * @type int + */ + PAUSED = 4, + /** + * The block is an finished state, ready to be cleared to "NONE" at the next frame. + * @constant + * @type int + */ + FINISH = 8, + /** + * The block is an stopped state, ready to be cleared to "NONE" at the next frame. + * @constant + * @type int + */ + STOPPED = 16, + /** + * The block has been launched once... + * @constant + * @type int + */ + ONCE = 2147483648, + /** + * Block will be reseted next frame + * @constant + * @type int + */ + RESET_NEXT_FRAME = 8388608, + /** + * Block is locked and so no further inputs can be activated. + * @constant + * @type int + */ + LOCKED = 536870912 +} +export declare enum BLOCK_MODE { + NORMAL = 0, + UPDATE_WIDGET_PROPERTY = 1 +} +/** + * Flags to describe a block's belonging to a standard signal. + * @enum {integer} module=xblox/types/BLOCK_OUTLET + * @memberOf module=xblox/types + */ +export declare enum BLOCK_OUTLET { + NONE = 0, + PROGRESS = 1, + ERROR = 2, + PAUSED = 4, + FINISH = 8, + STOPPED = 16 +} +export declare enum EVENTS { + ON_RUN_BLOCK = "onRunBlock", + ON_RUN_BLOCK_FAILED = "onRunBlockFailed", + ON_RUN_BLOCK_SUCCESS = "onRunBlockSuccess", + ON_BLOCK_SELECTED = "onItemSelected", + ON_BLOCK_UNSELECTED = "onBlockUnSelected", + ON_BLOCK_EXPRESSION_FAILED = "onExpressionFailed", + ON_BUILD_BLOCK_INFO_LIST = "onBuildBlockInfoList", + ON_BUILD_BLOCK_INFO_LIST_END = "onBuildBlockInfoListEnd", + ON_BLOCK_PROPERTY_CHANGED = "onBlockPropertyChanged", + ON_SCOPE_CREATED = "onScopeCreated", + ON_VARIABLE_CHANGED = "onVariableChanged", + ON_CREATE_VARIABLE_CI = "onCreateVariableCI" +} +export declare enum BlockType { + AssignmentExpression = "AssignmentExpression", + ArrayExpression = "ArrayExpression", + BlockStatement = "BlockStatement", + BinaryExpression = "BinaryExpression", + BreakStatement = "BreakStatement", + CallExpression = "CallExpression", + CatchClause = "CatchClause", + ConditionalExpression = "ConditionalExpression", + ContinueStatement = "ContinueStatement", + DoWhileStatement = "DoWhileStatement", + DebuggerStatement = "DebuggerStatement", + EmptyStatement = "EmptyStatement", + ExpressionStatement = "ExpressionStatement", + ForStatement = "ForStatement", + ForInStatement = "ForInStatement", + FunctionDeclaration = "FunctionDeclaration", + FunctionExpression = "FunctionExpression", + Identifier = "Identifier", + IfStatement = "IfStatement", + Literal = "Literal", + LabeledStatement = "LabeledStatement", + LogicalExpression = "LogicalExpression", + MemberExpression = "MemberExpression", + NewExpression = "NewExpression", + ObjectExpression = "ObjectExpression", + Program = "Program", + Property = "Property", + ReturnStatement = "ReturnStatement", + SequenceExpression = "SequenceExpression", + SwitchStatement = "SwitchStatement", + SwitchCase = "SwitchCase", + ThisExpression = "ThisExpression", + ThrowStatement = "ThrowStatement", + TryStatement = "TryStatement", + UnaryExpression = "UnaryExpression", + UpdateExpression = "UpdateExpression", + VariableDeclaration = "VariableDeclaration", + VariableDeclarator = "VariableDeclarator", + WhileStatement = "WhileStatement", + WithStatement = "WithStatement" +} +/** + * Variable Flags + * + * @enum {int} VARIABLE_FLAGS + * @global + */ +export declare enum VARIABLE_FLAGS { + PUBLISH = 2, + PUBLISH_IF_SERVER = 4 +} +export declare enum BLOCK_GROUPS { + VARIABLE = "DriverVariable", + BASIC_COMMAND = "DriverBasicCommand", + CONDITIONAL_COMMAND = "DriverConditionalCommand", + RESPONSE_VARIABLE = "DriverResponseVariable", + RESPONSE_BLOCKS = "conditionalProcess", + RESPONSE_VARIABLES = "processVariables", + BASIC_VARIABLES = "basicVariables" +} +export declare enum COMMAND_TYPES { + BASIC_COMMAND = "basic", + CONDITIONAL_COMMAND = "conditional", + INIT_COMMAND = "init" +} +export declare enum CIFLAG { + /** + * Instruct for no additional extra processing + * @constant + * @type int + */ + NONE = 0, + /** + * Will instruct the pre/post processor to base-64 decode or encode + * @constant + * @type int + */ + BASE_64 = 1, + /** + * Post/Pre process the value with a user function + * @constant + * @type int + */ + USE_FUNCTION = 2, + /** + * Replace variables with local scope's variables during the post/pre process + * @constant + * @type int + */ + REPLACE_VARIABLES = 4, + /** + * Replace variables with local scope's variables during the post/pre process but evaluate the whole string + * as Javascript + * @constant + * @type int + */ + REPLACE_VARIABLES_EVALUATED = 8, + /** + * Will instruct the pre/post processor to escpape evaluated or replaced variables or expressions + * @constant + * @type int + */ + ESCAPE = 16, + /** + * Will instruct the pre/post processor to replace block calls with oridinary vanilla script + * @constant + * @type int + */ + REPLACE_BLOCK_CALLS = 32, + /** + * Will instruct the pre/post processor to remove variable delimitters/placeholders from the final string + * @constant + * @type int + */ + REMOVE_DELIMTTERS = 64, + /** + * Will instruct the pre/post processor to remove "[" ,"]" , "(" , ")" , "{", "}" , "*" , "+" , "." + * @constant + * @type int + */ + ESCAPE_SPECIAL_CHARS = 128, + /** + * Will instruct the pre/post processor to use regular expressions over string substitution + * @constant + * @type int + */ + USE_REGEX = 256, + /** + * Will instruct the pre/post processor to use Filtrex (custom bison parser, needs xexpression) over string substitution + * @constant + * @type int + */ + USE_FILTREX = 512, + /** + * Cascade entry. There are cases where #USE_FUNCTION is not enough or we'd like to avoid further type checking. + * @constant + * @type int + */ + CASCADE = 1024, + /** + * Cascade entry. There are cases where #USE_FUNCTION is not enough or we'd like to avoid further type checking. + * @constant + * @type int + */ + EXPRESSION = 2048, + /** + * Dont parse anything + * @constant + * @type int + */ + DONT_PARSE = 4096, + /** + * Convert to hex + * @constant + * @type int + */ + TO_HEX = 8192, + /** + * Convert to hex + * @constant + * @type int + */ + REPLACE_HEX = 16384, + /** + * Wait for finish + * @constant + * @type int + */ + WAIT = 32768, + /** + * Wait for finish + * @constant + * @type int + */ + DONT_ESCAPE = 65536, + /** + * Flag to mark the maximum core bit mask, after here its user land + * @constant + * @type int + */ + END = 131072 +} diff --git a/packages/commons/dist/types_gui.js b/packages/commons/dist/types_gui.js new file mode 100644 index 00000000..7b45c2ed --- /dev/null +++ b/packages/commons/dist/types_gui.js @@ -0,0 +1,314 @@ +/** + * Flags to describe a block's execution behavior. + * + * @enum {integer} module=xide/types/RUN_FLAGS + * @memberOf module=xide/types + */ +export var RUN_FLAGS; +(function (RUN_FLAGS) { + /** + * The block can execute child blocks. + * @constant + * @type int + */ + RUN_FLAGS[RUN_FLAGS["CHILDREN"] = 32] = "CHILDREN"; + /** + * Block is waiting for a message => EXECUTION_STATE==RUNNING + * @constant + * @type int + */ + RUN_FLAGS[RUN_FLAGS["WAIT"] = 32768] = "WAIT"; +})(RUN_FLAGS = RUN_FLAGS || (RUN_FLAGS = {})); +; +/** + * Flags to describe a block's execution state. + * + * @enum {integer} module=xide/types/EXECUTION_STATE + * @memberOf module=xide/types + */ +export var EXECUTION_STATE; +(function (EXECUTION_STATE) { + /** + * The block is doing nothing and also has done nothing. The is the default state + * @constant + * @type int + */ + EXECUTION_STATE[EXECUTION_STATE["NONE"] = 0] = "NONE"; + /** + * The block is running. + * @constant + * @type int + */ + EXECUTION_STATE[EXECUTION_STATE["RUNNING"] = 1] = "RUNNING"; + /** + * The block is an error state. + * @constant + * @type int + */ + EXECUTION_STATE[EXECUTION_STATE["ERROR"] = 2] = "ERROR"; + /** + * The block is in an paused state. + * @constant + * @type int + */ + EXECUTION_STATE[EXECUTION_STATE["PAUSED"] = 4] = "PAUSED"; + /** + * The block is an finished state, ready to be cleared to "NONE" at the next frame. + * @constant + * @type int + */ + EXECUTION_STATE[EXECUTION_STATE["FINISH"] = 8] = "FINISH"; + /** + * The block is an stopped state, ready to be cleared to "NONE" at the next frame. + * @constant + * @type int + */ + EXECUTION_STATE[EXECUTION_STATE["STOPPED"] = 16] = "STOPPED"; + /** + * The block has been launched once... + * @constant + * @type int + */ + EXECUTION_STATE[EXECUTION_STATE["ONCE"] = 2147483648] = "ONCE"; + /** + * Block will be reseted next frame + * @constant + * @type int + */ + EXECUTION_STATE[EXECUTION_STATE["RESET_NEXT_FRAME"] = 8388608] = "RESET_NEXT_FRAME"; + /** + * Block is locked and so no further inputs can be activated. + * @constant + * @type int + */ + EXECUTION_STATE[EXECUTION_STATE["LOCKED"] = 536870912] = "LOCKED"; // Block is locked for utilisation in xblox +})(EXECUTION_STATE = EXECUTION_STATE || (EXECUTION_STATE = {})); +export var BLOCK_MODE; +(function (BLOCK_MODE) { + BLOCK_MODE[BLOCK_MODE["NORMAL"] = 0] = "NORMAL"; + BLOCK_MODE[BLOCK_MODE["UPDATE_WIDGET_PROPERTY"] = 1] = "UPDATE_WIDGET_PROPERTY"; +})(BLOCK_MODE = BLOCK_MODE || (BLOCK_MODE = {})); +; +/** + * Flags to describe a block's belonging to a standard signal. + * @enum {integer} module=xblox/types/BLOCK_OUTLET + * @memberOf module=xblox/types + */ +export var BLOCK_OUTLET; +(function (BLOCK_OUTLET) { + BLOCK_OUTLET[BLOCK_OUTLET["NONE"] = 0] = "NONE"; + BLOCK_OUTLET[BLOCK_OUTLET["PROGRESS"] = 1] = "PROGRESS"; + BLOCK_OUTLET[BLOCK_OUTLET["ERROR"] = 2] = "ERROR"; + BLOCK_OUTLET[BLOCK_OUTLET["PAUSED"] = 4] = "PAUSED"; + BLOCK_OUTLET[BLOCK_OUTLET["FINISH"] = 8] = "FINISH"; + BLOCK_OUTLET[BLOCK_OUTLET["STOPPED"] = 16] = "STOPPED"; +})(BLOCK_OUTLET = BLOCK_OUTLET || (BLOCK_OUTLET = {})); +; +export var EVENTS; +(function (EVENTS) { + EVENTS["ON_RUN_BLOCK"] = "onRunBlock"; + EVENTS["ON_RUN_BLOCK_FAILED"] = "onRunBlockFailed"; + EVENTS["ON_RUN_BLOCK_SUCCESS"] = "onRunBlockSuccess"; + EVENTS["ON_BLOCK_SELECTED"] = "onItemSelected"; + EVENTS["ON_BLOCK_UNSELECTED"] = "onBlockUnSelected"; + EVENTS["ON_BLOCK_EXPRESSION_FAILED"] = "onExpressionFailed"; + EVENTS["ON_BUILD_BLOCK_INFO_LIST"] = "onBuildBlockInfoList"; + EVENTS["ON_BUILD_BLOCK_INFO_LIST_END"] = "onBuildBlockInfoListEnd"; + EVENTS["ON_BLOCK_PROPERTY_CHANGED"] = "onBlockPropertyChanged"; + EVENTS["ON_SCOPE_CREATED"] = "onScopeCreated"; + EVENTS["ON_VARIABLE_CHANGED"] = "onVariableChanged"; + EVENTS["ON_CREATE_VARIABLE_CI"] = "onCreateVariableCI"; +})(EVENTS = EVENTS || (EVENTS = {})); +export var BlockType; +(function (BlockType) { + BlockType["AssignmentExpression"] = "AssignmentExpression"; + BlockType["ArrayExpression"] = "ArrayExpression"; + BlockType["BlockStatement"] = "BlockStatement"; + BlockType["BinaryExpression"] = "BinaryExpression"; + BlockType["BreakStatement"] = "BreakStatement"; + BlockType["CallExpression"] = "CallExpression"; + BlockType["CatchClause"] = "CatchClause"; + BlockType["ConditionalExpression"] = "ConditionalExpression"; + BlockType["ContinueStatement"] = "ContinueStatement"; + BlockType["DoWhileStatement"] = "DoWhileStatement"; + BlockType["DebuggerStatement"] = "DebuggerStatement"; + BlockType["EmptyStatement"] = "EmptyStatement"; + BlockType["ExpressionStatement"] = "ExpressionStatement"; + BlockType["ForStatement"] = "ForStatement"; + BlockType["ForInStatement"] = "ForInStatement"; + BlockType["FunctionDeclaration"] = "FunctionDeclaration"; + BlockType["FunctionExpression"] = "FunctionExpression"; + BlockType["Identifier"] = "Identifier"; + BlockType["IfStatement"] = "IfStatement"; + BlockType["Literal"] = "Literal"; + BlockType["LabeledStatement"] = "LabeledStatement"; + BlockType["LogicalExpression"] = "LogicalExpression"; + BlockType["MemberExpression"] = "MemberExpression"; + BlockType["NewExpression"] = "NewExpression"; + BlockType["ObjectExpression"] = "ObjectExpression"; + BlockType["Program"] = "Program"; + BlockType["Property"] = "Property"; + BlockType["ReturnStatement"] = "ReturnStatement"; + BlockType["SequenceExpression"] = "SequenceExpression"; + BlockType["SwitchStatement"] = "SwitchStatement"; + BlockType["SwitchCase"] = "SwitchCase"; + BlockType["ThisExpression"] = "ThisExpression"; + BlockType["ThrowStatement"] = "ThrowStatement"; + BlockType["TryStatement"] = "TryStatement"; + BlockType["UnaryExpression"] = "UnaryExpression"; + BlockType["UpdateExpression"] = "UpdateExpression"; + BlockType["VariableDeclaration"] = "VariableDeclaration"; + BlockType["VariableDeclarator"] = "VariableDeclarator"; + BlockType["WhileStatement"] = "WhileStatement"; + BlockType["WithStatement"] = "WithStatement"; +})(BlockType = BlockType || (BlockType = {})); +; +/** + * Variable Flags + * + * @enum {int} VARIABLE_FLAGS + * @global + */ +export var VARIABLE_FLAGS; +(function (VARIABLE_FLAGS) { + VARIABLE_FLAGS[VARIABLE_FLAGS["PUBLISH"] = 2] = "PUBLISH"; + VARIABLE_FLAGS[VARIABLE_FLAGS["PUBLISH_IF_SERVER"] = 4] = "PUBLISH_IF_SERVER"; +})(VARIABLE_FLAGS = VARIABLE_FLAGS || (VARIABLE_FLAGS = {})); +; +export var BLOCK_GROUPS; +(function (BLOCK_GROUPS) { + BLOCK_GROUPS["VARIABLE"] = "DriverVariable"; + BLOCK_GROUPS["BASIC_COMMAND"] = "DriverBasicCommand"; + BLOCK_GROUPS["CONDITIONAL_COMMAND"] = "DriverConditionalCommand"; + BLOCK_GROUPS["RESPONSE_VARIABLE"] = "DriverResponseVariable"; + BLOCK_GROUPS["RESPONSE_BLOCKS"] = "conditionalProcess"; + BLOCK_GROUPS["RESPONSE_VARIABLES"] = "processVariables"; + BLOCK_GROUPS["BASIC_VARIABLES"] = "basicVariables"; +})(BLOCK_GROUPS = BLOCK_GROUPS || (BLOCK_GROUPS = {})); +; +export var COMMAND_TYPES; +(function (COMMAND_TYPES) { + COMMAND_TYPES["BASIC_COMMAND"] = "basic"; + COMMAND_TYPES["CONDITIONAL_COMMAND"] = "conditional"; + COMMAND_TYPES["INIT_COMMAND"] = "init"; +})(COMMAND_TYPES = COMMAND_TYPES || (COMMAND_TYPES = {})); +; +export var CIFLAG; +(function (CIFLAG) { + /** + * Instruct for no additional extra processing + * @constant + * @type int + */ + CIFLAG[CIFLAG["NONE"] = 0] = "NONE"; + /** + * Will instruct the pre/post processor to base-64 decode or encode + * @constant + * @type int + */ + CIFLAG[CIFLAG["BASE_64"] = 1] = "BASE_64"; + /** + * Post/Pre process the value with a user function + * @constant + * @type int + */ + CIFLAG[CIFLAG["USE_FUNCTION"] = 2] = "USE_FUNCTION"; + /** + * Replace variables with local scope's variables during the post/pre process + * @constant + * @type int + */ + CIFLAG[CIFLAG["REPLACE_VARIABLES"] = 4] = "REPLACE_VARIABLES"; + /** + * Replace variables with local scope's variables during the post/pre process but evaluate the whole string + * as Javascript + * @constant + * @type int + */ + CIFLAG[CIFLAG["REPLACE_VARIABLES_EVALUATED"] = 8] = "REPLACE_VARIABLES_EVALUATED"; + /** + * Will instruct the pre/post processor to escpape evaluated or replaced variables or expressions + * @constant + * @type int + */ + CIFLAG[CIFLAG["ESCAPE"] = 16] = "ESCAPE"; + /** + * Will instruct the pre/post processor to replace block calls with oridinary vanilla script + * @constant + * @type int + */ + CIFLAG[CIFLAG["REPLACE_BLOCK_CALLS"] = 32] = "REPLACE_BLOCK_CALLS"; + /** + * Will instruct the pre/post processor to remove variable delimitters/placeholders from the final string + * @constant + * @type int + */ + CIFLAG[CIFLAG["REMOVE_DELIMTTERS"] = 64] = "REMOVE_DELIMTTERS"; + /** + * Will instruct the pre/post processor to remove "[" ,"]" , "(" , ")" , "{", "}" , "*" , "+" , "." + * @constant + * @type int + */ + CIFLAG[CIFLAG["ESCAPE_SPECIAL_CHARS"] = 128] = "ESCAPE_SPECIAL_CHARS"; + /** + * Will instruct the pre/post processor to use regular expressions over string substitution + * @constant + * @type int + */ + CIFLAG[CIFLAG["USE_REGEX"] = 256] = "USE_REGEX"; + /** + * Will instruct the pre/post processor to use Filtrex (custom bison parser, needs xexpression) over string substitution + * @constant + * @type int + */ + CIFLAG[CIFLAG["USE_FILTREX"] = 512] = "USE_FILTREX"; + /** + * Cascade entry. There are cases where #USE_FUNCTION is not enough or we'd like to avoid further type checking. + * @constant + * @type int + */ + CIFLAG[CIFLAG["CASCADE"] = 1024] = "CASCADE"; + /** + * Cascade entry. There are cases where #USE_FUNCTION is not enough or we'd like to avoid further type checking. + * @constant + * @type int + */ + CIFLAG[CIFLAG["EXPRESSION"] = 2048] = "EXPRESSION"; + /** + * Dont parse anything + * @constant + * @type int + */ + CIFLAG[CIFLAG["DONT_PARSE"] = 4096] = "DONT_PARSE"; + /** + * Convert to hex + * @constant + * @type int + */ + CIFLAG[CIFLAG["TO_HEX"] = 8192] = "TO_HEX"; + /** + * Convert to hex + * @constant + * @type int + */ + CIFLAG[CIFLAG["REPLACE_HEX"] = 16384] = "REPLACE_HEX"; + /** + * Wait for finish + * @constant + * @type int + */ + CIFLAG[CIFLAG["WAIT"] = 32768] = "WAIT"; + /** + * Wait for finish + * @constant + * @type int + */ + CIFLAG[CIFLAG["DONT_ESCAPE"] = 65536] = "DONT_ESCAPE"; + /** + * Flag to mark the maximum core bit mask, after here its user land + * @constant + * @type int + */ + CIFLAG[CIFLAG["END"] = 131072] = "END"; +})(CIFLAG = CIFLAG || (CIFLAG = {})); +//# sourceMappingURL=types_gui.js.map \ No newline at end of file diff --git a/packages/commons/dist/types_gui.js.map b/packages/commons/dist/types_gui.js.map new file mode 100644 index 00000000..96545b78 --- /dev/null +++ b/packages/commons/dist/types_gui.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types_gui.js","sourceRoot":"","sources":["../src/types_gui.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAN,IAAY,SAaX;AAbD,WAAY,SAAS;IACjB;;;;OAIG;IACH,kDAAqB,CAAA;IACrB;;;;OAIG;IACH,6CAAkB,CAAA;AACtB,CAAC,EAbW,SAAS,GAAT,SAAS,KAAT,SAAS,QAapB;AAAA,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAN,IAAY,eAuDX;AAvDD,WAAY,eAAe;IACvB;;;;OAIG;IACH,qDAAiB,CAAA;IACjB;;;;OAIG;IACH,2DAAoB,CAAA;IACpB;;;;OAIG;IACH,uDAAkB,CAAA;IAClB;;;;OAIG;IACH,yDAAmB,CAAA;IACnB;;;;OAIG;IACH,yDAAmB,CAAA;IACnB;;;;OAIG;IACH,4DAAoB,CAAA;IACpB;;;;OAIG;IACH,8DAAiB,CAAA;I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MAAM,CAAN,IAAY,MAoHX;AApHD,WAAY,MAAM;IACd;;;;OAIG;IACH,mCAAiB,CAAA;IACjB;;;;OAIG;IACH,yCAAoB,CAAA;IACpB;;;;OAIG;IACH,mDAAyB,CAAA;IACzB;;;;OAIG;IACH,6DAA8B,CAAA;IAC9B;;;;;OAKG;IACH,iFAAwC,CAAA;IACxC;;;;OAIG;IACH,wCAAmB,CAAA;IACnB;;;;OAIG;IACH,kEAAgC,CAAA;IAChC;;;;OAIG;IACH,8DAA8B,CAAA;IAC9B;;;;OAIG;IACH,qEAAiC,CAAA;IACjC;;;;OAIG;IACH,+CAAsB,CAAA;IACtB;;;;OAIG;IACH,mDAAwB,CAAA;IACxB;;;;OAIG;IACH,4CAAoB,CAAA;IACpB;;;;OAIG;IACH,kDAAuB,CAAA;IACvB;;;;OAIG;IACH,kDAAwB,CAAA;IACxB;;;;OAIG;IACH,0CAAoB,CAAA;IACpB;;;;OAIG;IACH,qDAAyB,CAAA;IACzB;;;;OAIG;IACH,uCAAkB,CAAA;IAClB;;;;OAIG;IACH,qDAAyB,CAAA;IACzB;;;;OAIG;IACH,sCAAiB,CAAA;AACrB,CAAC,EApHW,MAAM,GAAN,MAAM,KAAN,MAAM,QAoHjB"} \ No newline at end of file diff --git a/packages/commons/dist/types_kbot.d.ts b/packages/commons/dist/types_kbot.d.ts new file mode 100644 index 00000000..bdcf413c --- /dev/null +++ b/packages/commons/dist/types_kbot.d.ts @@ -0,0 +1,192 @@ +export interface IKBotOptions { + /** Path to the project directory */ + path?: string; + /** Description of the modifications to make to the project. Supports file paths. */ + query?: string; + /** Optional output path for modified files */ + output?: string | undefined; + /** Optional destination path for the result, will substitute ${MODEL} and ${ROUTER} in the path */ + dst?: string | undefined; + /** Template (typescript) or path to use for processing, see https://git.polymech.io/polymech/ai-template-typescript */ + template?: (("typescript") | string) | undefined; + /** Template root directory. When specified, templates are loaded with a prefix, eg: ${POLYMECH-ROOT}/ai-template-${options.template} */ + templateRoot?: string; + /** List of template parts to disable. Addionally, tools categories can be disabled, eg: --disable=fs,git,interact,terminal,search,web,email,user */ + disable?: string[]; + /** List of specific tools to disable */ + disableTools?: string[]; + /** Glob patterns to match files for processing, comma separated, eg: src/*.tsx,src/*.ts */ + glob?: string[] | undefined; + /** AI model to use for processing. Available models: +  +  OpenRouter models: +  + google/gemini-pro-1.5-exp | paid + meta-llama/llama-3.2-11b-vision-instruct:free | free + google/gemini-flash-1.5-exp | paid + google/gemini-flash-1.5-8b-exp | paid + microsoft/phi-3-medium-128k-instruct:free | free + microsoft/phi-3-mini-128k-instruct:free | free + google/gemini-2.0-flash-thinking-exp:free | free + google/gemini-2.0-flash-exp:free | free + meta-llama/llama-3.2-1b-instruct | paid + meta-llama/llama-3.2-3b-instruct | paid + meta-llama/llama-3.1-8b-instruct | paid + mistralai/mistral-7b-instruct | paid + mistralai/mistral-7b-instruct-v0.3 | paid + meta-llama/llama-3-8b-instruct | paid + amazon/nova-micro-v1 | paid + google/gemini-flash-1.5-8b | paid + mistralai/ministral-3b | paid + meta-llama/llama-3.2-11b-vision-instruct | paid + amazon/nova-lite-v1 | paid + google/gemini-flash-1.5 | paid + mistralai/ministral-8b | paid + microsoft/phi-3-mini-128k-instruct | paid + microsoft/phi-3.5-mini-128k-instruct | paid + meta-llama/llama-3.1-70b-instruct | paid + nvidia/llama-3.1-nemotron-70b-instruct | paid + deepseek/deepseek-chat | paid + cohere/command-r-08-2024 | paid + mistralai/mistral-nemo | paid + mistralai/pixtral-12b | paid + openai/gpt-4o-mini | paid + openai/gpt-4o-mini-2024-07-18 | paid + mistralai/mistral-7b-instruct-v0.1 | paid + ai21/jamba-1-5-mini | paid + mistralai/mistral-small | paid + qwen/qwen-2.5-72b-instruct | paid + meta-llama/llama-3-70b-instruct | paid + mistralai/mixtral-8x7b-instruct | paid + mistralai/mistral-tiny | paid + mistralai/codestral-mamba | paid + anthropic/claude-3-haiku:beta | paid + anthropic/claude-3-haiku | paid + nousresearch/hermes-3-llama-3.1-70b | paid + cohere/command-r-03-2024 | paid + cohere/command-r | paid + openai/gpt-3.5-turbo-0125 | paid + google/gemini-pro | paid + openai/gpt-3.5-turbo | paid + mistralai/mixtral-8x7b-instruct:nitro | paid + meta-llama/llama-3.1-405b-instruct | paid + amazon/nova-pro-v1 | paid + anthropic/claude-3.5-haiku:beta | paid + anthropic/claude-3.5-haiku | paid + anthropic/claude-3.5-haiku-20241022:beta | paid + anthropic/claude-3.5-haiku-20241022 | paid + microsoft/phi-3-medium-128k-instruct | paid + openai/gpt-3.5-turbo-1106 | paid + openai/gpt-3.5-turbo-0613 | paid + meta-llama/llama-3.2-90b-vision-instruct | paid + google/gemini-pro-1.5 | paid + mistralai/mixtral-8x22b-instruct | paid + mistralai/mistral-large | paid + mistralai/mistral-large-2407 | paid + mistralai/mistral-large-2411 | paid + mistralai/pixtral-large-2411 | paid + ai21/jamba-1-5-large | paid + x-ai/grok-2-1212 | paid + cohere/command-r-plus-08-2024 | paid + openai/gpt-4o | paid + openai/gpt-4o-2024-08-06 | paid + openai/gpt-4o-2024-11-20 | paid + mistralai/mistral-medium | paid + cohere/command-r-plus | paid + cohere/command-r-plus-04-2024 | paid + openai/gpt-3.5-turbo-16k | paid + anthropic/claude-3.5-sonnet:beta | paid + anthropic/claude-3.5-sonnet | paid + anthropic/claude-3-sonnet:beta | paid + anthropic/claude-3-sonnet | paid + anthropic/claude-3.5-sonnet-20240620:beta | paid + anthropic/claude-3.5-sonnet-20240620 | paid + openai/gpt-4o-2024-05-13 | paid + x-ai/grok-beta | paid + x-ai/grok-vision-beta | paid + openai/gpt-4o:extended | paid + openai/gpt-4-turbo | paid + openai/gpt-4-1106-preview | paid + openai/gpt-4-turbo-preview | paid + openai/o1 | paid + anthropic/claude-3-opus:beta | paid + anthropic/claude-3-opus | paid + openai/gpt-4 | paid + openai/gpt-4-0314 | paid + openai/gpt-4-32k-0314 | paid + openai/gpt-4-32k | paid +  +  OpenAI models: +  + gpt-4o-audio-preview-2024-10-01 + gpt-4o-realtime-preview + gpt-4o-realtime-preview-2024-10-01 + o1-mini-2024-09-12 + dall-e-2 + gpt-4-turbo + gpt-4-1106-preview + gpt-3.5-turbo + gpt-3.5-turbo-0125 + gpt-3.5-turbo-instruct + gpt-4-1106-vision-preview + babbage-002 + davinci-002 + whisper-1 + dall-e-3 + gpt-4o-mini-2024-07-18 + text-embedding-3-small + gpt-4o-mini + gpt-3.5-turbo-16k + gpt-4-0125-preview + gpt-4-turbo-preview + omni-moderation-latest + gpt-4o-2024-05-13 + omni-moderation-2024-09-26 + tts-1-hd-1106 + chatgpt-4o-latest + gpt-4 + gpt-4-0613 + o1-mini + o1-preview + o1-preview-2024-09-12 + tts-1-hd + gpt-4-vision-preview + text-embedding-ada-002 + gpt-3.5-turbo-1106 + gpt-4o-audio-preview + tts-1 + tts-1-1106 + gpt-3.5-turbo-instruct-0914 + text-embedding-3-large + gpt-4o-realtime-preview-2024-12-17 + gpt-4o-mini-realtime-preview + gpt-4o-mini-realtime-preview-2024-12-17 + gpt-4o-2024-11-20 + gpt-4o-audio-preview-2024-12-17 + gpt-4o-mini-audio-preview + gpt-4o-2024-08-06 + gpt-4o-mini-audio-preview-2024-12-17 + gpt-4o + gpt-4-turbo-2024-04-09 + ----- + */ + model?: string; + /** Router to use: openai or openrouter */ + router?: string; + /** Chat completion type - completion (without tools) or tools (with function calling) */ + type?: "completion" | "tools"; + /** Logging level for the application */ + logLevel?: unknown; + /** Profile for constants */ + profile?: string; + /** Environment (in profile) */ + env?: string; + /** Configuration as JSON string or path to JSON file, eg: {"openrouter":{"key":"your-key"}} or path/to/config.json */ + config?: string | undefined; + /** Write out as script */ + dump?: string | undefined; + /** Path to preferences file */ + preferences?: string; + /** Logging directory */ + logs?: string; +} diff --git a/packages/commons/dist/types_kbot.js b/packages/commons/dist/types_kbot.js new file mode 100644 index 00000000..ad257a1b --- /dev/null +++ b/packages/commons/dist/types_kbot.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types_kbot.js.map \ No newline at end of file diff --git a/packages/commons/dist/types_kbot.js.map b/packages/commons/dist/types_kbot.js.map new file mode 100644 index 00000000..a347f85c --- /dev/null +++ b/packages/commons/dist/types_kbot.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types_kbot.js","sourceRoot":"","sources":["../src/types_kbot.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/commons/dist/uri.d.ts b/packages/commons/dist/uri.d.ts new file mode 100644 index 00000000..5cb5db6e --- /dev/null +++ b/packages/commons/dist/uri.d.ts @@ -0,0 +1,11 @@ +/// +import { URL } from 'url'; +import * as path from 'path'; +export interface IDownloadUrl { + urlParts: URL; + pathParts: path.ParsedPath; + filename: string; + path: string; + url: string; +} +export declare const parseForDownload: (url: string, dst: string) => IDownloadUrl; diff --git a/packages/commons/dist/uri.js b/packages/commons/dist/uri.js new file mode 100644 index 00000000..31f97b2f --- /dev/null +++ b/packages/commons/dist/uri.js @@ -0,0 +1,23 @@ +import { URL } from 'url'; +import * as path from 'path'; +const filenamify = require('filenamify'); +const _sanitize = require("sanitize-filename"); +const sanitize_ex = (f) => { + let str = filenamify(_sanitize(f)).replace(/[^\x00-\x7F]/g, "").replace('_', ''); + return str; +}; +export const parseForDownload = (url, dst) => { + const parsed = new URL(url); + const parts = path.parse(parsed.pathname); + const filename = sanitize_ex(decodeURI(parts.base)); + const downloadPath = path.resolve(`${dst}/${filename}`); + const downloadUrl = parsed.origin + parsed.pathname; + return { + urlParts: parsed, + pathParts: parts, + filename: filename, + path: downloadPath, + url: downloadUrl + }; +}; +//# sourceMappingURL=uri.js.map \ No newline at end of file diff --git a/packages/commons/dist/uri.js.map b/packages/commons/dist/uri.js.map new file mode 100644 index 00000000..dc107377 --- /dev/null +++ b/packages/commons/dist/uri.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uri.js","sourceRoot":"","sources":["../src/uri.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAA;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAE5B,MAAM,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAAA;AACxC,MAAM,SAAS,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAA;AAE9C,MAAM,WAAW,GAAG,CAAC,CAAC,EAAE,EAAE;IACtB,IAAI,GAAG,GAAW,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACzF,OAAO,GAAG,CAAC;AACf,CAAC,CAAA;AAUD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAW,EAAE,GAAW,EAAiB,EAAE;IAExE,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IAC5B,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;IAEzC,MAAM,QAAQ,GAAG,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;IACnD,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,IAAI,QAAQ,EAAE,CAAC,CAAA;IACvD,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAA;IAEnD,OAAO;QACH,QAAQ,EAAC,MAAM;QACf,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,QAAQ;QAClB,IAAI,EAAE,YAAY;QAClB,GAAG,EAAE,WAAW;KACnB,CAAA;AACL,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/commons/dist/variables.d.ts b/packages/commons/dist/variables.d.ts new file mode 100644 index 00000000..e9769baf --- /dev/null +++ b/packages/commons/dist/variables.d.ts @@ -0,0 +1,12 @@ +export declare const DATE_VARS: () => { + YYYY: number; + MM: number; + DD: number; + HH: number; + SS: number; +}; +export declare const _substitute: (template: any, map: Record, keep?: boolean, alt?: boolean) => any; +export declare const substitute: (alt: boolean, template: string, vars?: Record, keep?: boolean) => any; +export declare const DEFAULT_VARS: (vars: any) => any; +export declare const resolveVariables: (_path: string, alt?: boolean, vars?: Record) => any; +export declare const resolve: (_path: string, alt?: boolean, vars?: Record) => any; diff --git a/packages/commons/dist/variables.js b/packages/commons/dist/variables.js new file mode 100644 index 00000000..05d74668 --- /dev/null +++ b/packages/commons/dist/variables.js @@ -0,0 +1,39 @@ +import { REGEX_VAR, REGEX_VAR_ALT } from "@polymech/core/constants.js"; +import { DEFAULT_ROOTS } from '@/config.js'; +export const DATE_VARS = () => { + return { + YYYY: new Date(Date.now()).getFullYear(), + MM: new Date(Date.now()).getMonth() + 1, + DD: new Date(Date.now()).getDate(), + HH: new Date(Date.now()).getHours(), + SS: new Date(Date.now()).getSeconds() + }; +}; +export const _substitute = (template, map, keep = true, alt = false) => { + const transform = (k) => k || ''; + return template.replace(alt ? REGEX_VAR_ALT : REGEX_VAR, (match, key, format) => { + if (map[key]) { + return transform(map[key]).toString(); + } + else if (map[key.replace(/-/g, '_')]) { + return transform(map[key.replace(/-/g, '_')]).toString(); + } + else if (keep) { + return "${" + key + "}"; + } + else { + return ""; + } + }); +}; +export const substitute = (alt, template, vars = {}, keep = true) => alt ? _substitute(template, vars, keep, alt) : _substitute(template, vars, keep, alt); +export const DEFAULT_VARS = (vars) => { + return { + ...DEFAULT_ROOTS, + ...DATE_VARS(), + ...vars + }; +}; +export const resolveVariables = (_path, alt = false, vars = {}) => substitute(alt, _path, DEFAULT_VARS(vars)); +export const resolve = (_path, alt = false, vars = {}) => resolveVariables(_path, alt, vars); +//# sourceMappingURL=variables.js.map \ No newline at end of file diff --git a/packages/commons/dist/variables.js.map b/packages/commons/dist/variables.js.map new file mode 100644 index 00000000..eb5ec6e1 --- /dev/null +++ b/packages/commons/dist/variables.js.map @@ -0,0 +1 @@ +{"version":3,"file":"variables.js","sourceRoot":"","sources":["../src/variables.ts"],"names":[],"mappings":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,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAA;SAC3D;aAAM,IAAI,IAAI,EAAE;YACb,OAAO,IAAI,GAAG,GAAG,GAAG,GAAG,CAAA;SAC1B;aAAM;YACH,OAAO,EAAE,CAAA;SACZ;IACL,CAAC,CAAC,CAAA;AACN,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,GAAY,EAAE,QAAgB,EAAE,OAA4B,EAAE,EAAE,OAAgB,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAA;AACzM,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,IAAS,EAAE,EAAE;IACtC,OAAO;QACH,GAAG,aAAa;QAChB,GAAG,SAAS,EAAE;QACd,GAAG,IAAI;KACV,CAAA;AACL,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,KAAa,EAAE,MAAe,KAAK,EAAE,OAA+B,EAAE,EAAE,EAAE,CACvG,UAAU,CAAC,GAAG,EAAE,KAAK,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC,CAAA;AAE9C,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,KAAa,EAAE,MAAe,KAAK,EAAE,OAA+B,EAAE,EAAE,EAAE,CAC9F,gBAAgB,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/commons/package.json b/packages/commons/package.json index 36ba98c3..bb6aad1a 100644 --- a/packages/commons/package.json +++ b/packages/commons/package.json @@ -6,18 +6,31 @@ "publishConfig": { "access": "public" }, + "exports": { + ".": { + "import": "./dist/index.js", + "require": "./dist/index.cjs" + }, + "./variables": { + "import": "./dist/variables.js", + "require": "./dist/variables.cjs" + }, + "./types": { + "import": "./dist/types.js", + "require": "./dist/types.cjs" + }, + "./schemas": { + "import": "./dist/schemas/index.js", + "require": "./dist/schemas/index.cjs" + } + }, "licenses": [ { "type": "BSD", "url": "https://git.osr-plastic.org/osr-plastic/osr-core/blob/master/LICENSE" } ], - "exports": { - ".": { - "import": "./dist/index.js", - "require": "./dist/index.cjs" - } - }, + "main": "dist/index.js", "repository": { "type": "git", @@ -25,11 +38,16 @@ }, "types": "index.d.ts", "dependencies": { + "@polymech/core": "workspace:*", + "@polymech/fs": "workspace:*", + "env-var": "^7.5.0", + "glob": "^10.4.1", "tslog": "^3.3.3", "tsup": "^8.3.5", + "yargs": "^17.7.2", "zod": "^3.24.1", - "@polymech/fs": "workspace:*", - "@polymech/core": "workspace:*" + "zod-to-json-schema": "^3.24.1", + "zod-to-ts": "^1.2.0" }, "devDependencies": { "@eslint/js": "^9.18.0", diff --git a/packages/commons/src/_glob.ts b/packages/commons/src/_glob.ts new file mode 100644 index 00000000..b8970056 --- /dev/null +++ b/packages/commons/src/_glob.ts @@ -0,0 +1,96 @@ +import * as path from 'path' +// import * as isGlob from 'is-glob' +// import * as fg from 'fast-glob' +import { glob, globSync, GlobOptions, hasMagic } from 'glob' +import { REGEX_VAR, REGEX_VAR_ALT } from "@polymech/core/constants.js" +import { sync as exists } from '@polymech/fs/exists' + +export const files = (cwd, glob, options?: any) => globSync(glob, { ...{ dot: true, cwd, absolute: true, caseSensitiveMatch: false }, ...options || {} }) as [] +export const filesEx = (cwd, glob, options?: GlobOptions) => globSync(glob, { ...{ dot: true, cwd, absolute: true, caseSensitiveMatch: false }, ...options || {} }) as [] + +import { substitute } from '@/variables.js' +import { isFile, isFolder, getExtensions } from '@/fs.js' +import { PATH_INFO } from '@/types_common.js' + +const globBase = require('glob-base') + +export const forward_slash = (path) => { + const isExtendedLengthPath = /^\\\\\?\\/.test(path) + const hasNonAscii = /[^\u0000-\u0080]+/.test(path) + if (isExtendedLengthPath || hasNonAscii) { + return path; + } + return path.replace(/\\/g, '/') +} +export const pathInfoEx = (src: string, altToken: boolean = false, globOptions: GlobOptions = {}): PATH_INFO => { + const srcParts = path.parse(src) + let variables: PATH_INFO = { + PATH: src + } as PATH_INFO + + variables.DIR = srcParts.dir + variables.NAME = srcParts.name + variables.FILE_NAME = srcParts.base + variables.FILE_EXT = srcParts.ext.replace('.', '') + variables.PATH = src + variables.IS_FILE = isFile(src) + variables.IS_FOLDER = isFolder(src) + variables.IS_EXPRESSION = src.match(altToken ? REGEX_VAR_ALT : REGEX_VAR) != null + + if (!variables.IS_FOLDER && !variables.IS_FILE) { + variables.IS_GLOB = hasMagic(substitute(altToken, srcParts.base, {}, false)) + } else { + variables.IS_GLOB = false + } + if (variables.IS_GLOB) { + //important: use the forward slash since path.resolve will return backslashes on Windows + const glob_base = globBase(src) + variables.DIR = path.resolve(glob_base.base) + variables.FILE_NAME = glob_base.glob + variables.GLOB = glob_base.glob + variables.GLOB_EXTENSIONS = getExtensions(glob_base.glob) + globOptions = { + ...globOptions, + cwd: globOptions.cwd ? path.join(globOptions.cwd as string, glob_base.base) : null + } + variables.FILES = glob.sync(glob_base.glob, globOptions) as [] + } else if (variables.IS_FILE && exists(src)) { + variables.FILES = [src] + } + return variables +} +export const pathInfo = (src: string, altToken: boolean = false, cwd: string = null): PATH_INFO => { + const srcParts = path.parse(src) + let variables: PATH_INFO = { + PATH: src + } as PATH_INFO + variables.DIR = srcParts.dir + variables.NAME = srcParts.name + variables.FILE_NAME = srcParts.base + variables.FILE_EXT = srcParts.ext.replace('.', '') + variables.PATH = src + variables.IS_FILE = isFile(src) + variables.IS_FOLDER = isFolder(src) + variables.IS_EXPRESSION = src.match(altToken ? REGEX_VAR_ALT : REGEX_VAR) != null + + if (!variables.IS_FOLDER && !variables.IS_FILE) { + variables.IS_GLOB = hasMagic(srcParts.base) + } else { + variables.IS_GLOB = false + } + if (variables.IS_GLOB) { + const glob_base = globBase(src) + variables.DIR = path.resolve(glob_base.base) + variables.FILE_NAME = glob_base.glob + variables.GLOB = glob_base.glob + variables.GLOB_EXTENSIONS = getExtensions(glob_base.glob) + variables.FILES = globSync(glob_base.glob, { + dot: true, + cwd: path.resolve(cwd || variables.DIR), + absolute: true + }) + } else if (variables.IS_FILE && exists(src)) { + variables.FILES = [src] + } + return variables +} \ No newline at end of file diff --git a/packages/commons/src/config.ts b/packages/commons/src/config.ts new file mode 100644 index 00000000..446a4efd --- /dev/null +++ b/packages/commons/src/config.ts @@ -0,0 +1,59 @@ +import * as env from 'env-var' +import { sync as read } from '@polymech/fs/read' +import { sync as exists } from '@polymech/fs/exists' +import * as path from 'path' + +export const API_PREFIX = 'osr' +export const API_PREFIX_NEXT = 'polymech' + +export const HOME = (sub = '') => path.join(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], sub) + +export const get_var = (key: string ='') => env.get(key).asString() || env.get(key.replace(/-/g, '_')).asString() || env.get(key.replace(/_/g, '-')).asString() + +export const OSR_ROOT = (key: string = 'OSR-ROOT') => get_var(key) || path.join(HOME('desktop'), API_PREFIX) +export const OSR_SUB_DEFAULT = (key: string = '') => get_var(key) || path.join(OSR_ROOT(), key) +export const CONFIG_DEFAULT_PATH = (key: string = 'OSR-CONFIG') => get_var(key) || path.join(HOME(`${API_PREFIX}`), '.config.json') + +export const OSR_TEMP = (key: string = 'OSR-TEMP') => get_var(key) || OSR_SUB_DEFAULT(`.${API_PREFIX}/temp`) +export const OSR_CACHE = (key: string = 'OSR-CACHE') => get_var(key) || OSR_SUB_DEFAULT(`.${API_PREFIX}/cache`) + +export const OSR_PRIVATE = (key: string = 'OSR-PRIVATE') => get_var(key) +export const KB_ROOT = (key: string = 'OSR-KB') => get_var(key) +export const OSR_LIBRARY = (key: string = 'OSR-LIBRARY') => get_var(key) +export const OSR_LIBRARY_MACHINES = (key: string = 'OSR-LIBRARY-MACHINES') => get_var(key) +export const OSR_LIBRARY_DIRECTORY = (key: string = 'OSR-LIBRARY-DIRECTORY') => get_var(key) + +export const PRODUCT_ROOT = (key: string = 'PRODUCT-ROOT') => get_var(key) +export const OSR_CUSTOMER_DRIVE = (key: string = 'OSR-CUSTOMER-DRIVE') => get_var(key) + +export const OA_ROOT = (key: string = 'OA-ROOT') => get_var(key) +export const OSR_USER_ASSETS = (key: string = 'OSR-USER-ASSETS') => get_var(key) + +export const POLYMECH_ROOT = (key: string = 'POLYMECH-ROOT') => get_var(key) || path.join(HOME('desktop'), API_PREFIX_NEXT) + +export const DEFAULT_ROOTS = { + OSR_ROOT: OSR_ROOT(), + OSR_TEMP: OSR_TEMP(), + PRODUCT_ROOT: PRODUCT_ROOT(), + OA_ROOT: OA_ROOT(), + KB_ROOT: KB_ROOT(), + OSR_CACHE: OSR_CACHE(), + OSR_LIBRARY: OSR_LIBRARY(), + OSR_LIBRARY_MACHINES: OSR_LIBRARY_MACHINES(), + OSR_LIBRARY_DIRECTORY: OSR_LIBRARY_DIRECTORY(), + OSR_USER_ASSETS: OSR_USER_ASSETS(), + OSR_PRIVATE: OSR_PRIVATE(), + OSR_TEMPLATES: path.join(OSR_SUB_DEFAULT('osr-templates')), + OSR_CONTENT: path.join(OSR_SUB_DEFAULT('osr-content')), + OSR_PROFILES: path.join(OSR_SUB_DEFAULT('osr-profiles')), + OSR_CUSTOMER_DRIVE: OSR_CUSTOMER_DRIVE(), + POLYMECH_ROOT: POLYMECH_ROOT() +} + +export const CONFIG_DEFAULT = (key: string = 'OSR-CONFIG') => { + const cPath = path.resolve(CONFIG_DEFAULT_PATH(key)); + if (exists(cPath)) { + return read(cPath, 'json'); + } + return false; +} \ No newline at end of file diff --git a/packages/commons/src/constants.ts b/packages/commons/src/constants.ts new file mode 100644 index 00000000..eb1d85d4 --- /dev/null +++ b/packages/commons/src/constants.ts @@ -0,0 +1,14 @@ +export const MODULE_NAME = `OSR-Commons` +export const PROFILE_FILE_NAME = `.osrl.json` +//////////////////////////////////////// +// +// OA Migration + +export const OA_LATEST = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}.json' +export const OA_LATEST_INVALID = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_INVALID.json' +export const OA_LATEST_CENSORED = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_CENSORED.json' +export const OA_LATEST_MERGED = '${OSR_ROOT}/osr-directory/pp/${YYYY}_${MM}_MERGED.json' + +// fecking bazar +export const PP_BAZAR_LATEST_INDEX = '${OSR_ROOT}/pp-bazar/${YYYY}/${MM}/index.json' +export const PP_BAZAR_LATEST_INDEX_MERGED = '${OSR_ROOT}/pp-bazar/${YYYY}/${MM}/index_merged.json' diff --git a/packages/commons/src/fs.ts b/packages/commons/src/fs.ts new file mode 100644 index 00000000..e0dd3c95 --- /dev/null +++ b/packages/commons/src/fs.ts @@ -0,0 +1,50 @@ +import * as fs from 'fs' + +// https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#namespaces +// https://github.com/isaacs/node-glob/blob/main/src/pattern.ts +export const GLOB_GROUP_PATTERN = /[!*+?@]\(.*\)/ +export const UNC_REGEX = /^[\\\/]{2,}[^\\\/]+[\\\/]+[^\\\/]+/ +export const WIN32_PATH_REGEX = /^([a-z]:)?[\\\/]/i + +import { is_windows } from './os.js' + +const parseGlob = require('parse-glob') + +export const getExtensions = (glob: string) => { + const match = glob.match(GLOB_GROUP_PATTERN); + if (match) { + return glob.substring((match.index || 0) + 2, glob.lastIndexOf(')')).split('|') + } else { + return [parseGlob(glob).path.ext] + } +} + +export const isFile = (src: string) => { + let srcIsFile = false; + try { + srcIsFile = fs.lstatSync(src).isFile() + } catch (e) { } + return srcIsFile +} + +export const isFolder = (src: string) => { + let srcIsFolder = false; + try { + srcIsFolder = fs.lstatSync(src).isDirectory() + } catch (e) { } + return srcIsFolder; +} + +const is_relative_win32 = (fp) => !fp.test(UNC_REGEX) && !WIN32_PATH_REGEX.test(fp) +const is_absolute_posix = (fp) => fp.charAt(0) === '/' +const is_absolute_win32 = (fp) => { + if (/[a-z]/i.test(fp.charAt(0)) && fp.charAt(1) === ':' && fp.charAt(2) === '\\') { + return true + } + // Microsoft Azure absolute filepath + if (fp.slice(0, 2) === '\\\\') { + return true; + } + return !is_relative_win32(fp) +} +export const is_absolute = (fp) => is_windows() ? is_absolute_win32(fp) : is_absolute_posix(fp) diff --git a/packages/commons/src/lib/fs.ts b/packages/commons/src/lib/fs.ts new file mode 100644 index 00000000..083b4cc0 --- /dev/null +++ b/packages/commons/src/lib/fs.ts @@ -0,0 +1,16 @@ +import * as fs from 'fs' + +export const isFile = (src: string) => { + let srcIsFile = false; + try { + srcIsFile = fs.lstatSync(src).isFile() + } catch (e) { } + return srcIsFile +} +export const isFolder = (src: string) => { + let srcIsFolder = false; + try { + srcIsFolder = fs.lstatSync(src).isDirectory() + } catch (e) { } + return srcIsFolder; +} \ No newline at end of file diff --git a/packages/commons/src/lib/index.ts b/packages/commons/src/lib/index.ts new file mode 100644 index 00000000..bb405d24 --- /dev/null +++ b/packages/commons/src/lib/index.ts @@ -0,0 +1,3 @@ +export * from './strings.js' +export * from './fs.js' + diff --git a/packages/commons/src/lib/strings.ts b/packages/commons/src/lib/strings.ts new file mode 100644 index 00000000..46862d95 --- /dev/null +++ b/packages/commons/src/lib/strings.ts @@ -0,0 +1,9 @@ +export const regexExEmojis = /((?:\ud83c\udde8\ud83c\uddf3|\ud83c\uddfa\ud83c\uddf8|\ud83c\uddf7\ud83c\uddfa|\ud83c\uddf0\ud83c\uddf7|\ud83c\uddef\ud83c\uddf5|\ud83c\uddee\ud83c\uddf9|\ud83c\uddec\ud83c\udde7|\ud83c\uddeb\ud83c\uddf7|\ud83c\uddea\ud83c\uddf8|\ud83c\udde9\ud83c\uddea|\u0039\ufe0f?\u20e3|\u0038\ufe0f?\u20e3|\u0037\ufe0f?\u20e3|\u0036\ufe0f?\u20e3|\u0035\ufe0f?\u20e3|\u0034\ufe0f?\u20e3|\u0033\ufe0f?\u20e3|\u0032\ufe0f?\u20e3|\u0031\ufe0f?\u20e3|\u0030\ufe0f?\u20e3|\u0023\ufe0f?\u20e3|\ud83d\udeb3|\ud83d\udeb1|\ud83d\udeb0|\ud83d\udeaf|\ud83d\udeae|\ud83d\udea6|\ud83d\udea3|\ud83d\udea1|\ud83d\udea0|\ud83d\ude9f|\ud83d\ude9e|\ud83d\ude9d|\ud83d\ude9c|\ud83d\ude9b|\ud83d\ude98|\ud83d\ude96|\ud83d\ude94|\ud83d\ude90|\ud83d\ude8e|\ud83d\ude8d|\ud83d\ude8b|\ud83d\ude8a|\ud83d\ude88|\ud83d\ude86|\ud83d\ude82|\ud83d\ude81|\ud83d\ude36|\ud83d\ude34|\ud83d\ude2f|\ud83d\ude2e|\ud83d\ude2c|\ud83d\ude27|\ud83d\ude26|\ud83d\ude1f|\ud83d\ude1b|\ud83d\ude19|\ud83d\ude17|\ud83d\ude15|\ud83d\ude11|\ud83d\ude10|\ud83d\ude0e|\ud83d\ude08|\ud83d\ude07|\ud83d\ude00|\ud83d\udd67|\ud83d\udd66|\ud83d\udd65|\ud83d\udd64|\ud83d\udd63|\ud83d\udd62|\ud83d\udd61|\ud83d\udd60|\ud83d\udd5f|\ud83d\udd5e|\ud83d\udd5d|\ud83d\udd5c|\ud83d\udd2d|\ud83d\udd2c|\ud83d\udd15|\ud83d\udd09|\ud83d\udd08|\ud83d\udd07|\ud83d\udd06|\ud83d\udd05|\ud83d\udd04|\ud83d\udd02|\ud83d\udd01|\ud83d\udd00|\ud83d\udcf5|\ud83d\udcef|\ud83d\udced|\ud83d\udcec|\ud83d\udcb7|\ud83d\udcb6|\ud83d\udcad|\ud83d\udc6d|\ud83d\udc6c|\ud83d\udc65|\ud83d\udc2a|\ud83d\udc16|\ud83d\udc15|\ud83d\udc13|\ud83d\udc10|\ud83d\udc0f|\ud83d\udc0b|\ud83d\udc0a|\ud83d\udc09|\ud83d\udc08|\ud83d\udc07|\ud83d\udc06|\ud83d\udc05|\ud83d\udc04|\ud83d\udc03|\ud83d\udc02|\ud83d\udc01|\ud83d\udc00|\ud83c\udfe4|\ud83c\udfc9|\ud83c\udfc7|\ud83c\udf7c|\ud83c\udf50|\ud83c\udf4b|\ud83c\udf33|\ud83c\udf32|\ud83c\udf1e|\ud83c\udf1d|\ud83c\udf1c|\ud83c\udf1a|\ud83c\udf18|\ud83c\udccf|\ud83c\udd8e|\ud83c\udd91|\ud83c\udd92|\ud83c\udd93|\ud83c\udd94|\ud83c\udd95|\ud83c\udd96|\ud83c\udd97|\ud83c\udd98|\ud83c\udd99|\ud83c\udd9a|\ud83d\udc77|\ud83d\udec5|\ud83d\udec4|\ud83d\udec3|\ud83d\udec2|\ud83d\udec1|\ud83d\udebf|\ud83d\udeb8|\ud83d\udeb7|\ud83d\udeb5|\ud83c\ude01|\ud83c\ude32|\ud83c\ude33|\ud83c\ude34|\ud83c\ude35|\ud83c\ude36|\ud83c\ude38|\ud83c\ude39|\ud83c\ude3a|\ud83c\ude50|\ud83c\ude51|\ud83c\udf00|\ud83c\udf01|\ud83c\udf02|\ud83c\udf03|\ud83c\udf04|\ud83c\udf05|\ud83c\udf06|\ud83c\udf07|\ud83c\udf08|\ud83c\udf09|\ud83c\udf0a|\ud83c\udf0b|\ud83c\udf0c|\ud83c\udf0f|\ud83c\udf11|\ud83c\udf13|\ud83c\udf14|\ud83c\udf15|\ud83c\udf19|\ud83c\udf1b|\ud83c\udf1f|\ud83c\udf20|\ud83c\udf30|\ud83c\udf31|\ud83c\udf34|\ud83c\udf35|\ud83c\udf37|\ud83c\udf38|\ud83c\udf39|\ud83c\udf3a|\ud83c\udf3b|\ud83c\udf3c|\ud83c\udf3d|\ud83c\udf3e|\ud83c\udf3f|\ud83c\udf40|\ud83c\udf41|\ud83c\udf42|\ud83c\udf43|\ud83c\udf44|\ud83c\udf45|\ud83c\udf46|\ud83c\udf47|\ud83c\udf48|\ud83c\udf49|\ud83c\udf4a|\ud83c\udf4c|\ud83c\udf4d|\ud83c\udf4e|\ud83c\udf4f|\ud83c\udf51|\ud83c\udf52|\ud83c\udf53|\ud83c\udf54|\ud83c\udf55|\ud83c\udf56|\ud83c\udf57|\ud83c\udf58|\ud83c\udf59|\ud83c\udf5a|\ud83c\udf5b|\ud83c\udf5c|\ud83c\udf5d|\ud83c\udf5e|\ud83c\udf5f|\ud83c\udf60|\ud83c\udf61|\ud83c\udf62|\ud83c\udf63|\ud83c\udf64|\ud83c\udf65|\ud83c\udf66|\ud83c\udf67|\ud83c\udf68|\ud83c\udf69|\ud83c\udf6a|\ud83c\udf6b|\ud83c\udf6c|\ud83c\udf6d|\ud83c\udf6e|\ud83c\udf6f|\ud83c\udf70|\ud83c\udf71|\ud83c\udf72|\ud83c\udf73|\ud83c\udf74|\ud83c\udf75|\ud83c\udf76|\ud83c\udf77|\ud83c\udf78|\ud83c\udf79|\ud83c\udf7a|\ud83c\udf7b|\ud83c\udf80|\ud83c\udf81|\ud83c\udf82|\ud83c\udf83|\ud83c\udf84|\ud83c\udf85|\ud83c\udf86|\ud83c\udf87|\ud83c\udf88|\ud83c\udf89|\ud83c\udf8a|\ud83c\udf8b|\ud83c\udf8c|\ud83c\udf8d|\ud83c\udf8e|\ud83c\udf8f|\ud83c\udf90|\ud83c\udf91|\ud83c\udf92|\ud83c\udf93|\ud83c\udfa0|\ud83c\udfa1|\ud83c\udfa2|\ud83c\udfa3|\ud83c\udfa4|\ud83c\udfa5|\ud83c\udfa6|\ud83c\udfa7|\ud83c\udfa8|\ud83c\udfa9|\ud83c\udfaa|\ud83c\udfab|\ud83c\udfac|\ud83c\udfad|\ud83c\udfae|\ud83c\udfaf|\ud83c\udfb0|\ud83c\udfb1|\ud83c\udfb2|\ud83c\udfb3|\ud83c\udfb4|\ud83c\udfb5|\ud83c\udfb6|\ud83c\udfb7|\ud83c\udfb8|\ud83c\udfb9|\ud83c\udfba|\ud83c\udfbb|\ud83c\udfbc|\ud83c\udfbd|\ud83c\udfbe|\ud83c\udfbf|\ud83c\udfc0|\ud83c\udfc1|\ud83c\udfc2|\ud83c\udfc3|\ud83c\udfc4|\ud83c\udfc6|\ud83c\udfc8|\ud83c\udfca|\ud83c\udfe0|\ud83c\udfe1|\ud83c\udfe2|\ud83c\udfe3|\ud83c\udfe5|\ud83c\udfe6|\ud83c\udfe7|\ud83c\udfe8|\ud83c\udfe9|\ud83c\udfea|\ud83c\udfeb|\ud83c\udfec|\ud83c\udfed|\ud83c\udfee|\ud83c\udfef|\ud83c\udff0|\ud83d\udc0c|\ud83d\udc0d|\ud83d\udc0e|\ud83d\udc11|\ud83d\udc12|\ud83d\udc14|\ud83d\udc17|\ud83d\udc18|\ud83d\udc19|\ud83d\udc1a|\ud83d\udc1b|\ud83d\udc1c|\ud83d\udc1d|\ud83d\udc1e|\ud83d\udc1f|\ud83d\udc20|\ud83d\udc21|\ud83d\udc22|\ud83d\udc23|\ud83d\udc24|\ud83d\udc25|\ud83d\udc26|\ud83d\udc27|\ud83d\udc28|\ud83d\udc29|\ud83d\udc2b|\ud83d\udc2c|\ud83d\udc2d|\ud83d\udc2e|\ud83d\udc2f|\ud83d\udc30|\ud83d\udc31|\ud83d\udc32|\ud83d\udc33|\ud83d\udc34|\ud83d\udc35|\ud83d\udc36|\ud83d\udc37|\ud83d\udc38|\ud83d\udc39|\ud83d\udc3a|\ud83d\udc3b|\ud83d\udc3c|\ud83d\udc3d|\ud83d\udc3e|\ud83d\udc40|\ud83d\udc42|\ud83d\udc43|\ud83d\udc44|\ud83d\udc45|\ud83d\udc46|\ud83d\udc47|\ud83d\udc48|\ud83d\udc49|\ud83d\udc4a|\ud83d\udc4b|\ud83d\udc4c|\ud83d\udc4d|\ud83d\udc4e|\ud83d\udc4f|\ud83d\udc50|\ud83d\udc51|\ud83d\udc52|\ud83d\udc53|\ud83d\udc54|\ud83d\udc55|\ud83d\udc56|\ud83d\udc57|\ud83d\udc58|\ud83d\udc59|\ud83d\udc5a|\ud83d\udc5b|\ud83d\udc5c|\ud83d\udc5d|\ud83d\udc5e|\ud83d\udc5f|\ud83d\udc60|\ud83d\udc61|\ud83d\udc62|\ud83d\udc63|\ud83d\udc64|\ud83d\udc66|\ud83d\udc67|\ud83d\udc68|\ud83d\udc69|\ud83d\udc6a|\ud83d\udc6b|\ud83d\udc6e|\ud83d\udc6f|\ud83d\udc70|\ud83d\udc71|\ud83d\udc72|\ud83d\udc73|\ud83d\udc74|\ud83d\udc75|\ud83d\udc76|\ud83d\udeb4|\ud83d\udc78|\ud83d\udc79|\ud83d\udc7a|\ud83d\udc7b|\ud83d\udc7c|\ud83d\udc7d|\ud83d\udc7e|\ud83d\udc7f|\ud83d\udc80|\ud83d\udc81|\ud83d\udc82|\ud83d\udc83|\ud83d\udc84|\ud83d\udc85|\ud83d\udc86|\ud83d\udc87|\ud83d\udc88|\ud83d\udc89|\ud83d\udc8a|\ud83d\udc8b|\ud83d\udc8c|\ud83d\udc8d|\ud83d\udc8e|\ud83d\udc8f|\ud83d\udc90|\ud83d\udc91|\ud83d\udc92|\ud83d\udc93|\ud83d\udc94|\ud83d\udc95|\ud83d\udc96|\ud83d\udc97|\ud83d\udc98|\ud83d\udc99|\ud83d\udc9a|\ud83d\udc9b|\ud83d\udc9c|\ud83d\udc9d|\ud83d\udc9e|\ud83d\udc9f|\ud83d\udca0|\ud83d\udca1|\ud83d\udca2|\ud83d\udca3|\ud83d\udca4|\ud83d\udca5|\ud83d\udca6|\ud83d\udca7|\ud83d\udca8|\ud83d\udca9|\ud83d\udcaa|\ud83d\udcab|\ud83d\udcac|\ud83d\udcae|\ud83d\udcaf|\ud83d\udcb0|\ud83d\udcb1|\ud83d\udcb2|\ud83d\udcb3|\ud83d\udcb4|\ud83d\udcb5|\ud83d\udcb8|\ud83d\udcb9|\ud83d\udcba|\ud83d\udcbb|\ud83d\udcbc|\ud83d\udcbd|\ud83d\udcbe|\ud83d\udcbf|\ud83d\udcc0|\ud83d\udcc1|\ud83d\udcc2|\ud83d\udcc3|\ud83d\udcc4|\ud83d\udcc5|\ud83d\udcc6|\ud83d\udcc7|\ud83d\udcc8|\ud83d\udcc9|\ud83d\udcca|\ud83d\udccb|\ud83d\udccc|\ud83d\udccd|\ud83d\udcce|\ud83d\udccf|\ud83d\udcd0|\ud83d\udcd1|\ud83d\udcd2|\ud83d\udcd3|\ud83d\udcd4|\ud83d\udcd5|\ud83d\udcd6|\ud83d\udcd7|\ud83d\udcd8|\ud83d\udcd9|\ud83d\udcda|\ud83d\udcdb|\ud83d\udcdc|\ud83d\udcdd|\ud83d\udcde|\ud83d\udcdf|\ud83d\udce0|\ud83d\udce1|\ud83d\udce2|\ud83d\udce3|\ud83d\udce4|\ud83d\udce5|\ud83d\udce6|\ud83d\udce7|\ud83d\udce8|\ud83d\udce9|\ud83d\udcea|\ud83d\udceb|\ud83d\udcee|\ud83d\udcf0|\ud83d\udcf1|\ud83d\udcf2|\ud83d\udcf3|\ud83d\udcf4|\ud83d\udcf6|\ud83d\udcf7|\ud83d\udcf9|\ud83d\udcfa|\ud83d\udcfb|\ud83d\udcfc|\ud83d\udd03|\ud83d\udd0a|\ud83d\udd0b|\ud83d\udd0c|\ud83d\udd0d|\ud83d\udd0e|\ud83d\udd0f|\ud83d\udd10|\ud83d\udd11|\ud83d\udd12|\ud83d\udd13|\ud83d\udd14|\ud83d\udd16|\ud83d\udd17|\ud83d\udd18|\ud83d\udd19|\ud83d\udd1a|\ud83d\udd1b|\ud83d\udd1c|\ud83d\udd1d|\ud83d\udd1e|\ud83d\udd1f|\ud83d\udd20|\ud83d\udd21|\ud83d\udd22|\ud83d\udd23|\ud83d\udd24|\ud83d\udd25|\ud83d\udd26|\ud83d\udd27|\ud83d\udd28|\ud83d\udd29|\ud83d\udd2a|\ud83d\udd2b|\ud83d\udd2e|\ud83d\udd2f|\ud83d\udd30|\ud83d\udd31|\ud83d\udd32|\ud83d\udd33|\ud83d\udd34|\ud83d\udd35|\ud83d\udd36|\ud83d\udd37|\ud83d\udd38|\ud83d\udd39|\ud83d\udd3a|\ud83d\udd3b|\ud83d\udd3c|\ud83d\udd3d|\ud83d\udd50|\ud83d\udd51|\ud83d\udd52|\ud83d\udd53|\ud83d\udd54|\ud83d\udd55|\ud83d\udd56|\ud83d\udd57|\ud83d\udd58|\ud83d\udd59|\ud83d\udd5a|\ud83d\udd5b|\ud83d\uddfb|\ud83d\uddfc|\ud83d\uddfd|\ud83d\uddfe|\ud83d\uddff|\ud83d\ude01|\ud83d\ude02|\ud83d\ude03|\ud83d\ude04|\ud83d\ude05|\ud83d\ude06|\ud83d\ude09|\ud83d\ude0a|\ud83d\ude0b|\ud83d\ude0c|\ud83d\ude0d|\ud83d\ude0f|\ud83d\ude12|\ud83d\ude13|\ud83d\ude14|\ud83d\ude16|\ud83d\ude18|\ud83d\ude1a|\ud83d\ude1c|\ud83d\ude1d|\ud83d\ude1e|\ud83d\ude20|\ud83d\ude21|\ud83d\ude22|\ud83d\ude23|\ud83d\ude24|\ud83d\ude25|\ud83d\ude28|\ud83d\ude29|\ud83d\ude2a|\ud83d\ude2b|\ud83d\ude2d|\ud83d\ude30|\ud83d\ude31|\ud83d\ude32|\ud83d\ude33|\ud83d\ude35|\ud83d\ude37|\ud83d\ude38|\ud83d\ude39|\ud83d\ude3a|\ud83d\ude3b|\ud83d\ude3c|\ud83d\ude3d|\ud83d\ude3e|\ud83d\ude3f|\ud83d\ude40|\ud83d\ude45|\ud83d\ude46|\ud83d\ude47|\ud83d\ude48|\ud83d\ude49|\ud83d\ude4a|\ud83d\ude4b|\ud83d\ude4c|\ud83d\ude4d|\ud83d\ude4e|\ud83d\ude4f|\ud83d\ude80|\ud83d\ude83|\ud83d\ude84|\ud83d\ude85|\ud83d\ude87|\ud83d\ude89|\ud83d\ude8c|\ud83d\ude8f|\ud83d\ude91|\ud83d\ude92|\ud83d\ude93|\ud83d\ude95|\ud83d\ude97|\ud83d\ude99|\ud83d\ude9a|\ud83d\udea2|\ud83d\udea4|\ud83d\udea5|\ud83d\udea7|\ud83d\udea8|\ud83d\udea9|\ud83d\udeaa|\ud83d\udeab|\ud83d\udeac|\ud83d\udead|\ud83d\udeb2|\ud83d\udeb6|\ud83d\udeb9|\ud83d\udeba|\ud83d\udebb|\ud83d\udebc|\ud83d\udebd|\ud83d\udebe|\ud83d\udec0|\ud83c\udde6|\ud83c\udde7|\ud83c\udde8|\ud83c\udde9|\ud83c\uddea|\ud83c\uddeb|\ud83c\uddec|\ud83c\udded|\ud83c\uddee|\ud83c\uddef|\ud83c\uddf0|\ud83c\uddf1|\ud83c\uddf2|\ud83c\uddf3|\ud83c\uddf4|\ud83c\uddf5|\ud83c\uddf6|\ud83c\uddf7|\ud83c\uddf8|\ud83c\uddf9|\ud83c\uddfa|\ud83c\uddfb|\ud83c\uddfc|\ud83c\uddfd|\ud83c\uddfe|\ud83c\uddff|\ud83c\udf0d|\ud83c\udf0e|\ud83c\udf10|\ud83c\udf12|\ud83c\udf16|\ud83c\udf17|\ue50a|\u27b0|\u2797|\u2796|\u2795|\u2755|\u2754|\u2753|\u274e|\u274c|\u2728|\u270b|\u270a|\u2705|\u26ce|\u23f3|\u23f0|\u23ec|\u23eb|\u23ea|\u23e9|\u27bf|\u00a9|\u00ae)|(?:(?:\ud83c\udc04|\ud83c\udd70|\ud83c\udd71|\ud83c\udd7e|\ud83c\udd7f|\ud83c\ude02|\ud83c\ude1a|\ud83c\ude2f|\ud83c\ude37|\u3299|\u303d|\u3030|\u2b55|\u2b50|\u2b1c|\u2b1b|\u2b07|\u2b06|\u2b05|\u2935|\u2934|\u27a1|\u2764|\u2757|\u2747|\u2744|\u2734|\u2733|\u2716|\u2714|\u2712|\u270f|\u270c|\u2709|\u2708|\u2702|\u26fd|\u26fa|\u26f5|\u26f3|\u26f2|\u26ea|\u26d4|\u26c5|\u26c4|\u26be|\u26bd|\u26ab|\u26aa|\u26a1|\u26a0|\u2693|\u267f|\u267b|\u3297|\u2666|\u2665|\u2663|\u2660|\u2653|\u2652|\u2651|\u2650|\u264f|\u264e|\u264d|\u264c|\u264b|\u264a|\u2649|\u2648|\u263a|\u261d|\u2615|\u2614|\u2611|\u260e|\u2601|\u2600|\u25fe|\u25fd|\u25fc|\u25fb|\u25c0|\u25b6|\u25ab|\u25aa|\u24c2|\u231b|\u231a|\u21aa|\u21a9|\u2199|\u2198|\u2197|\u2196|\u2195|\u2194|\u2139|\u2122|\u2049|\u203c|\u2668)([\uFE0E\uFE0F]?)))/g; + +// Alternative syntax using RegExp constructor +export const regexExEmojis2 = new RegExp('((?:\\ud83c\\udde8\\ud83c\\uddf3|\\ud83c\\uddfa\\ud83c\\uddf8|\\ud83c\\uddf7\\ud83c\\uddfa|\\ud83c\\uddf0\\ud83c\\uddf7|\\ud83c\\uddef\\ud83c\\uddf5|\\ud83c\\uddee\\ud83c\\uddf9|\\ud83c\\uddec\\ud83c\\udde7|\\ud83c\\uddeb\\ud83c\\uddf7|\\ud83c\\uddea\\ud83c\\uddf8|\\ud83c\\udde9\\ud83c\\uddea|\\u0039\\ufe0f?\\u20e3|\\u0038\\ufe0f?\\u20e3|\\u0037\\ufe0f?\\u20e3|\\u0036\\ufe0f?\\u20e3|\\u0035\\ufe0f?\\u20e3|\\u0034\\ufe0f?\\u20e3|\\u0033\\ufe0f?\\u20e3|\\u0032\\ufe0f?\\u20e3|\\u0031\\ufe0f?\\u20e3|\\u0030\\ufe0f?\\u20e3|\\u0023\\ufe0f?\\u20e3|\\ud83d\\udeb3|\\ud83d\\udeb1|\\ud83d\\udeb0|\\ud83d\\udeaf|\\ud83d\\udeae|\\ud83d\\udea6|\\ud83d\\udea3|\\ud83d\\udea1|\\ud83d\\udea0|\\ud83d\\ude9f|\\ud83d\\ude9e|\\ud83d\\ude9d|\\ud83d\\ude9c|\\ud83d\\ude9b|\\ud83d\\ude98|\\ud83d\\ude96|\\ud83d\\ude94|\\ud83d\\ude90|\\ud83d\\ude8e|\\ud83d\\ude8d|\\ud83d\\ude8b|\\ud83d\\ude8a|\\ud83d\\ude88|\\ud83d\\ude86|\\ud83d\\ude82|\\ud83d\\ude81|\\ud83d\\ude36|\\ud83d\\ude34|\\ud83d\\ude2f|\\ud83d\\ude2e|\\ud83d\\ude2c|\\ud83d\\ude27|\\ud83d\\ude26|\\ud83d\\ude1f|\\ud83d\\ude1b|\\ud83d\\ude19|\\ud83d\\ude17|\\ud83d\\ude15|\\ud83d\\ude11|\\ud83d\\ude10|\\ud83d\\ude0e|\\ud83d\\ude08|\\ud83d\\ude07|\\ud83d\\ude00|\\ud83d\\udd67|\\ud83d\\udd66|\\ud83d\\udd65|\\ud83d\\udd64|\\ud83d\\udd63|\\ud83d\\udd62|\\ud83d\\udd61|\\ud83d\\udd60|\\ud83d\\udd5f|\\ud83d\\udd5e|\\ud83d\\udd5d|\\ud83d\\udd5c|\\ud83d\\udd2d|\\ud83d\\udd2c|\\ud83d\\udd15|\\ud83d\\udd09|\\ud83d\\udd08|\\ud83d\\udd07|\\ud83d\\udd06|\\ud83d\\udd05|\\ud83d\\udd04|\\ud83d\\udd02|\\ud83d\\udd01|\\ud83d\\udd00|\\ud83d\\udcf5|\\ud83d\\udcef|\\ud83d\\udced|\\ud83d\\udcec|\\ud83d\\udcb7|\\ud83d\\udcb6|\\ud83d\\udcad|\\ud83d\\udc6d|\\ud83d\\udc6c|\\ud83d\\udc65|\\ud83d\\udc2a|\\ud83d\\udc16|\\ud83d\\udc15|\\ud83d\\udc13|\\ud83d\\udc10|\\ud83d\\udc0f|\\ud83d\\udc0b|\\ud83d\\udc0a|\\ud83d\\udc09|\\ud83d\\udc08|\\ud83d\\udc07|\\ud83d\\udc06|\\ud83d\\udc05|\\ud83d\\udc04|\\ud83d\\udc03|\\ud83d\\udc02|\\ud83d\\udc01|\\ud83d\\udc00|\\ud83c\\udfe4|\\ud83c\\udfc9|\\ud83c\\udfc7|\\ud83c\\udf7c|\\ud83c\\udf50|\\ud83c\\udf4b|\\ud83c\\udf33|\\ud83c\\udf32|\\ud83c\\udf1e|\\ud83c\\udf1d|\\ud83c\\udf1c|\\ud83c\\udf1a|\\ud83c\\udf18|\\ud83c\\udccf|\\ud83c\\udd8e|\\ud83c\\udd91|\\ud83c\\udd92|\\ud83c\\udd93|\\ud83c\\udd94|\\ud83c\\udd95|\\ud83c\\udd96|\\ud83c\\udd97|\\ud83c\\udd98|\\ud83c\\udd99|\\ud83c\\udd9a|\\ud83d\\udc77|\\ud83d\\udec5|\\ud83d\\udec4|\\ud83d\\udec3|\\ud83d\\udec2|\\ud83d\\udec1|\\ud83d\\udebf|\\ud83d\\udeb8|\\ud83d\\udeb7|\\ud83d\\udeb5|\\ud83c\\ude01|\\ud83c\\ude32|\\ud83c\\ude33|\\ud83c\\ude34|\\ud83c\\ude35|\\ud83c\\ude36|\\ud83c\\ude38|\\ud83c\\ude39|\\ud83c\\ude3a|\\ud83c\\ude50|\\ud83c\\ude51|\\ud83c\\udf00|\\ud83c\\udf01|\\ud83c\\udf02|\\ud83c\\udf03|\\ud83c\\udf04|\\ud83c\\udf05|\\ud83c\\udf06|\\ud83c\\udf07|\\ud83c\\udf08|\\ud83c\\udf09|\\ud83c\\udf0a|\\ud83c\\udf0b|\\ud83c\\udf0c|\\ud83c\\udf0f|\\ud83c\\udf11|\\ud83c\\udf13|\\ud83c\\udf14|\\ud83c\\udf15|\\ud83c\\udf19|\\ud83c\\udf1b|\\ud83c\\udf1f|\\ud83c\\udf20|\\ud83c\\udf30|\\ud83c\\udf31|\\ud83c\\udf34|\\ud83c\\udf35|\\ud83c\\udf37|\\ud83c\\udf38|\\ud83c\\udf39|\\ud83c\\udf3a|\\ud83c\\udf3b|\\ud83c\\udf3c|\\ud83c\\udf3d|\\ud83c\\udf3e|\\ud83c\\udf3f|\\ud83c\\udf40|\\ud83c\\udf41|\\ud83c\\udf42|\\ud83c\\udf43|\\ud83c\\udf44|\\ud83c\\udf45|\\ud83c\\udf46|\\ud83c\\udf47|\\ud83c\\udf48|\\ud83c\\udf49|\\ud83c\\udf4a|\\ud83c\\udf4c|\\ud83c\\udf4d|\\ud83c\\udf4e|\\ud83c\\udf4f|\\ud83c\\udf51|\\ud83c\\udf52|\\ud83c\\udf53|\\ud83c\\udf54|\\ud83c\\udf55|\\ud83c\\udf56|\\ud83c\\udf57|\\ud83c\\udf58|\\ud83c\\udf59|\\ud83c\\udf5a|\\ud83c\\udf5b|\\ud83c\\udf5c|\\ud83c\\udf5d|\\ud83c\\udf5e|\\ud83c\\udf5f|\\ud83c\\udf60|\\ud83c\\udf61|\\ud83c\\udf62|\\ud83c\\udf63|\\ud83c\\udf64|\\ud83c\\udf65|\\ud83c\\udf66|\\ud83c\\udf67|\\ud83c\\udf68|\\ud83c\\udf69|\\ud83c\\udf6a|\\ud83c\\udf6b|\\ud83c\\udf6c|\\ud83c\\udf6d|\\ud83c\\udf6e|\\ud83c\\udf6f|\\ud83c\\udf70|\\ud83c\\udf71|\\ud83c\\udf72|\\ud83c\\udf73|\\ud83c\\udf74|\\ud83c\\udf75|\\ud83c\\udf76|\\ud83c\\udf77|\\ud83c\\udf78|\\ud83c\\udf79|\\ud83c\\udf7a|\\ud83c\\udf7b|\\ud83c\\udf80|\\ud83c\\udf81|\\ud83c\\udf82|\\ud83c\\udf83|\\ud83c\\udf84|\\ud83c\\udf85|\\ud83c\\udf86|\\ud83c\\udf87|\\ud83c\\udf88|\\ud83c\\udf89|\\ud83c\\udf8a|\\ud83c\\udf8b|\\ud83c\\udf8c|\\ud83c\\udf8d|\\ud83c\\udf8e|\\ud83c\\udf8f|\\ud83c\\udf90|\\ud83c\\udf91|\\ud83c\\udf92|\\ud83c\\udf93|\\ud83c\\udfa0|\\ud83c\\udfa1|\\ud83c\\udfa2|\\ud83c\\udfa3|\\ud83c\\udfa4|\\ud83c\\udfa5|\\ud83c\\udfa6|\\ud83c\\udfa7|\\ud83c\\udfa8|\\ud83c\\udfa9|\\ud83c\\udfaa|\\ud83c\\udfab|\\ud83c\\udfac|\\ud83c\\udfad|\\ud83c\\udfae|\\ud83c\\udfaf|\\ud83c\\udfb0|\\ud83c\\udfb1|\\ud83c\\udfb2|\\ud83c\\udfb3|\\ud83c\\udfb4|\\ud83c\\udfb5|\\ud83c\\udfb6|\\ud83c\\udfb7|\\ud83c\\udfb8|\\ud83c\\udfb9|\\ud83c\\udfba|\\ud83c\\udfbb|\\ud83c\\udfbc|\\ud83c\\udfbd|\\ud83c\\udfbe|\\ud83c\\udfbf|\\ud83c\\udfc0|\\ud83c\\udfc1|\\ud83c\\udfc2|\\ud83c\\udfc3|\\ud83c\\udfc4|\\ud83c\\udfc6|\\ud83c\\udfc8|\\ud83c\\udfca|\\ud83c\\udfe0|\\ud83c\\udfe1|\\ud83c\\udfe2|\\ud83c\\udfe3|\\ud83c\\udfe5|\\ud83c\\udfe6|\\ud83c\\udfe7|\\ud83c\\udfe8|\\ud83c\\udfe9|\\ud83c\\udfea|\\ud83c\\udfeb|\\ud83c\\udfec|\\ud83c\\udfed|\\ud83c\\udfee|\\ud83c\\udfef|\\ud83c\\udff0|\\ud83d\\udc0c|\\ud83d\\udc0d|\\ud83d\\udc0e|\\ud83d\\udc11|\\ud83d\\udc12|\\ud83d\\udc14|\\ud83d\\udc17|\\ud83d\\udc18|\\ud83d\\udc19|\\ud83d\\udc1a|\\ud83d\\udc1b|\\ud83d\\udc1c|\\ud83d\\udc1d|\\ud83d\\udc1e|\\ud83d\\udc1f|\\ud83d\\udc20|\\ud83d\\udc21|\\ud83d\\udc22|\\ud83d\\udc23|\\ud83d\\udc24|\\ud83d\\udc25|\\ud83d\\udc26|\\ud83d\\udc27|\\ud83d\\udc28|\\ud83d\\udc29|\\ud83d\\udc2b|\\ud83d\\udc2c|\\ud83d\\udc2d|\\ud83d\\udc2e|\\ud83d\\udc2f|\\ud83d\\udc30|\\ud83d\\udc31|\\ud83d\\udc32|\\ud83d\\udc33|\\ud83d\\udc34|\\ud83d\\udc35|\\ud83d\\udc36|\\ud83d\\udc37|\\ud83d\\udc38|\\ud83d\\udc39|\\ud83d\\udc3a|\\ud83d\\udc3b|\\ud83d\\udc3c|\\ud83d\\udc3d|\\ud83d\\udc3e|\\ud83d\\udc40|\\ud83d\\udc42|\\ud83d\\udc43|\\ud83d\\udc44|\\ud83d\\udc45|\\ud83d\\udc46|\\ud83d\\udc47|\\ud83d\\udc48|\\ud83d\\udc49|\\ud83d\\udc4a|\\ud83d\\udc4b|\\ud83d\\udc4c|\\ud83d\\udc4d|\\ud83d\\udc4e|\\ud83d\\udc4f|\\ud83d\\udc50|\\ud83d\\udc51|\\ud83d\\udc52|\\ud83d\\udc53|\\ud83d\\udc54|\\ud83d\\udc55|\\ud83d\\udc56|\\ud83d\\udc57|\\ud83d\\udc58|\\ud83d\\udc59|\\ud83d\\udc5a|\\ud83d\\udc5b|\\ud83d\\udc5c|\\ud83d\\udc5d|\\ud83d\\udc5e|\\ud83d\\udc5f|\\ud83d\\udc60|\\ud83d\\udc61|\\ud83d\\udc62|\\ud83d\\udc63|\\ud83d\\udc64|\\ud83d\\udc66|\\ud83d\\udc67|\\ud83d\\udc68|\\ud83d\\udc69|\\ud83d\\udc6a|\\ud83d\\udc6b|\\ud83d\\udc6e|\\ud83d\\udc6f|\\ud83d\\udc70|\\ud83d\\udc71|\\ud83d\\udc72|\\ud83d\\udc73|\\ud83d\\udc74|\\ud83d\\udc75|\\ud83d\\udc76|\\ud83d\\udeb4|\\ud83d\\udc78|\\ud83d\\udc79|\\ud83d\\udc7a|\\ud83d\\udc7b|\\ud83d\\udc7c|\\ud83d\\udc7d|\\ud83d\\udc7e|\\ud83d\\udc7f|\\ud83d\\udc80|\\ud83d\\udc81|\\ud83d\\udc82|\\ud83d\\udc83|\\ud83d\\udc84|\\ud83d\\udc85|\\ud83d\\udc86|\\ud83d\\udc87|\\ud83d\\udc88|\\ud83d\\udc89|\\ud83d\\udc8a|\\ud83d\\udc8b|\\ud83d\\udc8c|\\ud83d\\udc8d|\\ud83d\\udc8e|\\ud83d\\udc8f|\\ud83d\\udc90|\\ud83d\\udc91|\\ud83d\\udc92|\\ud83d\\udc93|\\ud83d\\udc94|\\ud83d\\udc95|\\ud83d\\udc96|\\ud83d\\udc97|\\ud83d\\udc98|\\ud83d\\udc99|\\ud83d\\udc9a|\\ud83d\\udc9b|\\ud83d\\udc9c|\\ud83d\\udc9d|\\ud83d\\udc9e|\\ud83d\\udc9f|\\ud83d\\udca0|\\ud83d\\udca1|\\ud83d\\udca2|\\ud83d\\udca3|\\ud83d\\udca4|\\ud83d\\udca5|\\ud83d\\udca6|\\ud83d\\udca7|\\ud83d\\udca8|\\ud83d\\udca9|\\ud83d\\udcaa|\\ud83d\\udcab|\\ud83d\\udcac|\\ud83d\\udcae|\\ud83d\\udcaf|\\ud83d\\udcb0|\\ud83d\\udcb1|\\ud83d\\udcb2|\\ud83d\\udcb3|\\ud83d\\udcb4|\\ud83d\\udcb5|\\ud83d\\udcb8|\\ud83d\\udcb9|\\ud83d\\udcba|\\ud83d\\udcbb|\\ud83d\\udcbc|\\ud83d\\udcbd|\\ud83d\\udcbe|\\ud83d\\udcbf|\\ud83d\\udcc0|\\ud83d\\udcc1|\\ud83d\\udcc2|\\ud83d\\udcc3|\\ud83d\\udcc4|\\ud83d\\udcc5|\\ud83d\\udcc6|\\ud83d\\udcc7|\\ud83d\\udcc8|\\ud83d\\udcc9|\\ud83d\\udcca|\\ud83d\\udccb|\\ud83d\\udccc|\\ud83d\\udccd|\\ud83d\\udcce|\\ud83d\\udccf|\\ud83d\\udcd0|\\ud83d\\udcd1|\\ud83d\\udcd2|\\ud83d\\udcd3|\\ud83d\\udcd4|\\ud83d\\udcd5|\\ud83d\\udcd6|\\ud83d\\udcd7|\\ud83d\\udcd8|\\ud83d\\udcd9|\\ud83d\\udcda|\\ud83d\\udcdb|\\ud83d\\udcdc|\\ud83d\\udcdd|\\ud83d\\udcde|\\ud83d\\udcdf|\\ud83d\\udce0|\\ud83d\\udce1|\\ud83d\\udce2|\\ud83d\\udce3|\\ud83d\\udce4|\\ud83d\\udce5|\\ud83d\\udce6|\\ud83d\\udce7|\\ud83d\\udce8|\\ud83d\\udce9|\\ud83d\\udcea|\\ud83d\\udceb|\\ud83d\\udcee|\\ud83d\\udcf0|\\ud83d\\udcf1|\\ud83d\\udcf2|\\ud83d\\udcf3|\\ud83d\\udcf4|\\ud83d\\udcf6|\\ud83d\\udcf7|\\ud83d\\udcf9|\\ud83d\\udcfa|\\ud83d\\udcfb|\\ud83d\\udcfc|\\ud83d\\udd03|\\ud83d\\udd0a|\\ud83d\\udd0b|\\ud83d\\udd0c|\\ud83d\\udd0d|\\ud83d\\udd0e|\\ud83d\\udd0f|\\ud83d\\udd10|\\ud83d\\udd11|\\ud83d\\udd12|\\ud83d\\udd13|\\ud83d\\udd14|\\ud83d\\udd16|\\ud83d\\udd17|\\ud83d\\udd18|\\ud83d\\udd19|\\ud83d\\udd1a|\\ud83d\\udd1b|\\ud83d\\udd1c|\\ud83d\\udd1d|\\ud83d\\udd1e|\\ud83d\\udd1f|\\ud83d\\udd20|\\ud83d\\udd21|\\ud83d\\udd22|\\ud83d\\udd23|\\ud83d\\udd24|\\ud83d\\udd25|\\ud83d\\udd26|\\ud83d\\udd27|\\ud83d\\udd28|\\ud83d\\udd29|\\ud83d\\udd2a|\\ud83d\\udd2b|\\ud83d\\udd2e|\\ud83d\\udd2f|\\ud83d\\udd30|\\ud83d\\udd31|\\ud83d\\udd32|\\ud83d\\udd33|\\ud83d\\udd34|\\ud83d\\udd35|\\ud83d\\udd36|\\ud83d\\udd37|\\ud83d\\udd38|\\ud83d\\udd39|\\ud83d\\udd3a|\\ud83d\\udd3b|\\ud83d\\udd3c|\\ud83d\\udd3d|\\ud83d\\udd50|\\ud83d\\udd51|\\ud83d\\udd52|\\ud83d\\udd53|\\ud83d\\udd54|\\ud83d\\udd55|\\ud83d\\udd56|\\ud83d\\udd57|\\ud83d\\udd58|\\ud83d\\udd59|\\ud83d\\udd5a|\\ud83d\\udd5b|\\ud83d\\uddfb|\\ud83d\\uddfc|\\ud83d\\uddfd|\\ud83d\\uddfe|\\ud83d\\uddff|\\ud83d\\ude01|\\ud83d\\ude02|\\ud83d\\ude03|\\ud83d\\ude04|\\ud83d\\ude05|\\ud83d\\ude06|\\ud83d\\ude09|\\ud83d\\ude0a|\\ud83d\\ude0b|\\ud83d\\ude0c|\\ud83d\\ude0d|\\ud83d\\ude0f|\\ud83d\\ude12|\\ud83d\\ude13|\\ud83d\\ude14|\\ud83d\\ude16|\\ud83d\\ude18|\\ud83d\\ude1a|\\ud83d\\ude1c|\\ud83d\\ude1d|\\ud83d\\ude1e|\\ud83d\\ude20|\\ud83d\\ude21|\\ud83d\\ude22|\\ud83d\\ude23|\\ud83d\\ude24|\\ud83d\\ude25|\\ud83d\\ude28|\\ud83d\\ude29|\\ud83d\\ude2a|\\ud83d\\ude2b|\\ud83d\\ude2d|\\ud83d\\ude30|\\ud83d\\ude31|\\ud83d\\ude32|\\ud83d\\ude33|\\ud83d\\ude35|\\ud83d\\ude37|\\ud83d\\ude38|\\ud83d\\ude39|\\ud83d\\ude3a|\\ud83d\\ude3b|\\ud83d\\ude3c|\\ud83d\\ude3d|\\ud83d\\ude3e|\\ud83d\\ude3f|\\ud83d\\ude40|\\ud83d\\ude45|\\ud83d\\ude46|\\ud83d\\ude47|\\ud83d\\ude48|\\ud83d\\ude49|\\ud83d\\ude4a|\\ud83d\\ude4b|\\ud83d\\ude4c|\\ud83d\\ude4d|\\ud83d\\ude4e|\\ud83d\\ude4f|\\ud83d\\ude80|\\ud83d\\ude83|\\ud83d\\ude84|\\ud83d\\ude85|\\ud83d\\ude87|\\ud83d\\ude89|\\ud83d\\ude8c|\\ud83d\\ude8f|\\ud83d\\ude91|\\ud83d\\ude92|\\ud83d\\ude93|\\ud83d\\ude95|\\ud83d\\ude97|\\ud83d\\ude99|\\ud83d\\ude9a|\\ud83d\\udea2|\\ud83d\\udea4|\\ud83d\\udea5|\\ud83d\\udea7|\\ud83d\\udea8|\\ud83d\\udea9|\\ud83d\\udeaa|\\ud83d\\udeab|\\ud83d\\udeac|\\ud83d\\udead|\\ud83d\\udeb2|\\ud83d\\udeb6|\\ud83d\\udeb9|\\ud83d\\udeba|\\ud83d\\udebb|\\ud83d\\udebc|\\ud83d\\udebd|\\ud83d\\udebe|\\ud83d\\udec0|\\ud83c\\udde6|\\ud83c\\udde7|\\ud83c\\udde8|\\ud83c\\udde9|\\ud83c\\uddea|\\ud83c\\uddeb|\\ud83c\\uddec|\\ud83c\\udded|\\ud83c\\uddee|\\ud83c\\uddef|\\ud83c\\uddf0|\\ud83c\\uddf1|\\ud83c\\uddf2|\\ud83c\\uddf3|\\ud83c\\uddf4|\\ud83c\\uddf5|\\ud83c\\uddf6|\\ud83c\\uddf7|\\ud83c\\uddf8|\\ud83c\\uddf9|\\ud83c\\uddfa|\\ud83c\\uddfb|\\ud83c\\uddfc|\\ud83c\\uddfd|\\ud83c\\uddfe|\\ud83c\\uddff|\\ud83c\\udf0d|\\ud83c\\udf0e|\\ud83c\\udf10|\\ud83c\\udf12|\\ud83c\\udf16|\\ud83c\\udf17|\\ue50a|\\u27b0|\\u2797|\\u2796|\\u2795|\\u2755|\\u2754|\\u2753|\\u274e|\\u274c|\\u2728|\\u270b|\\u270a|\\u2705|\\u26ce|\\u23f3|\\u23f0|\\u23ec|\\u23eb|\\u23ea|\\u23e9|\\u27bf|\\u00a9|\\u00ae)|(?:(?:\\ud83c\\udc04|\\ud83c\\udd70|\\ud83c\\udd71|\\ud83c\\udd7e|\\ud83c\\udd7f|\\ud83c\\ude02|\\ud83c\\ude1a|\\ud83c\\ude2f|\\ud83c\\ude37|\\u3299|\\u303d|\\u3030|\\u2b55|\\u2b50|\\u2b1c|\\u2b1b|\\u2b07|\\u2b06|\\u2b05|\\u2935|\\u2934|\\u27a1|\\u2764|\\u2757|\\u2747|\\u2744|\\u2734|\\u2733|\\u2716|\\u2714|\\u2712|\\u270f|\\u270c|\\u2709|\\u2708|\\u2702|\\u26fd|\\u26fa|\\u26f5|\\u26f3|\\u26f2|\\u26ea|\\u26d4|\\u26c5|\\u26c4|\\u26be|\\u26bd|\\u26ab|\\u26aa|\\u26a1|\\u26a0|\\u2693|\\u267f|\\u267b|\\u3297|\\u2666|\\u2665|\\u2663|\\u2660|\\u2653|\\u2652|\\u2651|\\u2650|\\u264f|\\u264e|\\u264d|\\u264c|\\u264b|\\u264a|\\u2649|\\u2648|\\u263a|\\u261d|\\u2615|\\u2614|\\u2611|\\u260e|\\u2601|\\u2600|\\u25fe|\\u25fd|\\u25fc|\\u25fb|\\u25c0|\\u25b6|\\u25ab|\\u25aa|\\u24c2|\\u231b|\\u231a|\\u21aa|\\u21a9|\\u2199|\\u2198|\\u2197|\\u2196|\\u2195|\\u2194|\\u2139|\\u2122|\\u2049|\\u203c|\\u2668)([\\uFE0E\\uFE0F]?)))', 'g') + +// https://mths.be/emoji +export const regexExEmojis3 = /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2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DE6\uDDF2\uDDFC]|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC08\uDC26](?:\u200D\u2B1B)?|[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC2\uDECE-\uDEDB\uDEE0-\uDEE8]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF-\uDDB3\uDDBC\uDDBD]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g; + +const regexExEmojis4 = /([#0-9]\u20E3)|[\xA9\xAE\u203C\u2047-\u2049\u2122\u2139\u3030\u303D\u3297\u3299][\uFE00-\uFEFF]?|[\u2190-\u21FF][\uFE00-\uFEFF]?|[\u2300-\u23FF][\uFE00-\uFEFF]?|[\u2460-\u24FF][\uFE00-\uFEFF]?|[\u25A0-\u25FF][\uFE00-\uFEFF]?|[\u2600-\u27BF][\uFE00-\uFEFF]?|[\u2900-\u297F][\uFE00-\uFEFF]?|[\u2B00-\u2BF0][\uFE00-\uFEFF]?|(?:\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDEFF])[\uFE00-\uFEFF]?/g diff --git a/packages/commons/src/logger.ts b/packages/commons/src/logger.ts new file mode 100644 index 00000000..49585351 --- /dev/null +++ b/packages/commons/src/logger.ts @@ -0,0 +1,17 @@ +import { ISettingsParam, Logger } from "tslog" + +export function createLogger(name: string, options?: any) { + return new Logger({ + name, + type: 'pretty', + ...options, + }) +} +export const defaultLogger = createLogger('DefaultLogger', { + minLevel: 1 +}) + +import { MODULE_NAME } from './constants.js' +export { MODULE_NAME } from './constants.js' + +export const logger = createLogger(MODULE_NAME, {}) diff --git a/packages/commons/src/os.ts b/packages/commons/src/os.ts new file mode 100644 index 00000000..8272272f --- /dev/null +++ b/packages/commons/src/os.ts @@ -0,0 +1,10 @@ +export enum EPlatform { + Linux = 'linux', + Windows = 'win32', + OSX = 'darwin' +} +export enum EArch { + x64 = '64', + x32 = '32' +} +export const is_windows = () => process && (process.platform === 'win32') diff --git a/packages/commons/src/osr/component.ts b/packages/commons/src/osr/component.ts new file mode 100644 index 00000000..91fe24c1 --- /dev/null +++ b/packages/commons/src/osr/component.ts @@ -0,0 +1,102 @@ +import { IDiscourseUploadImage } from './discourse.js' + +export interface IDiscourseItemCommons { + // Discourse + forum?: string | boolean + // explicit forum title, otherwise #name will be used + forumTitle?: string + // linked Discourse category + forumCategory?: number + // Discourse tags + forumTags?: string | string[] + // Discourse post_id + forumPostId?: number + // Discourse topic_id + forumTopicId?: number + // Discourse owner id + forumUserId?: number + // Discourse owner username + forumUserName?: string + // last content hash + forumPostHash?: string + // map of Discourse uploads (internal uri > discourse upload uri) + forumUploads?: Record +} + +export interface IComponentConfig extends IDiscourseItemCommons { + + //CS-Cart + cart_id?: string + code: string + price?: number + + cscartCats?: number[] + cscartId?: number + vendorId?: number + + //OSR internal + + version?: string + status?: string + + authors: IAuthor[] + // outdated and replaced by (using slug) + replaced_by?: string + // alternative components (using slug) + alternatives?: string[] + // internal processing flags + flags?: number + //related Discourse howto categories + howto_categories?: string | string[] + + //content source language code (ISO) + sourceLanguage?: string + + //last sync timestamp + last_sync_ts?: number + + //OSR public + + // explicit download url, otherwise default expression + download?: boolean + // explicit 3d preview url, otherwise default expression + edrawings?: string + // human readable title (used for Discourse and CSCart) + name: string + + // content visibility features (used for Discourse and CSCart) + showDimensions?: boolean + + showParts?: boolean + + slug: string + + score?: number + Preview3d?: boolean + + keywords?: string + meta_keywords?: string + + // kb + + steps?: any + + /** + * @deprecated + */ + category: string + product_dimensions?: string + production?: IProduction + +} + +export interface IAuthor { + name: string + url: string +} + +export interface IProduction { + "fusion-folder": string + "nc-folder": string + cam: IAuthor[] +} diff --git a/packages/commons/src/osr/discourse.ts b/packages/commons/src/osr/discourse.ts new file mode 100644 index 00000000..43bb0d07 --- /dev/null +++ b/packages/commons/src/osr/discourse.ts @@ -0,0 +1,15 @@ +export interface IDiscourseUploadImage { + id: number + url: string + original_filename: string + filesize: number + width: number + height: number + thumbnail_width: number + thumbnail_height: number + extension: string + short_url: string + short_path: string + retain_hours: any + human_filesize: string + } \ No newline at end of file diff --git a/packages/commons/src/paths.ts b/packages/commons/src/paths.ts new file mode 100644 index 00000000..e69de29b diff --git a/packages/commons/src/profile.ts b/packages/commons/src/profile.ts new file mode 100644 index 00000000..1e60e6ed --- /dev/null +++ b/packages/commons/src/profile.ts @@ -0,0 +1,98 @@ +import * as path from 'path' +import { REGEX_VAR } from "@polymech/core/constants.js" +import { sync as read } from '@polymech/fs/read' +import { sync as exists } from '@polymech/fs/exists' +import { isString } from '@polymech/core/types.js' +import { resolve, substitute } from './variables.js' + +interface EnvVariables { + [key: string]: string +} + +interface EnvConfig { + includes: string[] + variables: EnvVariables +} + +export interface IProfile { + includes: string[] + variables: EnvVariables + env: { + [key: string]: EnvConfig + } +} + + +const _resolve = (config) => { + for (const key in config) { + if (config[key] && typeof config[key] == 'string') { + const resolved = substitute(false, config[key], config) + config[key] = resolved + } + } + return config; +} +// @todo: Implement the function `resolveConfig` +export const resolveConfig = (config) => { + config = _resolve(config) + config = _resolve(config) + return config +} +export const parseProfile = (profilePath: string, profile: IProfile, options: { env: string } = { env: 'default' }, rel?: string) => { + profilePath = path.resolve(resolve(profilePath, false, profile.variables)) + if (!exists(profilePath as string)) { + return + } + const _profile = read(profilePath as string, 'json') as any || { includes: [], variables: {} } as IProfile + + _profile.includes = _profile.includes || [] + _profile.variables = _profile.variables || {} + + if (options.env && _profile.env && _profile.env[options.env] && _profile.env[options.env].includes) { + profile.includes = [ + ...profile.includes, + ..._profile.includes, + ..._profile.env[options.env].includes + ] + } else { + profile.includes = [ + ...profile.includes, + ..._profile.includes + ] + } + if (options.env && _profile.env && _profile.env[options.env] && _profile.env[options.env].variables) { + profile.variables = { + ...profile.variables, + ..._profile.variables, + ..._profile.env[options.env].variables + } + } + for (const k in _profile.variables) { + if (isString(_profile.variables[k])) { + _profile.variables[k] = substitute(false, _profile.variables[k], profile.variables) + } + } + + profile.variables = { ...profile.variables, ..._profile.variables, ..._profile.env[options.env]?.variables || {} } + for (const k in profile.variables) { + if (isString(profile.variables[k])) { + profile.variables[k] = substitute(false, profile.variables[k], profile.variables) + } + } + profile.includes = Array.from(new Set(profile.includes)) + profile.includes = [ + ...profile.includes.map((i) => { + if (!path.isAbsolute(i) && rel && !i.match(REGEX_VAR)) { + return path.resolve(`${rel}/${i}`) + } + let ret = resolve(i, false, profile.variables) + ret = path.resolve(substitute(false, ret, profile.variables)) + return ret + })] + + profile.includes = profile.includes.filter((include) => + include !== null && + include !== '') + profile.includes = Array.from(new Set(profile.includes)) + return profile +} \ No newline at end of file diff --git a/packages/commons/src/shemas/index.ts b/packages/commons/src/shemas/index.ts index f90d65a9..9b652c84 100644 --- a/packages/commons/src/shemas/index.ts +++ b/packages/commons/src/shemas/index.ts @@ -1,10 +1,13 @@ -import * as path from 'node:path' +import * as path from 'path' import * as CLI from 'yargs' import { z, ZodTypeAny, ZodObject, ZodEffects, ZodOptional, ZodDefault } from 'zod' import { sync as writeFS } from '@polymech/fs/write' import { zodToTs, printNode } from 'zod-to-ts' import { zodToJsonSchema } from "zod-to-json-schema" -import { logger } from '../logger' + +import { logger } from '@/logger.js' +export * from './path.js' +export * from './zod_map.js' type InnerType = T extends ZodEffects ? InnerType : T @@ -14,7 +17,6 @@ type GetInnerType = T extends ZodObject ? InnerType : never; -export * from './path' export const generate_interfaces = (schemas: ZodObject[], dst: string) => { const types = schemas.map(schema => `export interface ${schema.description || 'IOptions'} ${printNode(zodToTs(schema).node)}`) @@ -215,4 +217,4 @@ export const combineValidatorsOrUsingZod2 = (validators: z.ZodTypeAny[]) => { }) }) } -export * from './zod_map' + diff --git a/packages/commons/src/shemas/path.ts b/packages/commons/src/shemas/path.ts index 2daf8fbe..7c81e067 100644 --- a/packages/commons/src/shemas/path.ts +++ b/packages/commons/src/shemas/path.ts @@ -2,18 +2,17 @@ import { z, ZodTypeAny } from 'zod' import * as path from 'path' import { accessSync, constants, lstatSync, existsSync } from 'fs' -import { isString } from '@polymech/' +import { isString } from '@polymech/core/primitives.js' -import { logger } from '../logger' +import { logger } from '@/logger.js' import { sync as exists } from '@polymech/fs/exists' import { sync as read } from '@polymech/fs/read' -import { DEFAULT_VARS, resolve, resolveVariables } from '../variables' - -import { getDescription } from '../' -import { isFile } from '../lib/fs' +import { DEFAULT_VARS, resolve, resolveVariables } from '@/variables.js' +import { getDescription } from '@/shemas/index.js' +import { isFile } from '@/lib/fs.js' type TResult = { resolved: string, source: string, value: unknown } type TRefine = (src: string, ctx: any, variables: Record) => string | z.ZodNever @@ -41,7 +40,7 @@ export enum E_PATH { ENSURE_PATH_IS_RELATIVE, GET_PATH_INFO } -export const Transformers = { +export const Transformers:Record = { resolve: (val: string, variables: Record = {}) => { if (!val) { return null @@ -238,7 +237,7 @@ export const test = () => { return ret } -export const Templates = +export const Templates:Record = { json: { refine: [IS_VALID_STRING, ENSURE_PATH_EXISTS], diff --git a/packages/commons/src/types.ts b/packages/commons/src/types.ts new file mode 100644 index 00000000..4f9a3cc2 --- /dev/null +++ b/packages/commons/src/types.ts @@ -0,0 +1,365 @@ +export interface IConvertedFileMeta { + photoData: Blob + objectUrl: string + name: string + type: string +} + +export interface IUploadedFileMeta { + downloadUrl: string + contentType?: string | null + fullPath: string + name: string + type: string + size: number + timeCreated: string + updated: string + data: any +} + +// Types for moderation status +export type IModerationStatus = + | 'draft' + | 'awaiting-moderation' + | 'rejected' + | 'accepted' + +export interface IModerable { + moderation: IModerationStatus + _createdBy?: string + _id?: string +} + +export type ISODateString = string; + +export interface IUserState { + user?: IUser +} +// IUser retains most of the fields from legacy users (omitting passwords), +// and has a few additional fields. Note 'email' is excluded +// _uid is unique/fixed identifier +// ALL USER INFO BELOW IS PUBLIC +export interface IUser { + // authID is additional id populated by firebase auth, required for some auth operations + _authID: string + _lastActive?: ISODateString + // userName is same as legacy 'mention_name', e.g. @my-name. It will also be the doc _id and + // firebase auth displayName property + userName: string + displayName: string + moderation: IModerationStatus + // note, user avatar url is taken direct from userName so no longer populated here + // avatar:string + verified: boolean + badges?: IUserBadges + // images will be in different formats if they are pending upload vs pulled from db + coverImages: IUploadedFileMeta[] | IConvertedFileMeta[] + links: IExternalLink[] + userRoles?: string[] + about?: string | null + DHSite_id?: number + DHSite_mention_name?: string + country?: string | null + // location?: ILocation | null + year?: ISODateString + stats?: IUserStats + /** keep a map of all howto ids that a user has voted as useful */ + votedUsefulHowtos?: { [howtoId: string]: boolean } + /** keep a map of all Research ids that a user has voted as useful */ + votedUsefulResearch?: { [researchId: string]: boolean } + notifications?: INotification[] +} + +interface IUserBadges { + verified: boolean +} + +interface IExternalLink { + url: string + label: + | 'email' + | 'website' + | 'discord' + | 'bazar' + | 'forum' + | 'social media' + | 'facebook' + | 'instagram' + | 'github' + | 'linkedin' + | 'map' + | 'forum' + | 'marketplace' + | 'other' + | 'other-2' +} + +/** + * Track the ids and moderation status as summary for user stats + */ +interface IUserStats { + userCreatedHowtos: { [id: string]: IModerationStatus } + userCreatedResearch: { [id: string]: IModerationStatus } + userCreatedEvents: { [id: string]: IModerationStatus } +} + +export type IUserDB = IUser; + +export interface INotification { + _id: string + _created: string + triggeredBy: { + displayName: string + userId: string + } + relevantUrl?: string + type: NotificationType + read: boolean +} + +export type NotificationType = + | 'new_comment' + | 'howto_useful' + | 'new_comment_research' + | 'research_useful' + + +export type PlasticTypeLabel = + | 'pet' + | 'hdpe' + | 'pvc' + | 'ldpe' + | 'pp' + | 'ps' + | 'other' + +export type MachineBuilderXpLabel = + | 'electronics' + | 'machining' + | 'welding' + | 'assembling' + | 'mould-making' + | 'development' + +export type WorkspaceType = + | 'shredder' + | 'sheetpress' + | 'extrusion' + | 'injection' + | 'mix' + | 'machine shop' + | 'service' + | 'educational' + | 'supplier' + | '3dprint' + +export type TOSR_User_Type = + | 'Precious Plastic' + | 'OSR-Plastic' + | 'Unknown' + | 'User Contact' + | 'Crawler' + | 'Fablab' + | 'OSE' + | 'Meetup' + +export interface IPlasticType { + label: PlasticTypeLabel + number: string + imageSrc?: string +} + +export interface IProfileType { + label: string; + imageSrc?: string + cleanImageSrc?: string + cleanImageVerifiedSrc?: string + textLabel?: string +} +export interface IWorkspaceType { + label: WorkspaceType + imageSrc?: string + textLabel?: string + subText?: string +} + +export interface IMAchineBuilderXp { + label: MachineBuilderXpLabel +} + +export interface IOpeningHours { + day: string + openFrom: string + openTo: string +} + +/** + * PP users can have a bunch of custom meta fields depending on profile type + */ +export interface IUserPP extends IUser { + profileType: string; + workspaceType?: WorkspaceType | null + mapPinDescription?: string | null + openingHours?: IOpeningHours[] + collectedPlasticTypes?: PlasticTypeLabel[] | null + machineBuilderXp?: IMAchineBuilderXp[] | null + isExpert?: boolean | null + isV4Member?: boolean | null +} + +export type IUserPPDB = IUserPP; + + +/////////////////////////////////////////////////////////////////// +// +// OSR Specific Namespace + +export interface IGeoLocation { + lng: number; + lat: number; +} + +export interface IOA_UserDetail { + lastActive: Date; + profilePicUrl: string; + shortDescription: string; + heroImageUrl: string; + name: string; + profileUrl: string; +} + +export interface IGeo_Administrative { + name: string; + description: string; + isoName: string; + order: number; + adminLevel: number; + isoCode: string; + wikidataId: string; + geonameId: number; +} + +export interface IGeo_Informative { + name: string; + description: string; + order: number; + isoCode: string; + wikidataId: string; + geonameId: number; +} + +export interface IGeo_LocalityInfo { + administrative: IGeo_Administrative[]; + informative: IGeo_Informative[]; +} + +export interface IGeo { + latitude: number; + longitude: number; + continent: string; + lookupSource: string; + continentCode: string; + localityLanguageRequested: string; + city: string; + countryName: string; + postcode: string; + countryCode: string; + principalSubdivision: string; + principalSubdivisionCode: string; + plusCode: string; + locality: string; + localityInfo: IGeo_LocalityInfo; +} + +export interface IUrl { + name: string; + url: string; +} + +export interface IOA_Service { + welding: boolean; + assembling: boolean; + machining: boolean; + electronics: boolean; + molds: boolean; +} + +export interface IImage { + url: string; +} + +export interface IOSRUserData { + urls: IUrl[]; + description: string; + services: IOA_Service[]; + title: string; + images: IImage[]; + jsError?:boolean +} + +export interface I_OSR_USER { + _created: Date; + location: IGeoLocation; + _modified: Date; + _id: string; + detail: IOA_UserDetail; + type: string; + _deleted: boolean; + moderation: string; + geo: IGeo; + data: IOSRUserData; +} + +export interface I_USER_SHORT { + name: string; + email: string; + bazar: string; + web: string; + social: string; + censored: string; + lastActive: Date; + ig: string; +} + +export type IProduct = { + slug: string; + name: string; + category: string; + code: string; + forum?: string; + forumCategory?: string; + version?: string; + cart_id?: string; +}; + +export interface IDiscourseUser { + id: number + username: string + name: string + avatar_template: string + active: boolean + admin: boolean + moderator: boolean + last_seen_at: any + last_emailed_at: string + created_at: string + last_seen_age: any + last_emailed_age: number + created_at_age: number + trust_level: number + manual_locked_trust_level: any + flag_level: number + title: any + time_read: number + staged: boolean + days_visited: number + posts_read_count: number + topics_entered: number + post_count: number + + } + + export * from './osr/component.js' + export * from './types_kbot.js' + + \ No newline at end of file diff --git a/packages/commons/src/types_cache.ts b/packages/commons/src/types_cache.ts new file mode 100644 index 00000000..5b086380 --- /dev/null +++ b/packages/commons/src/types_cache.ts @@ -0,0 +1,6 @@ +export interface IOptionsCache { + skip?: boolean + clear?: boolean + namespace?: string + cacheRoot?: string +} diff --git a/packages/commons/src/types_common.ts b/packages/commons/src/types_common.ts new file mode 100644 index 00000000..4e093a3b --- /dev/null +++ b/packages/commons/src/types_common.ts @@ -0,0 +1,129 @@ +export interface GeoPos { + lon: number + lat: number +} + +export interface PATH_INFO { + DIR?: string + NAME?: string + FILE_NAME?: string + FILE_EXT?: string + PATH?: string + IS_FILE?: boolean + IS_FOLDER?: boolean + IS_EXPRESSION?: boolean + IS_GLOB?: boolean + path: string + GLOB: string + GLOB_EXTENSIONS: string[] + FILES: string[] +} + +export interface IDeeplConfig { + auth_key: string + free_api: boolean +} + +export interface IIgConfig { + username: string + password: string +} + + +export interface ICsCartConfigMySQL { + host: string + user: string + database: string + password: string +} +export interface ICsCartConfig { + token: string + url: string + username: string + + siteUrl?: string + timeout?: number + language?: string + userToken?: string + + mysql?: ICsCartConfigMySQL +} +export interface IGiteaConfig { + token: string + url: string +} +export interface IDiscourseConfig { + host: string + key: string + username: string + rateLimitConcurrency: number +} + +export interface IScaleserp { + key: string +} + +export interface IOSRConfig { + deepl: IDeeplConfig + ig: IIgConfig + cscart: ICsCartConfig + discourse: IDiscourseConfig + discourse_admin: IDiscourseConfig + instagram: IIgConfig + urls: any + scaleserp?: IScaleserp + gitea?: IGiteaConfig +} + +export interface SRC_VARIABLES { + SRC_PATH: string + SRC_DIR: string + SRC_NAME: string + SRC_FILE_NAME: string + SRC_FILE_EXT: string + SRC_IS_FILE: boolean + SRC_IS_FOLDER: boolean + SRC_IS_EXPRESSION: boolean + SRC_IS_GLOB: boolean + SRC_GLOB: string + SRC_GLOB_EXTENSIONS: string[] + SRC_FILES: string[] +} + +export interface DST_VARIABLES { + DST_PATH: string + DST_DIR: string + DST_NAME: string + DST_FILE_NAME: string + DST_FILE_EXT: string + DST_IS_FILE: boolean + DST_IS_FOLDER: boolean + DST_IS_EXPRESSION: boolean + DST_IS_GLOB: boolean + DST_GLOB: string + DST_GLOB_EXTENSIONS: string[] + DST_FILES: string[] +} + +export type PATH_VARIABLES = SRC_VARIABLES & DST_VARIABLES + +export interface IOptionsBase { + variables: PATH_VARIABLES +} + +export interface PATH_INFO { + DIR?: string + FILE_EXT?: string + FILE_NAME?: string + FILES: string[] + GLOB_EXTENSIONS: string[] + GLOB: string + IS_EXPRESSION?: boolean + IS_FILE?: boolean + IS_FOLDER?: boolean + IS_GLOB?: boolean + NAME?: string + path: string + PATH?: string +} + diff --git a/packages/commons/src/types_gui.ts b/packages/commons/src/types_gui.ts new file mode 100644 index 00000000..40f271b8 --- /dev/null +++ b/packages/commons/src/types_gui.ts @@ -0,0 +1,304 @@ +/** + * Flags to describe a block's execution behavior. + * + * @enum {integer} module=xide/types/RUN_FLAGS + * @memberOf module=xide/types + */ +export enum RUN_FLAGS { + /** + * The block can execute child blocks. + * @constant + * @type int + */ + CHILDREN = 0x00000020, + /** + * Block is waiting for a message => EXECUTION_STATE==RUNNING + * @constant + * @type int + */ + WAIT = 0x000008000 +}; + +/** + * Flags to describe a block's execution state. + * + * @enum {integer} module=xide/types/EXECUTION_STATE + * @memberOf module=xide/types + */ +export enum EXECUTION_STATE { + /** + * The block is doing nothing and also has done nothing. The is the default state + * @constant + * @type int + */ + NONE = 0x00000000, + /** + * The block is running. + * @constant + * @type int + */ + RUNNING = 0x00000001, + /** + * The block is an error state. + * @constant + * @type int + */ + ERROR = 0x00000002, + /** + * The block is in an paused state. + * @constant + * @type int + */ + PAUSED = 0x00000004, + /** + * The block is an finished state, ready to be cleared to "NONE" at the next frame. + * @constant + * @type int + */ + FINISH = 0x00000008, + /** + * The block is an stopped state, ready to be cleared to "NONE" at the next frame. + * @constant + * @type int + */ + STOPPED = 0x00000010, + /** + * The block has been launched once... + * @constant + * @type int + */ + ONCE = 0x80000000, + /** + * Block will be reseted next frame + * @constant + * @type int + */ + RESET_NEXT_FRAME = 0x00800000, + /** + * Block is locked and so no further inputs can be activated. + * @constant + * @type int + */ + LOCKED = 0x20000000 // Block is locked for utilisation in xblox +} + +export enum BLOCK_MODE { + NORMAL = 0, + UPDATE_WIDGET_PROPERTY = 1 +}; + +/** + * Flags to describe a block's belonging to a standard signal. + * @enum {integer} module=xblox/types/BLOCK_OUTLET + * @memberOf module=xblox/types + */ +export enum BLOCK_OUTLET { + NONE = 0x00000000, + PROGRESS = 0x00000001, + ERROR = 0x00000002, + PAUSED = 0x00000004, + FINISH = 0x00000008, + STOPPED = 0x00000010 +}; + +export enum EVENTS { + ON_RUN_BLOCK = 'onRunBlock', + ON_RUN_BLOCK_FAILED = 'onRunBlockFailed', + ON_RUN_BLOCK_SUCCESS = 'onRunBlockSuccess', + ON_BLOCK_SELECTED = 'onItemSelected', + ON_BLOCK_UNSELECTED = 'onBlockUnSelected', + ON_BLOCK_EXPRESSION_FAILED = 'onExpressionFailed', + ON_BUILD_BLOCK_INFO_LIST = 'onBuildBlockInfoList', + ON_BUILD_BLOCK_INFO_LIST_END = 'onBuildBlockInfoListEnd', + ON_BLOCK_PROPERTY_CHANGED = 'onBlockPropertyChanged', + ON_SCOPE_CREATED = 'onScopeCreated', + ON_VARIABLE_CHANGED = 'onVariableChanged', + ON_CREATE_VARIABLE_CI = 'onCreateVariableCI' +} + +export enum BlockType { + AssignmentExpression = 'AssignmentExpression', + ArrayExpression = 'ArrayExpression', + BlockStatement = 'BlockStatement', + BinaryExpression = 'BinaryExpression', + BreakStatement = 'BreakStatement', + CallExpression = 'CallExpression', + CatchClause = 'CatchClause', + ConditionalExpression = 'ConditionalExpression', + ContinueStatement = 'ContinueStatement', + DoWhileStatement = 'DoWhileStatement', + DebuggerStatement = 'DebuggerStatement', + EmptyStatement = 'EmptyStatement', + ExpressionStatement = 'ExpressionStatement', + ForStatement = 'ForStatement', + ForInStatement = 'ForInStatement', + FunctionDeclaration = 'FunctionDeclaration', + FunctionExpression = 'FunctionExpression', + Identifier = 'Identifier', + IfStatement = 'IfStatement', + Literal = 'Literal', + LabeledStatement = 'LabeledStatement', + LogicalExpression = 'LogicalExpression', + MemberExpression = 'MemberExpression', + NewExpression = 'NewExpression', + ObjectExpression = 'ObjectExpression', + Program = 'Program', + Property = 'Property', + ReturnStatement = 'ReturnStatement', + SequenceExpression = 'SequenceExpression', + SwitchStatement = 'SwitchStatement', + SwitchCase = 'SwitchCase', + ThisExpression = 'ThisExpression', + ThrowStatement = 'ThrowStatement', + TryStatement = 'TryStatement', + UnaryExpression = 'UnaryExpression', + UpdateExpression = 'UpdateExpression', + VariableDeclaration = 'VariableDeclaration', + VariableDeclarator = 'VariableDeclarator', + WhileStatement = 'WhileStatement', + WithStatement = 'WithStatement' +}; +/** + * Variable Flags + * + * @enum {int} VARIABLE_FLAGS + * @global + */ +export enum VARIABLE_FLAGS { + PUBLISH = 0x00000002, + PUBLISH_IF_SERVER = 0x00000004 +}; + +export enum BLOCK_GROUPS { + VARIABLE = 'DriverVariable', + BASIC_COMMAND = 'DriverBasicCommand', + CONDITIONAL_COMMAND = 'DriverConditionalCommand', + RESPONSE_VARIABLE = 'DriverResponseVariable', + RESPONSE_BLOCKS = 'conditionalProcess', + RESPONSE_VARIABLES = 'processVariables', + BASIC_VARIABLES = 'basicVariables' +}; + +export enum COMMAND_TYPES { + BASIC_COMMAND = 'basic', + CONDITIONAL_COMMAND = 'conditional', + INIT_COMMAND = 'init' +}; + +export enum CIFLAG { + /** + * Instruct for no additional extra processing + * @constant + * @type int + */ + NONE = 0x00000000, + /** + * Will instruct the pre/post processor to base-64 decode or encode + * @constant + * @type int + */ + BASE_64 = 0x00000001, + /** + * Post/Pre process the value with a user function + * @constant + * @type int + */ + USE_FUNCTION = 0x00000002, + /** + * Replace variables with local scope's variables during the post/pre process + * @constant + * @type int + */ + REPLACE_VARIABLES = 0x00000004, + /** + * Replace variables with local scope's variables during the post/pre process but evaluate the whole string + * as Javascript + * @constant + * @type int + */ + REPLACE_VARIABLES_EVALUATED = 0x00000008, + /** + * Will instruct the pre/post processor to escpape evaluated or replaced variables or expressions + * @constant + * @type int + */ + ESCAPE = 0x00000010, + /** + * Will instruct the pre/post processor to replace block calls with oridinary vanilla script + * @constant + * @type int + */ + REPLACE_BLOCK_CALLS = 0x00000020, + /** + * Will instruct the pre/post processor to remove variable delimitters/placeholders from the final string + * @constant + * @type int + */ + REMOVE_DELIMTTERS = 0x00000040, + /** + * Will instruct the pre/post processor to remove "[" ,"]" , "(" , ")" , "{", "}" , "*" , "+" , "." + * @constant + * @type int + */ + ESCAPE_SPECIAL_CHARS = 0x00000080, + /** + * Will instruct the pre/post processor to use regular expressions over string substitution + * @constant + * @type int + */ + USE_REGEX = 0x00000100, + /** + * Will instruct the pre/post processor to use Filtrex (custom bison parser, needs xexpression) over string substitution + * @constant + * @type int + */ + USE_FILTREX = 0x00000200, + /** + * Cascade entry. There are cases where #USE_FUNCTION is not enough or we'd like to avoid further type checking. + * @constant + * @type int + */ + CASCADE = 0x00000400, + /** + * Cascade entry. There are cases where #USE_FUNCTION is not enough or we'd like to avoid further type checking. + * @constant + * @type int + */ + EXPRESSION = 0x00000800, + /** + * Dont parse anything + * @constant + * @type int + */ + DONT_PARSE = 0x000001000, + /** + * Convert to hex + * @constant + * @type int + */ + TO_HEX = 0x000002000, + /** + * Convert to hex + * @constant + * @type int + */ + REPLACE_HEX = 0x000004000, + /** + * Wait for finish + * @constant + * @type int + */ + WAIT = 0x000008000, + /** + * Wait for finish + * @constant + * @type int + */ + DONT_ESCAPE = 0x000010000, + /** + * Flag to mark the maximum core bit mask, after here its user land + * @constant + * @type int + */ + END = 0x000020000 +} diff --git a/packages/commons/src/types_kbot.ts b/packages/commons/src/types_kbot.ts new file mode 100644 index 00000000..ea5afe36 --- /dev/null +++ b/packages/commons/src/types_kbot.ts @@ -0,0 +1,192 @@ +export interface IKBotOptions { + /** Path to the project directory */ + path?: string; + /** Description of the modifications to make to the project. Supports file paths. */ + query?: string; + /** Optional output path for modified files */ + output?: string | undefined; + /** Optional destination path for the result, will substitute ${MODEL} and ${ROUTER} in the path */ + dst?: string | undefined; + /** Template (typescript) or path to use for processing, see https://git.polymech.io/polymech/ai-template-typescript */ + template?: (("typescript") | string) | undefined; + /** Template root directory. When specified, templates are loaded with a prefix, eg: ${POLYMECH-ROOT}/ai-template-${options.template} */ + templateRoot?: string; + /** List of template parts to disable. Addionally, tools categories can be disabled, eg: --disable=fs,git,interact,terminal,search,web,email,user */ + disable?: string[]; + /** List of specific tools to disable */ + disableTools?: string[]; + /** Glob patterns to match files for processing, comma separated, eg: src/*.tsx,src/*.ts */ + glob?: string[] | undefined; + /** AI model to use for processing. Available models: +  +  OpenRouter models: +  + google/gemini-pro-1.5-exp | paid + meta-llama/llama-3.2-11b-vision-instruct:free | free + google/gemini-flash-1.5-exp | paid + google/gemini-flash-1.5-8b-exp | paid + microsoft/phi-3-medium-128k-instruct:free | free + microsoft/phi-3-mini-128k-instruct:free | free + google/gemini-2.0-flash-thinking-exp:free | free + google/gemini-2.0-flash-exp:free | free + meta-llama/llama-3.2-1b-instruct | paid + meta-llama/llama-3.2-3b-instruct | paid + meta-llama/llama-3.1-8b-instruct | paid + mistralai/mistral-7b-instruct | paid + mistralai/mistral-7b-instruct-v0.3 | paid + meta-llama/llama-3-8b-instruct | paid + amazon/nova-micro-v1 | paid + google/gemini-flash-1.5-8b | paid + mistralai/ministral-3b | paid + meta-llama/llama-3.2-11b-vision-instruct | paid + amazon/nova-lite-v1 | paid + google/gemini-flash-1.5 | paid + mistralai/ministral-8b | paid + microsoft/phi-3-mini-128k-instruct | paid + microsoft/phi-3.5-mini-128k-instruct | paid + meta-llama/llama-3.1-70b-instruct | paid + nvidia/llama-3.1-nemotron-70b-instruct | paid + deepseek/deepseek-chat | paid + cohere/command-r-08-2024 | paid + mistralai/mistral-nemo | paid + mistralai/pixtral-12b | paid + openai/gpt-4o-mini | paid + openai/gpt-4o-mini-2024-07-18 | paid + mistralai/mistral-7b-instruct-v0.1 | paid + ai21/jamba-1-5-mini | paid + mistralai/mistral-small | paid + qwen/qwen-2.5-72b-instruct | paid + meta-llama/llama-3-70b-instruct | paid + mistralai/mixtral-8x7b-instruct | paid + mistralai/mistral-tiny | paid + mistralai/codestral-mamba | paid + anthropic/claude-3-haiku:beta | paid + anthropic/claude-3-haiku | paid + nousresearch/hermes-3-llama-3.1-70b | paid + cohere/command-r-03-2024 | paid + cohere/command-r | paid + openai/gpt-3.5-turbo-0125 | paid + google/gemini-pro | paid + openai/gpt-3.5-turbo | paid + mistralai/mixtral-8x7b-instruct:nitro | paid + meta-llama/llama-3.1-405b-instruct | paid + amazon/nova-pro-v1 | paid + anthropic/claude-3.5-haiku:beta | paid + anthropic/claude-3.5-haiku | paid + anthropic/claude-3.5-haiku-20241022:beta | paid + anthropic/claude-3.5-haiku-20241022 | paid + microsoft/phi-3-medium-128k-instruct | paid + openai/gpt-3.5-turbo-1106 | paid + openai/gpt-3.5-turbo-0613 | paid + meta-llama/llama-3.2-90b-vision-instruct | paid + google/gemini-pro-1.5 | paid + mistralai/mixtral-8x22b-instruct | paid + mistralai/mistral-large | paid + mistralai/mistral-large-2407 | paid + mistralai/mistral-large-2411 | paid + mistralai/pixtral-large-2411 | paid + ai21/jamba-1-5-large | paid + x-ai/grok-2-1212 | paid + cohere/command-r-plus-08-2024 | paid + openai/gpt-4o | paid + openai/gpt-4o-2024-08-06 | paid + openai/gpt-4o-2024-11-20 | paid + mistralai/mistral-medium | paid + cohere/command-r-plus | paid + cohere/command-r-plus-04-2024 | paid + openai/gpt-3.5-turbo-16k | paid + anthropic/claude-3.5-sonnet:beta | paid + anthropic/claude-3.5-sonnet | paid + anthropic/claude-3-sonnet:beta | paid + anthropic/claude-3-sonnet | paid + anthropic/claude-3.5-sonnet-20240620:beta | paid + anthropic/claude-3.5-sonnet-20240620 | paid + openai/gpt-4o-2024-05-13 | paid + x-ai/grok-beta | paid + x-ai/grok-vision-beta | paid + openai/gpt-4o:extended | paid + openai/gpt-4-turbo | paid + openai/gpt-4-1106-preview | paid + openai/gpt-4-turbo-preview | paid + openai/o1 | paid + anthropic/claude-3-opus:beta | paid + anthropic/claude-3-opus | paid + openai/gpt-4 | paid + openai/gpt-4-0314 | paid + openai/gpt-4-32k-0314 | paid + openai/gpt-4-32k | paid +  +  OpenAI models: +  + gpt-4o-audio-preview-2024-10-01 + gpt-4o-realtime-preview + gpt-4o-realtime-preview-2024-10-01 + o1-mini-2024-09-12 + dall-e-2 + gpt-4-turbo + gpt-4-1106-preview + gpt-3.5-turbo + gpt-3.5-turbo-0125 + gpt-3.5-turbo-instruct + gpt-4-1106-vision-preview + babbage-002 + davinci-002 + whisper-1 + dall-e-3 + gpt-4o-mini-2024-07-18 + text-embedding-3-small + gpt-4o-mini + gpt-3.5-turbo-16k + gpt-4-0125-preview + gpt-4-turbo-preview + omni-moderation-latest + gpt-4o-2024-05-13 + omni-moderation-2024-09-26 + tts-1-hd-1106 + chatgpt-4o-latest + gpt-4 + gpt-4-0613 + o1-mini + o1-preview + o1-preview-2024-09-12 + tts-1-hd + gpt-4-vision-preview + text-embedding-ada-002 + gpt-3.5-turbo-1106 + gpt-4o-audio-preview + tts-1 + tts-1-1106 + gpt-3.5-turbo-instruct-0914 + text-embedding-3-large + gpt-4o-realtime-preview-2024-12-17 + gpt-4o-mini-realtime-preview + gpt-4o-mini-realtime-preview-2024-12-17 + gpt-4o-2024-11-20 + gpt-4o-audio-preview-2024-12-17 + gpt-4o-mini-audio-preview + gpt-4o-2024-08-06 + gpt-4o-mini-audio-preview-2024-12-17 + gpt-4o + gpt-4-turbo-2024-04-09 + ----- + */ + model?: string; + /** Router to use: openai or openrouter */ + router?: string; + /** Chat completion type - completion (without tools) or tools (with function calling) */ + type?: "completion" | "tools"; + /** Logging level for the application */ + logLevel?: unknown; + /** Profile for constants */ + profile?: string; + /** Environment (in profile) */ + env?: string; + /** Configuration as JSON string or path to JSON file, eg: {"openrouter":{"key":"your-key"}} or path/to/config.json */ + config?: string | undefined; + /** Write out as script */ + dump?: string | undefined; + /** Path to preferences file */ + preferences?: string; + /** Logging directory */ + logs?: string; +} \ No newline at end of file diff --git a/packages/commons/src/uri.ts b/packages/commons/src/uri.ts new file mode 100644 index 00000000..324e29b6 --- /dev/null +++ b/packages/commons/src/uri.ts @@ -0,0 +1,36 @@ +import { URL } from 'url' +import * as path from 'path' + +const filenamify = require('filenamify') +const _sanitize = require("sanitize-filename") + +const sanitize_ex = (f) => { + let str: string = filenamify(_sanitize(f)).replace(/[^\x00-\x7F]/g, "").replace('_', ''); + return str; +} + +export interface IDownloadUrl{ + urlParts: URL + pathParts: path.ParsedPath + filename: string + path:string + url: string +} + +export const parseForDownload = (url: string, dst: string) : IDownloadUrl => { + + const parsed = new URL(url); + const parts = path.parse(parsed.pathname) + + const filename = sanitize_ex(decodeURI(parts.base)) + const downloadPath = path.resolve(`${dst}/${filename}`) + const downloadUrl = parsed.origin + parsed.pathname + + return { + urlParts:parsed, + pathParts: parts, + filename: filename, + path: downloadPath, + url: downloadUrl + } +} \ No newline at end of file diff --git a/packages/commons/src/variables.ts b/packages/commons/src/variables.ts new file mode 100644 index 00000000..990ef117 --- /dev/null +++ b/packages/commons/src/variables.ts @@ -0,0 +1,40 @@ +import { REGEX_VAR, REGEX_VAR_ALT } from "@polymech/core/constants.js" +import { DEFAULT_ROOTS } from '@/config.js' + +export const DATE_VARS = () => { + return { + YYYY: new Date(Date.now()).getFullYear(), + MM: new Date(Date.now()).getMonth() + 1, + DD: new Date(Date.now()).getDate(), + HH: new Date(Date.now()).getHours(), + SS: new Date(Date.now()).getSeconds() + } +} + +export const _substitute = (template, map: Record, keep: boolean = true, alt: boolean = false) => { + const transform = (k) => k || '' + return template.replace(alt ? REGEX_VAR_ALT : REGEX_VAR, (match, key, format) => { + if (map[key]) { + return transform(map[key]).toString() + } else if (map[key.replace(/-/g, '_')]) { + return transform(map[key.replace(/-/g, '_')]).toString() + } else if (keep) { + return "${" + key + "}" + } else { + return "" + } + }) +} +export const substitute = (alt: boolean, template: string, vars: Record = {}, keep: boolean = true) => alt ? _substitute(template, vars, keep, alt) : _substitute(template, vars, keep, alt) +export const DEFAULT_VARS = (vars: any) => { + return { + ...DEFAULT_ROOTS, + ...DATE_VARS(), + ...vars + } +} +export const resolveVariables = (_path: string, alt: boolean = false, vars: Record = {}) => + substitute(alt, _path, DEFAULT_VARS(vars)) + +export const resolve = (_path: string, alt: boolean = false, vars: Record = {}) => + resolveVariables(_path, alt, vars) diff --git a/packages/commons/tsconfig.json b/packages/commons/tsconfig.json index fdf8e607..f50dae7c 100644 --- a/packages/commons/tsconfig.json +++ b/packages/commons/tsconfig.json @@ -4,10 +4,14 @@ "files": ["src/index.ts"], "compilerOptions": { "allowJs": true, + "baseUrl": ".", "declarationDir": "./dist", "outDir": "./dist", - "sourceMap": true, + "sourceMap": true, + "preserveConstEnums": true, + "paths": { + "@/*": ["src/*"] + } - "preserveConstEnums": true }, } diff --git a/packages/core/dist/arrays.d.ts b/packages/core/dist/arrays.d.ts new file mode 100644 index 00000000..6255ee48 --- /dev/null +++ b/packages/core/dist/arrays.d.ts @@ -0,0 +1,287 @@ +import { CancellationToken } from './cancellation.js'; +import { ISplice } from './sequence.js'; +/** + * Returns the last element of an array. + * @param array The array. + * @param n Which element from the end (default is zero). + */ +export declare function tail(array: ArrayLike, n?: number): T | undefined; +export declare function tail2(arr: T[]): [T[], T]; +export declare function equals(one: ReadonlyArray | undefined, other: ReadonlyArray | undefined, itemEquals?: (a: T, b: T) => boolean): boolean; +/** + * Remove the element at `index` by replacing it with the last element. This is faster than `splice` + * but changes the order of the array + */ +export declare function removeFastWithoutKeepingOrder(array: T[], index: number): void; +/** + * Performs a binary search algorithm over a sorted array. + * + * @param array The array being searched. + * @param key The value we search for. + * @param comparator A function that takes two array elements and returns zero + * if they are equal, a negative number if the first element precedes the + * second one in the sorting order, or a positive number if the second element + * precedes the first one. + * @return See {@link binarySearch2} + */ +export declare function binarySearch(array: ReadonlyArray, key: T, comparator: (op1: T, op2: T) => number): number; +/** + * Performs a binary search algorithm over a sorted collection. Useful for cases + * when we need to perform a binary search over something that isn't actually an + * array, and converting data to an array would defeat the use of binary search + * in the first place. + * + * @param length The collection length. + * @param compareToKey A function that takes an index of an element in the + * collection and returns zero if the value at this index is equal to the + * search key, a negative number if the value precedes the search key in the + * sorting order, or a positive number if the search key precedes the value. + * @return A non-negative index of an element, if found. If not found, the + * result is -(n+1) (or ~n, using bitwise notation), where n is the index + * where the key should be inserted to maintain the sorting order. + */ +export declare function binarySearch2(length: number, compareToKey: (index: number) => number): number; +type Compare = (a: T, b: T) => number; +export declare function quickSelect(nth: number, data: T[], compare: Compare): T; +export declare function groupBy(data: ReadonlyArray, compare: (a: T, b: T) => number): T[][]; +/** + * Splits the given items into a list of (non-empty) groups. + * `shouldBeGrouped` is used to decide if two consecutive items should be in the same group. + * The order of the items is preserved. + */ +export declare function groupAdjacentBy(items: Iterable, shouldBeGrouped: (item1: T, item2: T) => boolean): Iterable; +export declare function forEachAdjacent(arr: T[], f: (item1: T | undefined, item2: T | undefined) => void): void; +export declare function forEachWithNeighbors(arr: T[], f: (before: T | undefined, element: T, after: T | undefined) => void): void; +/** + * Diffs two *sorted* arrays and computes the splices which apply the diff. + */ +export declare function sortedDiff(before: ReadonlyArray, after: ReadonlyArray, compare: (a: T, b: T) => number): ISplice[]; +/** + * Takes two *sorted* arrays and computes their delta (removed, added elements). + * Finishes in `Math.min(before.length, after.length)` steps. + */ +export declare function delta(before: ReadonlyArray, after: ReadonlyArray, compare: (a: T, b: T) => number): { + removed: T[]; + added: T[]; +}; +/** + * Returns the top N elements from the array. + * + * Faster than sorting the entire array when the array is a lot larger than N. + * + * @param array The unsorted array. + * @param compare A sort function for the elements. + * @param n The number of elements to return. + * @return The first n elements from array when sorted with compare. + */ +export declare function top(array: ReadonlyArray, compare: (a: T, b: T) => number, n: number): T[]; +/** + * Asynchronous variant of `top()` allowing for splitting up work in batches between which the event loop can run. + * + * Returns the top N elements from the array. + * + * Faster than sorting the entire array when the array is a lot larger than N. + * + * @param array The unsorted array. + * @param compare A sort function for the elements. + * @param n The number of elements to return. + * @param batch The number of elements to examine before yielding to the event loop. + * @return The first n elements from array when sorted with compare. + */ +export declare function topAsync(array: T[], compare: (a: T, b: T) => number, n: number, batch: number, token?: CancellationToken): Promise; +/** + * @returns New array with all falsy values removed. The original array IS NOT modified. + */ +export declare function coalesce(array: ReadonlyArray): T[]; +/** + * Remove all falsy values from `array`. The original array IS modified. + */ +export declare function coalesceInPlace(array: Array): asserts array is Array; +/** + * @deprecated Use `Array.copyWithin` instead + */ +export declare function move(array: unknown[], from: number, to: number): void; +/** + * @returns false if the provided object is an array and not empty. + */ +export declare function isFalsyOrEmpty(obj: any): boolean; +/** + * @returns True if the provided object is an array and has at least one element. + */ +export declare function isNonEmptyArray(obj: T[] | undefined | null): obj is T[]; +export declare function isNonEmptyArray(obj: readonly T[] | undefined | null): obj is readonly T[]; +/** + * Removes duplicates from the given array. The optional keyFn allows to specify + * how elements are checked for equality by returning an alternate value for each. + */ +export declare function distinct(array: ReadonlyArray, keyFn?: (value: T) => unknown): T[]; +export declare function uniqueFilter(keyFn: (t: T) => R): (t: T) => boolean; +export declare function commonPrefixLength(one: ReadonlyArray, other: ReadonlyArray, equals?: (a: T, b: T) => boolean): number; +export declare function range(to: number): number[]; +export declare function range(from: number, to: number): number[]; +export declare function index(array: ReadonlyArray, indexer: (t: T) => string): { + [key: string]: T; +}; +export declare function index(array: ReadonlyArray, indexer: (t: T) => string, mapper: (t: T) => R): { + [key: string]: R; +}; +/** + * Inserts an element into an array. Returns a function which, when + * called, will remove that element from the array. + * + * @deprecated In almost all cases, use a `Set` instead. + */ +export declare function insert(array: T[], element: T): () => void; +/** + * Removes an element from an array if it can be found. + * + * @deprecated In almost all cases, use a `Set` instead. + */ +export declare function remove(array: T[], element: T): T | undefined; +/** + * Insert `insertArr` inside `target` at `insertIndex`. + * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array + */ +export declare function arrayInsert(target: T[], insertIndex: number, insertArr: T[]): T[]; +/** + * Uses Fisher-Yates shuffle to shuffle the given array + */ +export declare function shuffle(array: T[], _seed?: number): void; +/** + * Pushes an element to the start of the array, if found. + */ +export declare function pushToStart(arr: T[], value: T): void; +/** + * Pushes an element to the end of the array, if found. + */ +export declare function pushToEnd(arr: T[], value: T): void; +export declare function pushMany(arr: T[], items: ReadonlyArray): void; +export declare function mapArrayOrNot(items: T | T[], fn: (_: T) => U): U | U[]; +export declare function asArray(x: T | T[]): T[]; +export declare function asArray(x: T | readonly T[]): readonly T[]; +export declare function getRandomElement(arr: T[]): T | undefined; +/** + * Insert the new items in the array. + * @param array The original array. + * @param start The zero-based location in the array from which to start inserting elements. + * @param newItems The items to be inserted + */ +export declare function insertInto(array: T[], start: number, newItems: T[]): void; +/** + * Removes elements from an array and inserts new elements in their place, returning the deleted elements. Alternative to the native Array.splice method, it + * can only support limited number of items due to the maximum call stack size limit. + * @param array The original array. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @returns An array containing the elements that were deleted. + */ +export declare function splice(array: T[], start: number, deleteCount: number, newItems: T[]): T[]; +/** + * When comparing two values, + * a negative number indicates that the first value is less than the second, + * a positive number indicates that the first value is greater than the second, + * and zero indicates that neither is the case. +*/ +export type CompareResult = number; +export declare namespace CompareResult { + function isLessThan(result: CompareResult): boolean; + function isLessThanOrEqual(result: CompareResult): boolean; + function isGreaterThan(result: CompareResult): boolean; + function isNeitherLessOrGreaterThan(result: CompareResult): boolean; + const greaterThan = 1; + const lessThan = -1; + const neitherLessOrGreaterThan = 0; +} +/** + * A comparator `c` defines a total order `<=` on `T` as following: + * `c(a, b) <= 0` iff `a` <= `b`. + * We also have `c(a, b) == 0` iff `c(b, a) == 0`. +*/ +export type Comparator = (a: T, b: T) => CompareResult; +export declare function compareBy(selector: (item: TItem) => TCompareBy, comparator: Comparator): Comparator; +export declare function tieBreakComparators(...comparators: Comparator[]): Comparator; +/** + * The natural order on numbers. +*/ +export declare const numberComparator: Comparator; +export declare const booleanComparator: Comparator; +export declare function reverseOrder(comparator: Comparator): Comparator; +export declare class ArrayQueue { + private firstIdx; + private items; + private lastIdx; + /** + * Constructs a queue that is backed by the given array. Runtime is O(1). + */ + constructor(); + get length(): number; + /** + * Consumes elements from the beginning of the queue as long as the predicate returns true. + * If no elements were consumed, `null` is returned. Has a runtime of O(result.length). + */ + takeWhile(predicate: (value: T) => boolean): T[] | null; + /** + * Consumes elements from the end of the queue as long as the predicate returns true. + * If no elements were consumed, `null` is returned. + * The result has the same order as the underlying array! + */ + takeFromEndWhile(predicate: (value: T) => boolean): T[] | null; + peek(): T | undefined; + peekLast(): T | undefined; + dequeue(): T | undefined; + removeLast(): T | undefined; + takeCount(count: number): T[]; +} +/** + * This class is faster than an iterator and array for lazy computed data. +*/ +export declare class CallbackIterable { + /** + * Calls the callback for every item. + * Stops when the callback returns false. + */ + readonly iterate: (callback: (item: T) => boolean) => void; + static readonly empty: CallbackIterable; + constructor( + /** + * Calls the callback for every item. + * Stops when the callback returns false. + */ + iterate: (callback: (item: T) => boolean) => void); + forEach(handler: (item: T) => void): void; + toArray(): T[]; + filter(predicate: (item: T) => boolean): CallbackIterable; + map(mapFn: (item: T) => TResult): CallbackIterable; + some(predicate: (item: T) => boolean): boolean; + findFirst(predicate: (item: T) => boolean): T | undefined; + findLast(predicate: (item: T) => boolean): T | undefined; + findLastMaxBy(comparator: Comparator): T | undefined; +} +/** + * Represents a re-arrangement of items in an array. + */ +export declare class Permutation { + private readonly _indexMap; + constructor(_indexMap: readonly number[]); + /** + * Returns a permutation that sorts the given array according to the given compare function. + */ + static createSortPermutation(arr: readonly T[], compareFn: (a: T, b: T) => number): Permutation; + /** + * Returns a new array with the elements of the given array re-arranged according to this permutation. + */ + apply(arr: readonly T[]): T[]; + /** + * Returns a new permutation that undoes the re-arrangement of this permutation. + */ + inverse(): Permutation; +} +/** + * Asynchronous variant of `Array.find()`, returning the first element in + * the array for which the predicate returns true. + * + * This implementation does not bail early and waits for all promises to + * resolve before returning. + */ +export declare function findAsync(array: readonly T[], predicate: (element: T, index: number) => Promise): Promise; +export {}; diff --git a/packages/core/dist/arrays.js b/packages/core/dist/arrays.js new file mode 100644 index 00000000..9ddba997 --- /dev/null +++ b/packages/core/dist/arrays.js @@ -0,0 +1,759 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { findFirstIdxMonotonousOrArrLen } from './arraysFind.js'; +import { CancellationError } from './errors.js'; +/** + * Returns the last element of an array. + * @param array The array. + * @param n Which element from the end (default is zero). + */ +export function tail(array, n = 0) { + return array[array.length - (1 + n)]; +} +export function tail2(arr) { + if (arr.length === 0) { + throw new Error('Invalid tail call'); + } + return [arr.slice(0, arr.length - 1), arr[arr.length - 1]]; +} +export function equals(one, other, itemEquals = (a, b) => a === b) { + if (one === other) { + return true; + } + if (!one || !other) { + return false; + } + if (one.length !== other.length) { + return false; + } + for (let i = 0, len = one.length; i < len; i++) { + if (!itemEquals(one[i], other[i])) { + return false; + } + } + return true; +} +/** + * Remove the element at `index` by replacing it with the last element. This is faster than `splice` + * but changes the order of the array + */ +export function removeFastWithoutKeepingOrder(array, index) { + const last = array.length - 1; + if (index < last) { + array[index] = array[last]; + } + array.pop(); +} +/** + * Performs a binary search algorithm over a sorted array. + * + * @param array The array being searched. + * @param key The value we search for. + * @param comparator A function that takes two array elements and returns zero + * if they are equal, a negative number if the first element precedes the + * second one in the sorting order, or a positive number if the second element + * precedes the first one. + * @return See {@link binarySearch2} + */ +export function binarySearch(array, key, comparator) { + return binarySearch2(array.length, i => comparator(array[i], key)); +} +/** + * Performs a binary search algorithm over a sorted collection. Useful for cases + * when we need to perform a binary search over something that isn't actually an + * array, and converting data to an array would defeat the use of binary search + * in the first place. + * + * @param length The collection length. + * @param compareToKey A function that takes an index of an element in the + * collection and returns zero if the value at this index is equal to the + * search key, a negative number if the value precedes the search key in the + * sorting order, or a positive number if the search key precedes the value. + * @return A non-negative index of an element, if found. If not found, the + * result is -(n+1) (or ~n, using bitwise notation), where n is the index + * where the key should be inserted to maintain the sorting order. + */ +export function binarySearch2(length, compareToKey) { + let low = 0, high = length - 1; + while (low <= high) { + const mid = ((low + high) / 2) | 0; + const comp = compareToKey(mid); + if (comp < 0) { + low = mid + 1; + } + else if (comp > 0) { + high = mid - 1; + } + else { + return mid; + } + } + return -(low + 1); +} +export function quickSelect(nth, data, compare) { + nth = nth | 0; + if (nth >= data.length) { + throw new TypeError('invalid index'); + } + const pivotValue = data[Math.floor(data.length * Math.random())]; + const lower = []; + const higher = []; + const pivots = []; + for (const value of data) { + const val = compare(value, pivotValue); + if (val < 0) { + lower.push(value); + } + else if (val > 0) { + higher.push(value); + } + else { + pivots.push(value); + } + } + if (nth < lower.length) { + return quickSelect(nth, lower, compare); + } + else if (nth < lower.length + pivots.length) { + return pivots[0]; + } + else { + return quickSelect(nth - (lower.length + pivots.length), higher, compare); + } +} +export function groupBy(data, compare) { + const result = []; + let currentGroup = undefined; + for (const element of data.slice(0).sort(compare)) { + if (!currentGroup || compare(currentGroup[0], element) !== 0) { + currentGroup = [element]; + result.push(currentGroup); + } + else { + currentGroup.push(element); + } + } + return result; +} +/** + * Splits the given items into a list of (non-empty) groups. + * `shouldBeGrouped` is used to decide if two consecutive items should be in the same group. + * The order of the items is preserved. + */ +export function* groupAdjacentBy(items, shouldBeGrouped) { + let currentGroup; + let last; + for (const item of items) { + if (last !== undefined && shouldBeGrouped(last, item)) { + currentGroup.push(item); + } + else { + if (currentGroup) { + yield currentGroup; + } + currentGroup = [item]; + } + last = item; + } + if (currentGroup) { + yield currentGroup; + } +} +export function forEachAdjacent(arr, f) { + for (let i = 0; i <= arr.length; i++) { + f(i === 0 ? undefined : arr[i - 1], i === arr.length ? undefined : arr[i]); + } +} +export function forEachWithNeighbors(arr, f) { + for (let i = 0; i < arr.length; i++) { + f(i === 0 ? undefined : arr[i - 1], arr[i], i + 1 === arr.length ? undefined : arr[i + 1]); + } +} +/** + * Diffs two *sorted* arrays and computes the splices which apply the diff. + */ +export function sortedDiff(before, after, compare) { + const result = []; + function pushSplice(start, deleteCount, toInsert) { + if (deleteCount === 0 && toInsert.length === 0) { + return; + } + const latest = result[result.length - 1]; + if (latest && latest.start + latest.deleteCount === start) { + latest.deleteCount += deleteCount; + latest.toInsert.push(...toInsert); + } + else { + result.push({ start, deleteCount, toInsert }); + } + } + let beforeIdx = 0; + let afterIdx = 0; + while (true) { + if (beforeIdx === before.length) { + pushSplice(beforeIdx, 0, after.slice(afterIdx)); + break; + } + if (afterIdx === after.length) { + pushSplice(beforeIdx, before.length - beforeIdx, []); + break; + } + const beforeElement = before[beforeIdx]; + const afterElement = after[afterIdx]; + const n = compare(beforeElement, afterElement); + if (n === 0) { + // equal + beforeIdx += 1; + afterIdx += 1; + } + else if (n < 0) { + // beforeElement is smaller -> before element removed + pushSplice(beforeIdx, 1, []); + beforeIdx += 1; + } + else if (n > 0) { + // beforeElement is greater -> after element added + pushSplice(beforeIdx, 0, [afterElement]); + afterIdx += 1; + } + } + return result; +} +/** + * Takes two *sorted* arrays and computes their delta (removed, added elements). + * Finishes in `Math.min(before.length, after.length)` steps. + */ +export function delta(before, after, compare) { + const splices = sortedDiff(before, after, compare); + const removed = []; + const added = []; + for (const splice of splices) { + removed.push(...before.slice(splice.start, splice.start + splice.deleteCount)); + added.push(...splice.toInsert); + } + return { removed, added }; +} +/** + * Returns the top N elements from the array. + * + * Faster than sorting the entire array when the array is a lot larger than N. + * + * @param array The unsorted array. + * @param compare A sort function for the elements. + * @param n The number of elements to return. + * @return The first n elements from array when sorted with compare. + */ +export function top(array, compare, n) { + if (n === 0) { + return []; + } + const result = array.slice(0, n).sort(compare); + topStep(array, compare, result, n, array.length); + return result; +} +/** + * Asynchronous variant of `top()` allowing for splitting up work in batches between which the event loop can run. + * + * Returns the top N elements from the array. + * + * Faster than sorting the entire array when the array is a lot larger than N. + * + * @param array The unsorted array. + * @param compare A sort function for the elements. + * @param n The number of elements to return. + * @param batch The number of elements to examine before yielding to the event loop. + * @return The first n elements from array when sorted with compare. + */ +export function topAsync(array, compare, n, batch, token) { + if (n === 0) { + return Promise.resolve([]); + } + return new Promise((resolve, reject) => { + (async () => { + const o = array.length; + const result = array.slice(0, n).sort(compare); + for (let i = n, m = Math.min(n + batch, o); i < o; i = m, m = Math.min(m + batch, o)) { + if (i > n) { + await new Promise(resolve => setTimeout(resolve)); // any other delay function would starve I/O + } + if (token && token.isCancellationRequested) { + throw new CancellationError(); + } + topStep(array, compare, result, i, m); + } + return result; + })() + .then(resolve, reject); + }); +} +function topStep(array, compare, result, i, m) { + for (const n = result.length; i < m; i++) { + const element = array[i]; + if (compare(element, result[n - 1]) < 0) { + result.pop(); + const j = findFirstIdxMonotonousOrArrLen(result, e => compare(element, e) < 0); + result.splice(j, 0, element); + } + } +} +/** + * @returns New array with all falsy values removed. The original array IS NOT modified. + */ +export function coalesce(array) { + return array.filter((e) => !!e); +} +/** + * Remove all falsy values from `array`. The original array IS modified. + */ +export function coalesceInPlace(array) { + let to = 0; + for (let i = 0; i < array.length; i++) { + if (!!array[i]) { + array[to] = array[i]; + to += 1; + } + } + array.length = to; +} +/** + * @deprecated Use `Array.copyWithin` instead + */ +export function move(array, from, to) { + array.splice(to, 0, array.splice(from, 1)[0]); +} +/** + * @returns false if the provided object is an array and not empty. + */ +export function isFalsyOrEmpty(obj) { + return !Array.isArray(obj) || obj.length === 0; +} +export function isNonEmptyArray(obj) { + return Array.isArray(obj) && obj.length > 0; +} +/** + * Removes duplicates from the given array. The optional keyFn allows to specify + * how elements are checked for equality by returning an alternate value for each. + */ +export function distinct(array, keyFn = value => value) { + const seen = new Set(); + return array.filter(element => { + const key = keyFn(element); + if (seen.has(key)) { + return false; + } + seen.add(key); + return true; + }); +} +export function uniqueFilter(keyFn) { + const seen = new Set(); + return element => { + const key = keyFn(element); + if (seen.has(key)) { + return false; + } + seen.add(key); + return true; + }; +} +export function commonPrefixLength(one, other, equals = (a, b) => a === b) { + let result = 0; + for (let i = 0, len = Math.min(one.length, other.length); i < len && equals(one[i], other[i]); i++) { + result++; + } + return result; +} +export function range(arg, to) { + let from = typeof to === 'number' ? arg : 0; + if (typeof to === 'number') { + from = arg; + } + else { + from = 0; + to = arg; + } + const result = []; + if (from <= to) { + for (let i = from; i < to; i++) { + result.push(i); + } + } + else { + for (let i = from; i > to; i--) { + result.push(i); + } + } + return result; +} +export function index(array, indexer, mapper) { + return array.reduce((r, t) => { + r[indexer(t)] = mapper ? mapper(t) : t; + return r; + }, Object.create(null)); +} +/** + * Inserts an element into an array. Returns a function which, when + * called, will remove that element from the array. + * + * @deprecated In almost all cases, use a `Set` instead. + */ +export function insert(array, element) { + array.push(element); + return () => remove(array, element); +} +/** + * Removes an element from an array if it can be found. + * + * @deprecated In almost all cases, use a `Set` instead. + */ +export function remove(array, element) { + const index = array.indexOf(element); + if (index > -1) { + array.splice(index, 1); + return element; + } + return undefined; +} +/** + * Insert `insertArr` inside `target` at `insertIndex`. + * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array + */ +export function arrayInsert(target, insertIndex, insertArr) { + const before = target.slice(0, insertIndex); + const after = target.slice(insertIndex); + return before.concat(insertArr, after); +} +/** + * Uses Fisher-Yates shuffle to shuffle the given array + */ +export function shuffle(array, _seed) { + let rand; + if (typeof _seed === 'number') { + let seed = _seed; + // Seeded random number generator in JS. Modified from: + // https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript + rand = () => { + const x = Math.sin(seed++) * 179426549; // throw away most significant digits and reduce any potential bias + return x - Math.floor(x); + }; + } + else { + rand = Math.random; + } + for (let i = array.length - 1; i > 0; i -= 1) { + const j = Math.floor(rand() * (i + 1)); + const temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } +} +/** + * Pushes an element to the start of the array, if found. + */ +export function pushToStart(arr, value) { + const index = arr.indexOf(value); + if (index > -1) { + arr.splice(index, 1); + arr.unshift(value); + } +} +/** + * Pushes an element to the end of the array, if found. + */ +export function pushToEnd(arr, value) { + const index = arr.indexOf(value); + if (index > -1) { + arr.splice(index, 1); + arr.push(value); + } +} +export function pushMany(arr, items) { + for (const item of items) { + arr.push(item); + } +} +export function mapArrayOrNot(items, fn) { + return Array.isArray(items) ? + items.map(fn) : + fn(items); +} +export function asArray(x) { + return Array.isArray(x) ? x : [x]; +} +export function getRandomElement(arr) { + return arr[Math.floor(Math.random() * arr.length)]; +} +/** + * Insert the new items in the array. + * @param array The original array. + * @param start The zero-based location in the array from which to start inserting elements. + * @param newItems The items to be inserted + */ +export function insertInto(array, start, newItems) { + const startIdx = getActualStartIndex(array, start); + const originalLength = array.length; + const newItemsLength = newItems.length; + array.length = originalLength + newItemsLength; + // Move the items after the start index, start from the end so that we don't overwrite any value. + for (let i = originalLength - 1; i >= startIdx; i--) { + array[i + newItemsLength] = array[i]; + } + for (let i = 0; i < newItemsLength; i++) { + array[i + startIdx] = newItems[i]; + } +} +/** + * Removes elements from an array and inserts new elements in their place, returning the deleted elements. Alternative to the native Array.splice method, it + * can only support limited number of items due to the maximum call stack size limit. + * @param array The original array. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @returns An array containing the elements that were deleted. + */ +export function splice(array, start, deleteCount, newItems) { + const index = getActualStartIndex(array, start); + let result = array.splice(index, deleteCount); + if (result === undefined) { + // see https://bugs.webkit.org/show_bug.cgi?id=261140 + result = []; + } + insertInto(array, index, newItems); + return result; +} +/** + * Determine the actual start index (same logic as the native splice() or slice()) + * If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided. + * If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.) If array.length + start is less than 0, it will begin from index 0. + * @param array The target array. + * @param start The operation index. + */ +function getActualStartIndex(array, start) { + return start < 0 ? Math.max(start + array.length, 0) : Math.min(start, array.length); +} +export var CompareResult; +(function (CompareResult) { + function isLessThan(result) { + return result < 0; + } + CompareResult.isLessThan = isLessThan; + function isLessThanOrEqual(result) { + return result <= 0; + } + CompareResult.isLessThanOrEqual = isLessThanOrEqual; + function isGreaterThan(result) { + return result > 0; + } + CompareResult.isGreaterThan = isGreaterThan; + function isNeitherLessOrGreaterThan(result) { + return result === 0; + } + CompareResult.isNeitherLessOrGreaterThan = isNeitherLessOrGreaterThan; + CompareResult.greaterThan = 1; + CompareResult.lessThan = -1; + CompareResult.neitherLessOrGreaterThan = 0; +})(CompareResult = CompareResult || (CompareResult = {})); +export function compareBy(selector, comparator) { + return (a, b) => comparator(selector(a), selector(b)); +} +export function tieBreakComparators(...comparators) { + return (item1, item2) => { + for (const comparator of comparators) { + const result = comparator(item1, item2); + if (!CompareResult.isNeitherLessOrGreaterThan(result)) { + return result; + } + } + return CompareResult.neitherLessOrGreaterThan; + }; +} +/** + * The natural order on numbers. +*/ +export const numberComparator = (a, b) => a - b; +export const booleanComparator = (a, b) => numberComparator(a ? 1 : 0, b ? 1 : 0); +export function reverseOrder(comparator) { + return (a, b) => -comparator(a, b); +} +export class ArrayQueue { + firstIdx = 0; + items = []; + lastIdx = this.items.length - 1; + /** + * Constructs a queue that is backed by the given array. Runtime is O(1). + */ + constructor() { } + get length() { + return this.lastIdx - this.firstIdx + 1; + } + /** + * Consumes elements from the beginning of the queue as long as the predicate returns true. + * If no elements were consumed, `null` is returned. Has a runtime of O(result.length). + */ + takeWhile(predicate) { + // P(k) := k <= this.lastIdx && predicate(this.items[k]) + // Find s := min { k | k >= this.firstIdx && !P(k) } and return this.data[this.firstIdx...s) + let startIdx = this.firstIdx; + while (startIdx < this.items.length && predicate(this.items[startIdx])) { + startIdx++; + } + const result = startIdx === this.firstIdx ? null : this.items.slice(this.firstIdx, startIdx); + this.firstIdx = startIdx; + return result; + } + /** + * Consumes elements from the end of the queue as long as the predicate returns true. + * If no elements were consumed, `null` is returned. + * The result has the same order as the underlying array! + */ + takeFromEndWhile(predicate) { + // P(k) := this.firstIdx >= k && predicate(this.items[k]) + // Find s := max { k | k <= this.lastIdx && !P(k) } and return this.data(s...this.lastIdx] + let endIdx = this.lastIdx; + while (endIdx >= 0 && predicate(this.items[endIdx])) { + endIdx--; + } + const result = endIdx === this.lastIdx ? null : this.items.slice(endIdx + 1, this.lastIdx + 1); + this.lastIdx = endIdx; + return result; + } + peek() { + if (this.length === 0) { + return undefined; + } + return this.items[this.firstIdx]; + } + peekLast() { + if (this.length === 0) { + return undefined; + } + return this.items[this.lastIdx]; + } + dequeue() { + const result = this.items[this.firstIdx]; + this.firstIdx++; + return result; + } + removeLast() { + const result = this.items[this.lastIdx]; + this.lastIdx--; + return result; + } + takeCount(count) { + const result = this.items.slice(this.firstIdx, this.firstIdx + count); + this.firstIdx += count; + return result; + } +} +/** + * This class is faster than an iterator and array for lazy computed data. +*/ +export class CallbackIterable { + iterate; + static empty = new CallbackIterable(_callback => { }); + constructor( + /** + * Calls the callback for every item. + * Stops when the callback returns false. + */ + iterate) { + this.iterate = iterate; + } + forEach(handler) { + this.iterate(item => { handler(item); return true; }); + } + toArray() { + const result = []; + this.iterate(item => { result.push(item); return true; }); + return result; + } + filter(predicate) { + return new CallbackIterable(cb => this.iterate(item => predicate(item) ? cb(item) : true)); + } + map(mapFn) { + return new CallbackIterable(cb => this.iterate(item => cb(mapFn(item)))); + } + some(predicate) { + let result = false; + this.iterate(item => { result = predicate(item); return !result; }); + return result; + } + findFirst(predicate) { + let result; + this.iterate(item => { + if (predicate(item)) { + result = item; + return false; + } + return true; + }); + return result; + } + findLast(predicate) { + let result; + this.iterate(item => { + if (predicate(item)) { + result = item; + } + return true; + }); + return result; + } + findLastMaxBy(comparator) { + let result; + let first = true; + this.iterate(item => { + if (first || CompareResult.isGreaterThan(comparator(item, result))) { + first = false; + result = item; + } + return true; + }); + return result; + } +} +/** + * Represents a re-arrangement of items in an array. + */ +export class Permutation { + _indexMap; + constructor(_indexMap) { + this._indexMap = _indexMap; + } + /** + * Returns a permutation that sorts the given array according to the given compare function. + */ + static createSortPermutation(arr, compareFn) { + const sortIndices = Array.from(arr.keys()).sort((index1, index2) => compareFn(arr[index1], arr[index2])); + return new Permutation(sortIndices); + } + /** + * Returns a new array with the elements of the given array re-arranged according to this permutation. + */ + apply(arr) { + return arr.map((_, index) => arr[this._indexMap[index]]); + } + /** + * Returns a new permutation that undoes the re-arrangement of this permutation. + */ + inverse() { + const inverseIndexMap = this._indexMap.slice(); + for (let i = 0; i < this._indexMap.length; i++) { + inverseIndexMap[this._indexMap[i]] = i; + } + return new Permutation(inverseIndexMap); + } +} +/** + * Asynchronous variant of `Array.find()`, returning the first element in + * the array for which the predicate returns true. + * + * This implementation does not bail early and waits for all promises to + * resolve before returning. + */ +export async function findAsync(array, predicate) { + const results = await Promise.all(array.map(async (element, index) => ({ element, ok: await predicate(element, index) }))); + return results.find(r => r.ok)?.element; +} +//# sourceMappingURL=arrays.js.map \ No newline at end of file diff --git a/packages/core/dist/arrays.js.map b/packages/core/dist/arrays.js.map new file mode 100644 index 00000000..f2e803fd --- /dev/null +++ b/packages/core/dist/arrays.js.map @@ -0,0 +1 @@ +{"version":3,"file":"arrays.js","sourceRoot":"","sources":["../src/arrays.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,8BAA8B,EAAE,MAAM,iBAAiB,CAAC;AAEjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGhD;;;;GAIG;AACH,MAAM,UAAU,IAAI,CAAI,KAAmB,EAAE,IAAY,CAAC;IACzD,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,KAAK,CAAI,GAAQ;IAChC,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE;QACrB,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;KACrC;IAED,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,MAAM,CAAI,GAAiC,EAAE,KAAmC,EAAE,aAAsC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC;IACxJ,IAAI,GAAG,KAAK,KAAK,EAAE;QAClB,OAAO,IAAI,CAAC;KACZ;IAED,IAA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GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC1D,CAAC;IAED;;MAEE;IACF,OAAO;QACN,MAAM,eAAe,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;QAC/C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC/C,eAAe,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;SACvC;QACD,OAAO,IAAI,WAAW,CAAC,eAAe,CAAC,CAAC;IACzC,CAAC;CACD;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAI,KAAmB,EAAE,SAA0D;IACjH,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAC1C,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,EAAE,CAAC,CAC5E,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC;AACzC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/arraysFind.d.ts b/packages/core/dist/arraysFind.d.ts new file mode 100644 index 00000000..edbbf31f --- /dev/null +++ b/packages/core/dist/arraysFind.d.ts @@ -0,0 +1,67 @@ +import { Comparator } from './arrays.js'; +export declare function findLast(array: readonly T[], predicate: (item: T) => boolean): T | undefined; +export declare function findLastIdx(array: readonly T[], predicate: (item: T) => boolean, fromIndex?: number): number; +/** + * Finds the last item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`! + * + * @returns `undefined` if no item matches, otherwise the last item that matches the predicate. + */ +export declare function findLastMonotonous(array: readonly T[], predicate: (item: T) => boolean): T | undefined; +/** + * Finds the last item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`! + * + * @returns `startIdx - 1` if predicate is false for all items, otherwise the index of the last item that matches the predicate. + */ +export declare function findLastIdxMonotonous(array: readonly T[], predicate: (item: T) => boolean, startIdx?: number, endIdxEx?: number): number; +/** + * Finds the first item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`! + * + * @returns `undefined` if no item matches, otherwise the first item that matches the predicate. + */ +export declare function findFirstMonotonous(array: readonly T[], predicate: (item: T) => boolean): T | undefined; +/** + * Finds the first item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`! + * + * @returns `endIdxEx` if predicate is false for all items, otherwise the index of the first item that matches the predicate. + */ +export declare function findFirstIdxMonotonousOrArrLen(array: readonly T[], predicate: (item: T) => boolean, startIdx?: number, endIdxEx?: number): number; +export declare function findFirstIdxMonotonous(array: readonly T[], predicate: (item: T) => boolean, startIdx?: number, endIdxEx?: number): number; +/** + * Use this when + * * You have a sorted array + * * You query this array with a monotonous predicate to find the last item that has a certain property. + * * You query this array multiple times with monotonous predicates that get weaker and weaker. + */ +export declare class MonotonousArray { + private readonly _array; + static assertInvariants: boolean; + private _findLastMonotonousLastIdx; + private _prevFindLastPredicate; + constructor(_array: readonly T[]); + /** + * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`! + * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`. + */ + findLastMonotonous(predicate: (item: T) => boolean): T | undefined; +} +/** + * Returns the first item that is equal to or greater than every other item. +*/ +export declare function findFirstMax(array: readonly T[], comparator: Comparator): T | undefined; +/** + * Returns the last item that is equal to or greater than every other item. +*/ +export declare function findLastMax(array: readonly T[], comparator: Comparator): T | undefined; +/** + * Returns the first item that is equal to or less than every other item. +*/ +export declare function findFirstMin(array: readonly T[], comparator: Comparator): T | undefined; +export declare function findMaxIdx(array: readonly T[], comparator: Comparator): number; +/** + * Returns the first mapped value of the array which is not undefined. + */ +export declare function mapFindFirst(items: Iterable, mapFn: (value: T) => R | undefined): R | undefined; diff --git a/packages/core/dist/arraysFind.js b/packages/core/dist/arraysFind.js new file mode 100644 index 00000000..f1f7951f --- /dev/null +++ b/packages/core/dist/arraysFind.js @@ -0,0 +1,182 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +export function findLast(array, predicate) { + const idx = findLastIdx(array, predicate); + if (idx === -1) { + return undefined; + } + return array[idx]; +} +export function findLastIdx(array, predicate, fromIndex = array.length - 1) { + for (let i = fromIndex; i >= 0; i--) { + const element = array[i]; + if (predicate(element)) { + return i; + } + } + return -1; +} +/** + * Finds the last item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`! + * + * @returns `undefined` if no item matches, otherwise the last item that matches the predicate. + */ +export function findLastMonotonous(array, predicate) { + const idx = findLastIdxMonotonous(array, predicate); + return idx === -1 ? undefined : array[idx]; +} +/** + * Finds the last item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`! + * + * @returns `startIdx - 1` if predicate is false for all items, otherwise the index of the last item that matches the predicate. + */ +export function findLastIdxMonotonous(array, predicate, startIdx = 0, endIdxEx = array.length) { + let i = startIdx; + let j = endIdxEx; + while (i < j) { + const k = Math.floor((i + j) / 2); + if (predicate(array[k])) { + i = k + 1; + } + else { + j = k; + } + } + return i - 1; +} +/** + * Finds the first item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`! + * + * @returns `undefined` if no item matches, otherwise the first item that matches the predicate. + */ +export function findFirstMonotonous(array, predicate) { + const idx = findFirstIdxMonotonousOrArrLen(array, predicate); + return idx === array.length ? undefined : array[idx]; +} +/** + * Finds the first item where predicate is true using binary search. + * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`! + * + * @returns `endIdxEx` if predicate is false for all items, otherwise the index of the first item that matches the predicate. + */ +export function findFirstIdxMonotonousOrArrLen(array, predicate, startIdx = 0, endIdxEx = array.length) { + let i = startIdx; + let j = endIdxEx; + while (i < j) { + const k = Math.floor((i + j) / 2); + if (predicate(array[k])) { + j = k; + } + else { + i = k + 1; + } + } + return i; +} +export function findFirstIdxMonotonous(array, predicate, startIdx = 0, endIdxEx = array.length) { + const idx = findFirstIdxMonotonousOrArrLen(array, predicate, startIdx, endIdxEx); + return idx === array.length ? -1 : idx; +} +/** + * Use this when + * * You have a sorted array + * * You query this array with a monotonous predicate to find the last item that has a certain property. + * * You query this array multiple times with monotonous predicates that get weaker and weaker. + */ +export class MonotonousArray { + _array; + static assertInvariants = false; + _findLastMonotonousLastIdx = 0; + _prevFindLastPredicate; + constructor(_array) { + this._array = _array; + } + /** + * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`! + * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`. + */ + findLastMonotonous(predicate) { + if (MonotonousArray.assertInvariants) { + if (this._prevFindLastPredicate) { + for (const item of this._array) { + if (this._prevFindLastPredicate(item) && !predicate(item)) { + throw new Error('MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.'); + } + } + } + this._prevFindLastPredicate = predicate; + } + const idx = findLastIdxMonotonous(this._array, predicate, this._findLastMonotonousLastIdx); + this._findLastMonotonousLastIdx = idx + 1; + return idx === -1 ? undefined : this._array[idx]; + } +} +/** + * Returns the first item that is equal to or greater than every other item. +*/ +export function findFirstMax(array, comparator) { + if (array.length === 0) { + return undefined; + } + let max = array[0]; + for (let i = 1; i < array.length; i++) { + const item = array[i]; + if (comparator(item, max) > 0) { + max = item; + } + } + return max; +} +/** + * Returns the last item that is equal to or greater than every other item. +*/ +export function findLastMax(array, comparator) { + if (array.length === 0) { + return undefined; + } + let max = array[0]; + for (let i = 1; i < array.length; i++) { + const item = array[i]; + if (comparator(item, max) >= 0) { + max = item; + } + } + return max; +} +/** + * Returns the first item that is equal to or less than every other item. +*/ +export function findFirstMin(array, comparator) { + return findFirstMax(array, (a, b) => -comparator(a, b)); +} +export function findMaxIdx(array, comparator) { + if (array.length === 0) { + return -1; + } + let maxIdx = 0; + for (let i = 1; i < array.length; i++) { + const item = array[i]; + if (comparator(item, array[maxIdx]) > 0) { + maxIdx = i; + } + } + return maxIdx; +} +/** + * Returns the first mapped value of the array which is not undefined. + */ +export function mapFindFirst(items, mapFn) { + for (const value of items) { + const mapped = mapFn(value); + if (mapped !== undefined) { + return mapped; + } + } + return undefined; +} +//# sourceMappingURL=arraysFind.js.map \ No newline at end of file diff --git a/packages/core/dist/arraysFind.js.map b/packages/core/dist/arraysFind.js.map new file mode 100644 index 00000000..e863b177 --- /dev/null +++ b/packages/core/dist/arraysFind.js.map @@ -0,0 +1 @@ +{"version":3,"file":"arraysFind.js","sourceRoot":"","sources":["../src/arraysFind.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAIhG,MAAM,UAAU,QAAQ,CAAI,KAAmB,EAAE,SAA+B;IAC/E,MAAM,GAAG,GAAG,WAAW,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;IAC1C,IAAI,GAAG,KAAK,CAAC,CAAC,EAAE;QACf,OAAO,SAAS,CAAC;KACjB;IACD,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,WAAW,CAAI,KAAmB,EAAE,SAA+B,EAAE,SAAS,GAAG,KAAK,CAAC,MAAM,GAA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OAAO,MAAM,CAAC;SACd;KACD;IAED,OAAO,SAAS,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/aspects.d.ts b/packages/core/dist/aspects.d.ts new file mode 100644 index 00000000..a5b2791b --- /dev/null +++ b/packages/core/dist/aspects.d.ts @@ -0,0 +1,87 @@ +export declare enum SIGNALS { + BEFORE = "BEFORE", + AFTER = "AFTER", + AROUND = "AROUND", + ERROR = "ERROR" +} +type AnyFunction = (...args: any[]) => any; +/** + * If a function returns a Promise, then its awaited type is T. + * Otherwise, it's just ReturnType. + */ +type AwaitedReturn = T extends (...args: any[]) => Promise ? U : ReturnType; +/** + * BEFORE advice: + * - Receives `context` (the `this` of the function) + * - Receives the original `args` + * - Can return either nothing (`void`) or new arguments (`Parameters`) + * - Can be async, returning a Promise that resolves to new args or `void` + */ +export type BeforeAdvice = (context: ThisParameterType, args: Parameters) => void | Parameters | Promise>; +/** + * AFTER advice: + * - Receives `context`, the original function’s final (awaited) result, + * and the original arguments + * - Can return a new result (sync or async) + */ +export type AfterAdvice = (context: ThisParameterType, result: AwaitedReturn, args: Parameters) => AwaitedReturn | Promise>; +/** + * AROUND advice: + * - Provides a `proceed(...args)` function that calls the original method + * - You can call `proceed` any number of times, or skip it + * - Supports both sync and async usage + */ +export type AroundAdvice = (proceed: (...args: Parameters) => ReturnType, context: ThisParameterType, args: Parameters) => ReturnType; +/** + * ERROR advice: + * - Intercepts errors thrown by the original method (sync or async) + * - Can return a fallback result or rethrow + */ +export type ErrorAdvice = (error: unknown, context: ThisParameterType, args: Parameters) => ReturnType | void; +interface AspectOptions { + type: T; + advice: A; +} +/** + * The core aspect(...) function + * - Returns a decorator if used in that style + * - Otherwise, can wrap a function directly + */ +declare function aspect({ type, advice }: AspectOptions): (target: any, _name?: string, descriptor?: PropertyDescriptor) => any; +/** + * `before`: + * Decorator usage => @before((ctx, args) => ...) + * Direct usage => myFn = before(myFn, (ctx, args) => ...) + */ +export declare function before(advice: BeforeAdvice): (target: any, name?: string, descriptor?: PropertyDescriptor) => any; +export declare function before(fn: T, advice: BeforeAdvice): T; +/** + * `after`: + * Decorator usage => @after((ctx, result, args) => ...) + * Direct usage => myFn = after(myFn, (ctx, result, args) => ...) + */ +export declare function after(advice: AfterAdvice): (target: any, name?: string, descriptor?: PropertyDescriptor) => any; +export declare function after(fn: T, advice: AfterAdvice): T; +/** + * `around`: + * Decorator usage => @around((proceed, ctx, args) => ...) + * Direct usage => myFn = around(myFn, (proceed, ctx, args) => ...) + */ +export declare function around(advice: AroundAdvice): (target: any, name?: string, descriptor?: PropertyDescriptor) => any; +export declare function around(fn: T, advice: AroundAdvice): T; +/** + * `error`: + * Decorator usage => @error((err, ctx, args) => ...) + * Direct usage => myFn = error(myFn, (err, ctx, args) => ...) + */ +export declare function error(advice: ErrorAdvice): (target: any, name?: string, descriptor?: PropertyDescriptor) => any; +export declare function error(fn: T, advice: ErrorAdvice): T; +declare const _default: { + SIGNALS: typeof SIGNALS; + before: typeof before; + after: typeof after; + around: typeof around; + error: typeof error; + aspect: typeof aspect; +}; +export default _default; diff --git a/packages/core/dist/aspects.js b/packages/core/dist/aspects.js new file mode 100644 index 00000000..c510c887 --- /dev/null +++ b/packages/core/dist/aspects.js @@ -0,0 +1,188 @@ +/* ------------------------------------------------------------------------- + * aspects.ts + * + * A robust “aspect” system supporting: + * - before: optionally modifies arguments (sync or async) + * - after: optionally modifies return value (sync or async) + * - around: complete control over function invocation + * - error: intercept errors (sync or async) + * + * Works as both: + * 1) Decorators for class methods (e.g. @before(...)) + * 2) Direct function wrappers (e.g. fn = before(fn, ...)). + * ------------------------------------------------------------------------ */ +/* ------------------------------------------------------------------------- + * 1) SIGNALS Enum (string-based to avoid symbol issues) + * ------------------------------------------------------------------------ */ +export var SIGNALS; +(function (SIGNALS) { + SIGNALS["BEFORE"] = "BEFORE"; + SIGNALS["AFTER"] = "AFTER"; + SIGNALS["AROUND"] = "AROUND"; + SIGNALS["ERROR"] = "ERROR"; +})(SIGNALS = SIGNALS || (SIGNALS = {})); +/* ------------------------------------------------------------------------- + * 5) The SignalMap Implementation + * - This is where the actual "wrapping" logic lives. + * ------------------------------------------------------------------------ */ +const SignalMap = { + /** + * BEFORE: + * - Possibly modifies arguments + * - If returns a Promise, we await it before calling original + * - If returns an array, we use that as new arguments + */ + [SIGNALS.BEFORE](original, advice) { + return function (...args) { + const maybeNewArgs = advice(this, args); + if (maybeNewArgs instanceof Promise) { + return maybeNewArgs.then((resolvedArgs) => { + const finalArgs = resolvedArgs || args; + const result = original.apply(this, finalArgs); + return (result instanceof Promise) ? result : Promise.resolve(result); + }); + } + else { + const finalArgs = Array.isArray(maybeNewArgs) ? maybeNewArgs : args; + return original.apply(this, finalArgs); + } + }; + }, + /** + * AFTER: + * - Possibly modifies the return value + * - If original is async, we chain on its promise + * - Advice can be sync or async + */ + [SIGNALS.AFTER](original, advice) { + return function (...args) { + const result = original.apply(this, args); + if (result instanceof Promise) { + return result.then((unwrapped) => { + const maybeNewResult = advice(this, unwrapped, args); + return (maybeNewResult instanceof Promise) ? maybeNewResult : maybeNewResult; + }); + } + else { + const maybeNewResult = advice(this, result, args); + if (maybeNewResult instanceof Promise) { + return maybeNewResult.then(r => r); + } + return maybeNewResult; + } + }; + }, + /** + * AROUND: + * - Full control over invocation + * - Typically you do: proceed(...args) + * - If you want to skip or call multiple times, you can + */ + [SIGNALS.AROUND](original, advice) { + return function (...args) { + const proceed = (...innerArgs) => original.apply(this, innerArgs); + return advice(proceed, this, args); + }; + }, + /** + * ERROR: + * - Intercepts errors thrown by the original function or a rejected Promise + * - Optionally returns a fallback or rethrows + */ + [SIGNALS.ERROR](original, advice) { + return function (...args) { + try { + const result = original.apply(this, args); + if (result instanceof Promise) { + // Handle async rejections + return result.catch((err) => { + return advice(err, this, args); + }); + } + return result; + } + catch (err) { + // Synchronous error + return advice(err, this, args); + } + }; + }, +}; +/* ------------------------------------------------------------------------- + * 6) Decorator Helper + * ------------------------------------------------------------------------ */ +/** Checks if we’re decorating a class method. */ +function isMethod(_target, descriptor) { + return !!descriptor && typeof descriptor.value === 'function'; +} +/* ------------------------------------------------------------------------- + * 7) Wrapped Helpers (cutMethod, cut, aspect) + * ------------------------------------------------------------------------ */ +/** Strictly typed wrapping for class methods. */ +function cutMethod(descriptor, advice, type) { + const original = descriptor.value; + descriptor.value = SignalMap[type](original, advice); // Cast `any` or refine further + return descriptor; +} +/** Strictly typed wrapping for direct function usage. */ +function cut(target, advice, type) { + return SignalMap[type](target, advice); +} +/** + * The core aspect(...) function + * - Returns a decorator if used in that style + * - Otherwise, can wrap a function directly + */ +function aspect({ type, advice }) { + // If type is invalid, produce a no-op decorator + if (!(type in SignalMap)) { + return function crosscut(target, _name, descriptor) { + return descriptor || target; + }; + } + // Return a decorator function + return function crosscut(target, _name, descriptor) { + // If used on a method + if (isMethod(target, descriptor)) { + return cutMethod(descriptor, advice, type); + } + // If used directly on a function or something else + return cut(target, advice, type); + }; +} +export function before(arg1, arg2) { + if (typeof arg1 === 'function' && typeof arg2 === 'function') { + return SignalMap[SIGNALS.BEFORE](arg1, arg2); + } + return aspect({ type: SIGNALS.BEFORE, advice: arg1 }); +} +export function after(arg1, arg2) { + if (typeof arg1 === 'function' && typeof arg2 === 'function') { + return SignalMap[SIGNALS.AFTER](arg1, arg2); + } + return aspect({ type: SIGNALS.AFTER, advice: arg1 }); +} +export function around(arg1, arg2) { + if (typeof arg1 === 'function' && typeof arg2 === 'function') { + return SignalMap[SIGNALS.AROUND](arg1, arg2); + } + return aspect({ type: SIGNALS.AROUND, advice: arg1 }); +} +export function error(arg1, arg2) { + if (typeof arg1 === 'function' && typeof arg2 === 'function') { + return SignalMap[SIGNALS.ERROR](arg1, arg2); + } + return aspect({ type: SIGNALS.ERROR, advice: arg1 }); +} +/* ------------------------------------------------------------------------- + * 9) Default Export + * ------------------------------------------------------------------------ */ +export default { + SIGNALS, + before, + after, + around, + error, + aspect, +}; +//# sourceMappingURL=aspects.js.map \ No newline at end of file diff --git a/packages/core/dist/aspects.js.map b/packages/core/dist/aspects.js.map new file mode 100644 index 00000000..887cadaf --- /dev/null +++ b/packages/core/dist/aspects.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aspects.js","sourceRoot":"","sources":["../src/aspects.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;8EAY8E;AAE9E;;8EAE8E;AAC9E,MAAM,CAAN,IAAY,OAKX;AALD,WAAY,OAAO;IACjB,4BAAiB,CAAA;IACjB,0BAAe,CAAA;IACf,4BAAiB,CAAA;IACjB,0BAAe,CAAA;AACjB,CAAC,EALW,OAAO,GAAP,OAAO,KAAP,OAAO,QAKlB;AA2ED;;;8EAG8E;AAC9E,MAAM,SAAS,GAAe;IAC5B;;;;;OAKG;IACH,CAAC,OAAO,CAAC,MAAM,CAAC,CAAwB,QAAW,EAAE,MAAuB;QAC1E,OAAO,UAAsC,GAAG,IAAmB;YACjE,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAExC,IAAI,YAAY,YAAY,OAAO,EAAE;gBACnC,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,EAAE;oBACxC,MAAM,SAAS,GAAG,YAAY,IAAI,IAAI,CAAC;oBACvC,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;oBAC/C,OAAO,CAAC,MAAM,YAAY,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;gBACxE,CAAC,CAAkB,CAAC;aACrB;iBAAM;gBACL,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC;gBACpE,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;aACxC;QACH,CAAM,CAAC;IACT,CAAC;IAED;;;;;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AAM,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;KAC9C;IACD,OAAO,MAAM,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,IAAuB,EAAE,CAAC,CAAC;AAC3E,CAAC;AAWD,MAAM,UAAU,KAAK,CACnB,IAAwB,EACxB,IAAqB;IAErB,IAAI,OAAO,IAAI,KAAK,UAAU,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE;QAC5D,OAAO,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;KAC7C;IACD,OAAO,MAAM,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,IAAsB,EAAE,CAAC,CAAC;AACzE,CAAC;AAED;;8EAE8E;AAC9E,eAAe;IACb,OAAO;IACP,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;CACP,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/aspects_simple.d.ts b/packages/core/dist/aspects_simple.d.ts new file mode 100644 index 00000000..e024aef5 --- /dev/null +++ b/packages/core/dist/aspects_simple.d.ts @@ -0,0 +1,68 @@ +export declare enum SIGNALS { + BEFORE = "BEFORE", + AFTER = "AFTER", + AROUND = "AROUND", + ERROR = "ERROR" +} +type AnyFunction = (...args: any[]) => any; +/** + * If a function returns a Promise, then its awaited type is T. + * Otherwise, it's just ReturnType. + */ +type AwaitedReturn = T extends (...args: any[]) => Promise ? U : ReturnType; +/** + * BEFORE advice: + * - Receives `context` (the `this` of the function) + * - Receives the original `args` + * - Can return either nothing (`void`) or new arguments (`Parameters`) + * - Can be async, returning a Promise that resolves to new args or `void` + */ +export type BeforeAdvice = (context: ThisParameterType, args: Parameters) => void | Parameters | Promise>; +/** + * AFTER advice: + * - Receives `context`, the original function’s final (awaited) result, + * and the original arguments + * - Can return a new result (sync or async) + */ +export type AfterAdvice = (context: ThisParameterType, result: AwaitedReturn, args: Parameters) => AwaitedReturn | Promise>; +/** + * AROUND advice: + * - Provides a `proceed(...args)` function that calls the original method + * - You can call `proceed` any number of times, or skip it + * - Supports both sync and async usage + */ +export type AroundAdvice = (proceed: (...args: Parameters) => ReturnType, context: ThisParameterType, args: Parameters) => ReturnType; +/** + * ERROR advice: + * - Intercepts errors thrown by the original function (sync or async) + * - Can return a fallback result or rethrow + */ +export type ErrorAdvice = (error: unknown, context: ThisParameterType, args: Parameters) => ReturnType | void; +/** + * `before`: + * Direct usage => myFn = before(myFn, (ctx, args) => ...) + */ +export declare function before(fn: T, advice: BeforeAdvice): T; +/** + * `after`: + * Direct usage => myFn = after(myFn, (ctx, result, args) => ...) + */ +export declare function after(fn: T, advice: AfterAdvice): T; +/** + * `around`: + * Direct usage => myFn = around(myFn, (proceed, ctx, args) => ...) + */ +export declare function around(fn: T, advice: AroundAdvice): T; +/** + * `error`: + * Direct usage => myFn = error(myFn, (err, ctx, args) => ...) + */ +export declare function error(fn: T, advice: ErrorAdvice): T; +declare const _default: { + SIGNALS: typeof SIGNALS; + before: typeof before; + after: typeof after; + around: typeof around; + error: typeof error; +}; +export default _default; diff --git a/packages/core/dist/aspects_simple.js b/packages/core/dist/aspects_simple.js new file mode 100644 index 00000000..4e08be50 --- /dev/null +++ b/packages/core/dist/aspects_simple.js @@ -0,0 +1,150 @@ +/* ------------------------------------------------------------------------- + * aspects.ts + * + * A robust “aspect” system supporting: + * - before: optionally modifies arguments (sync or async) + * - after: optionally modifies return value (sync or async) + * - around: complete control over function invocation + * - error: intercept errors (sync or async) + * + * Only supports direct function wrappers (e.g. fn = before(fn, ...)). + * ------------------------------------------------------------------------ */ +/* ------------------------------------------------------------------------- + * 1) SIGNALS Enum (string-based to avoid symbol issues) + * ------------------------------------------------------------------------ */ +export var SIGNALS; +(function (SIGNALS) { + SIGNALS["BEFORE"] = "BEFORE"; + SIGNALS["AFTER"] = "AFTER"; + SIGNALS["AROUND"] = "AROUND"; + SIGNALS["ERROR"] = "ERROR"; +})(SIGNALS = SIGNALS || (SIGNALS = {})); +/* ------------------------------------------------------------------------- + * 5) The SignalMap Implementation + * - This is where the actual "wrapping" logic lives. + * ------------------------------------------------------------------------ */ +const SignalMap = { + /** + * BEFORE: + * - Possibly modifies arguments + * - If returns a Promise, we await it before calling original + * - If returns an array, we use that as new arguments + */ + [SIGNALS.BEFORE](original, advice) { + return function (...args) { + const maybeNewArgs = advice(this, args); + if (maybeNewArgs instanceof Promise) { + return maybeNewArgs.then((resolvedArgs) => { + const finalArgs = resolvedArgs || args; + const result = original.apply(this, finalArgs); + return (result instanceof Promise) ? result : Promise.resolve(result); + }); + } + else { + const finalArgs = Array.isArray(maybeNewArgs) ? maybeNewArgs : args; + return original.apply(this, finalArgs); + } + }; + }, + /** + * AFTER: + * - Possibly modifies the return value + * - If original is async, we chain on its promise + * - Advice can be sync or async + */ + [SIGNALS.AFTER](original, advice) { + return function (...args) { + const result = original.apply(this, args); + if (result instanceof Promise) { + return result.then((unwrapped) => { + const maybeNewResult = advice(this, unwrapped, args); + return (maybeNewResult instanceof Promise) ? maybeNewResult : maybeNewResult; + }); + } + else { + const maybeNewResult = advice(this, result, args); + if (maybeNewResult instanceof Promise) { + return maybeNewResult.then(r => r); + } + return maybeNewResult; + } + }; + }, + /** + * AROUND: + * - Full control over invocation + * - Typically you do: proceed(...args) + * - If you want to skip or call multiple times, you can + */ + [SIGNALS.AROUND](original, advice) { + return function (...args) { + const proceed = (...innerArgs) => original.apply(this, innerArgs); + return advice(proceed, this, args); + }; + }, + /** + * ERROR: + * - Intercepts errors thrown by the original function or a rejected Promise + * - Optionally returns a fallback or rethrows + */ + [SIGNALS.ERROR](original, advice) { + return function (...args) { + try { + const result = original.apply(this, args); + if (result instanceof Promise) { + // Handle async rejections + return result.catch((err) => { + return advice(err, this, args); + }); + } + return result; + } + catch (err) { + // Synchronous error + return advice(err, this, args); + } + }; + }, +}; +/* ------------------------------------------------------------------------- + * 6) Direct Usage Functions (no decorator support) + * ------------------------------------------------------------------------ */ +/** + * `before`: + * Direct usage => myFn = before(myFn, (ctx, args) => ...) + */ +export function before(fn, advice) { + return SignalMap[SIGNALS.BEFORE](fn, advice); +} +/** + * `after`: + * Direct usage => myFn = after(myFn, (ctx, result, args) => ...) + */ +export function after(fn, advice) { + return SignalMap[SIGNALS.AFTER](fn, advice); +} +/** + * `around`: + * Direct usage => myFn = around(myFn, (proceed, ctx, args) => ...) + */ +export function around(fn, advice) { + return SignalMap[SIGNALS.AROUND](fn, advice); +} +/** + * `error`: + * Direct usage => myFn = error(myFn, (err, ctx, args) => ...) + */ +export function error(fn, advice) { + return SignalMap[SIGNALS.ERROR](fn, advice); +} +/* ------------------------------------------------------------------------- + * 7) Default Export + * ------------------------------------------------------------------------ */ +export default { + SIGNALS, + before, + after, + around, + error, +}; +//# sourceMappingURL=aspects_simple.js.map \ No newline at end of file diff --git a/packages/core/dist/aspects_simple.js.map b/packages/core/dist/aspects_simple.js.map new file mode 100644 index 00000000..6fd79010 --- /dev/null +++ b/packages/core/dist/aspects_simple.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aspects_simple.js","sourceRoot":"","sources":["../src/aspects_simple.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;8EAU8E;AAE9E;;8EAE8E;AAC9E,MAAM,CAAN,IAAY,OAKT;AALH,WAAY,OAAO;IACf,4BAAiB,CAAA;IACjB,0BAAe,CAAA;IACf,4BAAiB,CAAA;IACjB,0BAAe,CAAA;AACjB,CAAC,EALS,OAAO,GAAP,OAAO,KAAP,OAAO,QAKhB;AA2ED;;;8EAG8E;AAC9E,MAAM,SAAS,GAAe;IAC5B;;;;;OAKG;IACH,CAAC,OAAO,CAAC,MAAM,CAAC,CAAwB,QAAW,EAAE,MAAuB;QAC1E,OAAO,UAAsC,GAAG,IAAmB;YACjE,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAExC,IAAI,YAAY,YAAY,OAAO,EAAE;gBACnC,OAAO,YAA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AAK,CAAwB,EAAK,EAAE,MAAsB;IACxE,OAAO,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AAC9C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,MAAM,CAAwB,EAAK,EAAE,MAAuB;IAC1E,OAAO,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AAC/C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,KAAK,CAAwB,EAAK,EAAE,MAAsB;IACxE,OAAO,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AAC9C,CAAC;AAED;;8EAE8E;AAC9E,eAAe;IACb,OAAO;IACP,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;CACN,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/assert.d.ts b/packages/core/dist/assert.d.ts new file mode 100644 index 00000000..aaa52c13 --- /dev/null +++ b/packages/core/dist/assert.d.ts @@ -0,0 +1,26 @@ +/** + * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value. + * + * @deprecated Use `assert(...)` instead. + * This method is usually used like this: + * ```ts + * import * as assert from 'vs/base/common/assert'; + * assert.ok(...); + * ``` + * + * However, `assert` in that example is a user chosen name. + * There is no tooling for generating such an import statement. + * Thus, the `assert(...)` function should be used instead. + */ +export declare function ok(value?: unknown, message?: string): void; +export declare function assertNever(value: never, message?: string): never; +export declare function assert(condition: boolean, message?: string): asserts condition; +/** + * Like assert, but doesn't throw. + */ +export declare function softAssert(condition: boolean): void; +/** + * condition must be side-effect free! + */ +export declare function assertFn(condition: () => boolean): void; +export declare function checkAdjacentItems(items: readonly T[], predicate: (item1: T, item2: T) => boolean): boolean; diff --git a/packages/core/dist/assert.js b/packages/core/dist/assert.js new file mode 100644 index 00000000..a6b3b329 --- /dev/null +++ b/packages/core/dist/assert.js @@ -0,0 +1,65 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { BugIndicatingError, onUnexpectedError } from './errors.js'; +/** + * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value. + * + * @deprecated Use `assert(...)` instead. + * This method is usually used like this: + * ```ts + * import * as assert from 'vs/base/common/assert'; + * assert.ok(...); + * ``` + * + * However, `assert` in that example is a user chosen name. + * There is no tooling for generating such an import statement. + * Thus, the `assert(...)` function should be used instead. + */ +export function ok(value, message) { + if (!value) { + throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed'); + } +} +export function assertNever(value, message = 'Unreachable') { + throw new Error(message); +} +export function assert(condition, message = 'unexpected state') { + if (!condition) { + throw new BugIndicatingError(`Assertion Failed: ${message}`); + } +} +/** + * Like assert, but doesn't throw. + */ +export function softAssert(condition) { + if (!condition) { + onUnexpectedError(new BugIndicatingError('Soft Assertion Failed')); + } +} +/** + * condition must be side-effect free! + */ +export function assertFn(condition) { + if (!condition()) { + // eslint-disable-next-line no-debugger + debugger; + // Reevaluate `condition` again to make debugging easier + condition(); + onUnexpectedError(new BugIndicatingError('Assertion Failed')); + } +} +export function checkAdjacentItems(items, predicate) { + let i = 0; + while (i < items.length - 1) { + const a = items[i]; + const b = items[i + 1]; + if (!predicate(a, b)) { + return false; + } + i++; + } + return true; +} +//# sourceMappingURL=assert.js.map \ No newline at end of file diff --git a/packages/core/dist/assert.js.map b/packages/core/dist/assert.js.map new file mode 100644 index 00000000..621de2a7 --- /dev/null +++ b/packages/core/dist/assert.js.map @@ -0,0 +1 @@ +{"version":3,"file":"assert.js","sourceRoot":"","sources":["../src/assert.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,EAAE,CAAC,KAAe,EA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AAC,EAAE,CAAC;KACJ;IACD,OAAO,IAAI,CAAC;AACb,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/cache.d.ts b/packages/core/dist/cache.d.ts new file mode 100644 index 00000000..eb82d846 --- /dev/null +++ b/packages/core/dist/cache.d.ts @@ -0,0 +1,46 @@ +import { CancellationToken } from './cancellation.js'; +import { IDisposable } from './lifecycle.js'; +export interface CacheResult extends IDisposable { + promise: Promise; +} +export declare class Cache { + private task; + private result; + constructor(task: (ct: CancellationToken) => Promise); + get(): CacheResult; +} +export declare function identity(t: T): T; +interface ICacheOptions { + /** + * The cache key is used to identify the cache entry. + * Strict equality is used to compare cache keys. + */ + getCacheKey: (arg: TArg) => unknown; +} +/** + * Uses a LRU cache to make a given parametrized function cached. + * Caches just the last key/value. +*/ +export declare class LRUCachedFunction { + private lastCache; + private lastArgKey; + private readonly _fn; + private readonly _computeKey; + constructor(fn: (arg: TArg) => TComputed); + constructor(options: ICacheOptions, fn: (arg: TArg) => TComputed); + get(arg: TArg): TComputed; +} +/** + * Uses an unbounded cache to memoize the results of the given function. +*/ +export declare class CachedFunction { + private readonly _map; + private readonly _map2; + get cachedValues(): ReadonlyMap; + private readonly _fn; + private readonly _computeKey; + constructor(fn: (arg: TArg) => TComputed); + constructor(options: ICacheOptions, fn: (arg: TArg) => TComputed); + get(arg: TArg): TComputed; +} +export {}; diff --git a/packages/core/dist/cache.js b/packages/core/dist/cache.js new file mode 100644 index 00000000..9ad9a7d6 --- /dev/null +++ b/packages/core/dist/cache.js @@ -0,0 +1,92 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { CancellationTokenSource } from './cancellation.js'; +export class Cache { + task; + result = null; + constructor(task) { + this.task = task; + } + get() { + if (this.result) { + return this.result; + } + const cts = new CancellationTokenSource(); + const promise = this.task(cts.token); + this.result = { + promise, + dispose: () => { + this.result = null; + cts.cancel(); + cts.dispose(); + } + }; + return this.result; + } +} +export function identity(t) { + return t; +} +/** + * Uses a LRU cache to make a given parametrized function cached. + * Caches just the last key/value. +*/ +export class LRUCachedFunction { + lastCache = undefined; + lastArgKey = undefined; + _fn; + _computeKey; + constructor(arg1, arg2) { + if (typeof arg1 === 'function') { + this._fn = arg1; + this._computeKey = identity; + } + else { + this._fn = arg2; + this._computeKey = arg1.getCacheKey; + } + } + get(arg) { + const key = this._computeKey(arg); + if (this.lastArgKey !== key) { + this.lastArgKey = key; + this.lastCache = this._fn(arg); + } + return this.lastCache; + } +} +/** + * Uses an unbounded cache to memoize the results of the given function. +*/ +export class CachedFunction { + _map = new Map(); + _map2 = new Map(); + get cachedValues() { + return this._map; + } + _fn; + _computeKey; + constructor(arg1, arg2) { + if (typeof arg1 === 'function') { + this._fn = arg1; + this._computeKey = identity; + } + else { + this._fn = arg2; + this._computeKey = arg1.getCacheKey; + } + } + get(arg) { + const key = this._computeKey(arg); + if (this._map2.has(key)) { + return this._map2.get(key); + } + const value = this._fn(arg); + this._map.set(arg, value); + this._map2.set(key, value); + return value; + } +} +//# sourceMappingURL=cache.js.map \ No newline at end of file diff --git a/packages/core/dist/cache.js.map b/packages/core/dist/cache.js.map new file mode 100644 index 00000000..60baebce --- /dev/null +++ b/packages/core/dist/cache.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cache.js","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAqB,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAO/E,MAAM,OAAO,KAAK;IAGG;IADZ,MAAM,GAA0B,IAAI,CAAC;IAC7C,YAAoB,IAA2C;QAA3C,SAAI,GAAJ,IAAI,CAAuC;IAAI,CAAC;IAEpE,GAAG;QACF,IAAI,IAAI,CAAC,MAAM,EAAE;YAChB,OAAO,IAAI,CAAC,MAAM,CAAC;SACnB;QAED,MAAM,GAAG,GAAG,IAAI,uBAAuB,EAAE,C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CAAC;IAClC,KAAK,GAAG,IAAI,GAAG,EAAsB,CAAC;IACvD,IAAW,YAAY;QACtB,OAAO,IAAI,CAAC,IAAI,CAAC;IAClB,CAAC;IAEgB,GAAG,CAA2B;IAC9B,WAAW,CAAyB;IAIrD,YAAY,IAAsD,EAAE,IAA+B;QAClG,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE;YAC/B,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC;YAChB,IAAI,CAAC,WAAW,GAAG,QAAQ,CAAC;SAC5B;aAAM;YACN,IAAI,CAAC,GAAG,GAAG,IAAK,CAAC;YACjB,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;SACpC;IACF,CAAC;IAEM,GAAG,CAAC,GAAS;QACnB,MAAM,GAAG,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;YACxB,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAE,CAAC;SAC5B;QAED,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC5B,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC1B,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC3B,OAAO,KAAK,CAAC;IACd,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/cancellation.d.ts b/packages/core/dist/cancellation.d.ts new file mode 100644 index 00000000..f19d787e --- /dev/null +++ b/packages/core/dist/cancellation.d.ts @@ -0,0 +1,30 @@ +import { DisposableStore, IDisposable } from './lifecycle.js'; +export interface CancellationToken { + /** + * A flag signalling is cancellation has been requested. + */ + readonly isCancellationRequested: boolean; + /** + * An event which fires when cancellation is requested. This event + * only ever fires `once` as cancellation can only happen once. Listeners + * that are registered after cancellation will be called (next event loop run), + * but also only once. + * + * @event + */ + readonly onCancellationRequested: (listener: (e: any) => any, thisArgs?: any, disposables?: IDisposable[]) => IDisposable; +} +export declare namespace CancellationToken { + function isCancellationToken(thing: unknown): thing is CancellationToken; + const None: Readonly; + const Cancelled: Readonly; +} +export declare class CancellationTokenSource { + private _token?; + private _parentListener?; + constructor(parent?: CancellationToken); + get token(): CancellationToken; + cancel(): void; + dispose(cancel?: boolean): void; +} +export declare function cancelOnDispose(store: DisposableStore): CancellationToken; diff --git a/packages/core/dist/cancellation.js b/packages/core/dist/cancellation.js new file mode 100644 index 00000000..ed40cdb5 --- /dev/null +++ b/packages/core/dist/cancellation.js @@ -0,0 +1,112 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { Emitter, Event } from './event.js'; +const shortcutEvent = Object.freeze(function (callback, context) { + const handle = setTimeout(callback.bind(context), 0); + return { dispose() { clearTimeout(handle); } }; +}); +export var CancellationToken; +(function (CancellationToken) { + function isCancellationToken(thing) { + if (thing === CancellationToken.None || thing === CancellationToken.Cancelled) { + return true; + } + if (thing instanceof MutableToken) { + return true; + } + if (!thing || typeof thing !== 'object') { + return false; + } + return typeof thing.isCancellationRequested === 'boolean' + && typeof thing.onCancellationRequested === 'function'; + } + CancellationToken.isCancellationToken = isCancellationToken; + CancellationToken.None = Object.freeze({ + isCancellationRequested: false, + onCancellationRequested: Event.None + }); + CancellationToken.Cancelled = Object.freeze({ + isCancellationRequested: true, + onCancellationRequested: shortcutEvent + }); +})(CancellationToken = CancellationToken || (CancellationToken = {})); +class MutableToken { + _isCancelled = false; + _emitter = null; + cancel() { + if (!this._isCancelled) { + this._isCancelled = true; + if (this._emitter) { + this._emitter.fire(undefined); + this.dispose(); + } + } + } + get isCancellationRequested() { + return this._isCancelled; + } + get onCancellationRequested() { + if (this._isCancelled) { + return shortcutEvent; + } + if (!this._emitter) { + this._emitter = new Emitter(); + } + return this._emitter.event; + } + dispose() { + if (this._emitter) { + this._emitter.dispose(); + this._emitter = null; + } + } +} +export class CancellationTokenSource { + _token = undefined; + _parentListener = undefined; + constructor(parent) { + this._parentListener = parent && parent.onCancellationRequested(this.cancel, this); + } + get token() { + if (!this._token) { + // be lazy and create the token only when + // actually needed + this._token = new MutableToken(); + } + return this._token; + } + cancel() { + if (!this._token) { + // save an object by returning the default + // cancelled token when cancellation happens + // before someone asks for the token + this._token = CancellationToken.Cancelled; + } + else if (this._token instanceof MutableToken) { + // actually cancel + this._token.cancel(); + } + } + dispose(cancel = false) { + if (cancel) { + this.cancel(); + } + this._parentListener?.dispose(); + if (!this._token) { + // ensure to initialize with an empty token if we had none + this._token = CancellationToken.None; + } + else if (this._token instanceof MutableToken) { + // actually dispose + this._token.dispose(); + } + } +} +export function cancelOnDispose(store) { + const source = new CancellationTokenSource(); + store.add({ dispose() { source.cancel(); } }); + return source.token; +} +//# sourceMappingURL=cancellation.js.map \ No newline at end of file diff --git a/packages/core/dist/cancellation.js.map b/packages/core/dist/cancellation.js.map new file mode 100644 index 00000000..fd598f78 --- /dev/null +++ b/packages/core/dist/cancellation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cancellation.js","sourceRoot":"","sources":["../src/cancellation.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAqB5C,MAAM,aAAa,GAAe,MAAM,CAAC,MAAM,CAAC,UAAU,QAAQ,EAAE,OAAQ;IAC3E,MAAM,MAAM,GAAG,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC;IACrD,OAAO,EAAE,OAAO,KAAK,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAChD,CAAC,CAAC,CAAC;AAEH,MAAM,KAAW,iBAAiB,CA0BjC;AA1BD,WAAi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AAI,CAAC,IAAI,CAAC,MAAM,EAAE;YACjB,0DAA0D;YAC1D,IAAI,CAAC,MAAM,GAAG,iBAAiB,CAAC,IAAI,CAAC;SAErC;aAAM,IAAI,IAAI,CAAC,MAAM,YAAY,YAAY,EAAE;YAC/C,mBAAmB;YACnB,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;SACtB;IACF,CAAC;CACD;AAED,MAAM,UAAU,eAAe,CAAC,KAAsB;IACrD,MAAM,MAAM,GAAG,IAAI,uBAAuB,EAAE,CAAC;IAC7C,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,KAAK,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IAC9C,OAAO,MAAM,CAAC,KAAK,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/charCode.d.ts b/packages/core/dist/charCode.d.ts new file mode 100644 index 00000000..8468ca1a --- /dev/null +++ b/packages/core/dist/charCode.d.ts @@ -0,0 +1,401 @@ +/** + * An inlined enum containing useful character codes (to be used with String.charCodeAt). + * Please leave the const keyword such that it gets inlined when compiled to JavaScript! + */ +export declare const enum CharCode { + Null = 0, + /** + * The `\t` character. + */ + Tab = 9, + /** + * The `\n` character. + */ + LineFeed = 10, + /** + * The `\r` character. + */ + CarriageReturn = 13, + Space = 32, + /** + * The `!` character. + */ + ExclamationMark = 33, + /** + * The `"` character. + */ + DoubleQuote = 34, + /** + * The `#` character. + */ + Hash = 35, + /** + * The `$` character. + */ + DollarSign = 36, + /** + * The `%` character. + */ + PercentSign = 37, + /** + * The `&` character. + */ + Ampersand = 38, + /** + * The `'` character. + */ + SingleQuote = 39, + /** + * The `(` character. + */ + OpenParen = 40, + /** + * The `)` character. + */ + CloseParen = 41, + /** + * The `*` character. + */ + Asterisk = 42, + /** + * The `+` character. + */ + Plus = 43, + /** + * The `,` character. + */ + Comma = 44, + /** + * The `-` character. + */ + Dash = 45, + /** + * The `.` character. + */ + Period = 46, + /** + * The `/` character. + */ + Slash = 47, + Digit0 = 48, + Digit1 = 49, + Digit2 = 50, + Digit3 = 51, + Digit4 = 52, + Digit5 = 53, + Digit6 = 54, + Digit7 = 55, + Digit8 = 56, + Digit9 = 57, + /** + * The `:` character. + */ + Colon = 58, + /** + * The `;` character. + */ + Semicolon = 59, + /** + * The `<` character. + */ + LessThan = 60, + /** + * The `=` character. + */ + Equals = 61, + /** + * The `>` character. + */ + GreaterThan = 62, + /** + * The `?` character. + */ + QuestionMark = 63, + /** + * The `@` character. + */ + AtSign = 64, + A = 65, + B = 66, + C = 67, + D = 68, + E = 69, + F = 70, + G = 71, + H = 72, + I = 73, + J = 74, + K = 75, + L = 76, + M = 77, + N = 78, + O = 79, + P = 80, + Q = 81, + R = 82, + S = 83, + T = 84, + U = 85, + V = 86, + W = 87, + X = 88, + Y = 89, + Z = 90, + /** + * The `[` character. + */ + OpenSquareBracket = 91, + /** + * The `\` character. + */ + Backslash = 92, + /** + * The `]` character. + */ + CloseSquareBracket = 93, + /** + * The `^` character. + */ + Caret = 94, + /** + * The `_` character. + */ + Underline = 95, + /** + * The ``(`)`` character. + */ + BackTick = 96, + a = 97, + b = 98, + c = 99, + d = 100, + e = 101, + f = 102, + g = 103, + h = 104, + i = 105, + j = 106, + k = 107, + l = 108, + m = 109, + n = 110, + o = 111, + p = 112, + q = 113, + r = 114, + s = 115, + t = 116, + u = 117, + v = 118, + w = 119, + x = 120, + y = 121, + z = 122, + /** + * The `{` character. + */ + OpenCurlyBrace = 123, + /** + * The `|` character. + */ + Pipe = 124, + /** + * The `}` character. + */ + CloseCurlyBrace = 125, + /** + * The `~` character. + */ + Tilde = 126, + U_Combining_Grave_Accent = 768, + U_Combining_Acute_Accent = 769, + U_Combining_Circumflex_Accent = 770, + U_Combining_Tilde = 771, + U_Combining_Macron = 772, + U_Combining_Overline = 773, + U_Combining_Breve = 774, + U_Combining_Dot_Above = 775, + U_Combining_Diaeresis = 776, + U_Combining_Hook_Above = 777, + U_Combining_Ring_Above = 778, + U_Combining_Double_Acute_Accent = 779, + U_Combining_Caron = 780, + U_Combining_Vertical_Line_Above = 781, + U_Combining_Double_Vertical_Line_Above = 782, + U_Combining_Double_Grave_Accent = 783, + U_Combining_Candrabindu = 784, + U_Combining_Inverted_Breve = 785, + U_Combining_Turned_Comma_Above = 786, + U_Combining_Comma_Above = 787, + U_Combining_Reversed_Comma_Above = 788, + U_Combining_Comma_Above_Right = 789, + U_Combining_Grave_Accent_Below = 790, + U_Combining_Acute_Accent_Below = 791, + U_Combining_Left_Tack_Below = 792, + U_Combining_Right_Tack_Below = 793, + U_Combining_Left_Angle_Above = 794, + U_Combining_Horn = 795, + U_Combining_Left_Half_Ring_Below = 796, + U_Combining_Up_Tack_Below = 797, + U_Combining_Down_Tack_Below = 798, + U_Combining_Plus_Sign_Below = 799, + U_Combining_Minus_Sign_Below = 800, + U_Combining_Palatalized_Hook_Below = 801, + U_Combining_Retroflex_Hook_Below = 802, + U_Combining_Dot_Below = 803, + U_Combining_Diaeresis_Below = 804, + U_Combining_Ring_Below = 805, + U_Combining_Comma_Below = 806, + U_Combining_Cedilla = 807, + U_Combining_Ogonek = 808, + U_Combining_Vertical_Line_Below = 809, + U_Combining_Bridge_Below = 810, + U_Combining_Inverted_Double_Arch_Below = 811, + U_Combining_Caron_Below = 812, + U_Combining_Circumflex_Accent_Below = 813, + U_Combining_Breve_Below = 814, + U_Combining_Inverted_Breve_Below = 815, + U_Combining_Tilde_Below = 816, + U_Combining_Macron_Below = 817, + U_Combining_Low_Line = 818, + U_Combining_Double_Low_Line = 819, + U_Combining_Tilde_Overlay = 820, + U_Combining_Short_Stroke_Overlay = 821, + U_Combining_Long_Stroke_Overlay = 822, + U_Combining_Short_Solidus_Overlay = 823, + U_Combining_Long_Solidus_Overlay = 824, + U_Combining_Right_Half_Ring_Below = 825, + U_Combining_Inverted_Bridge_Below = 826, + U_Combining_Square_Below = 827, + U_Combining_Seagull_Below = 828, + U_Combining_X_Above = 829, + U_Combining_Vertical_Tilde = 830, + U_Combining_Double_Overline = 831, + U_Combining_Grave_Tone_Mark = 832, + U_Combining_Acute_Tone_Mark = 833, + U_Combining_Greek_Perispomeni = 834, + U_Combining_Greek_Koronis = 835, + U_Combining_Greek_Dialytika_Tonos = 836, + U_Combining_Greek_Ypogegrammeni = 837, + U_Combining_Bridge_Above = 838, + U_Combining_Equals_Sign_Below = 839, + U_Combining_Double_Vertical_Line_Below = 840, + U_Combining_Left_Angle_Below = 841, + U_Combining_Not_Tilde_Above = 842, + U_Combining_Homothetic_Above = 843, + U_Combining_Almost_Equal_To_Above = 844, + U_Combining_Left_Right_Arrow_Below = 845, + U_Combining_Upwards_Arrow_Below = 846, + U_Combining_Grapheme_Joiner = 847, + U_Combining_Right_Arrowhead_Above = 848, + U_Combining_Left_Half_Ring_Above = 849, + U_Combining_Fermata = 850, + U_Combining_X_Below = 851, + U_Combining_Left_Arrowhead_Below = 852, + U_Combining_Right_Arrowhead_Below = 853, + U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 854, + U_Combining_Right_Half_Ring_Above = 855, + U_Combining_Dot_Above_Right = 856, + U_Combining_Asterisk_Below = 857, + U_Combining_Double_Ring_Below = 858, + U_Combining_Zigzag_Above = 859, + U_Combining_Double_Breve_Below = 860, + U_Combining_Double_Breve = 861, + U_Combining_Double_Macron = 862, + U_Combining_Double_Macron_Below = 863, + U_Combining_Double_Tilde = 864, + U_Combining_Double_Inverted_Breve = 865, + U_Combining_Double_Rightwards_Arrow_Below = 866, + U_Combining_Latin_Small_Letter_A = 867, + U_Combining_Latin_Small_Letter_E = 868, + U_Combining_Latin_Small_Letter_I = 869, + U_Combining_Latin_Small_Letter_O = 870, + U_Combining_Latin_Small_Letter_U = 871, + U_Combining_Latin_Small_Letter_C = 872, + U_Combining_Latin_Small_Letter_D = 873, + U_Combining_Latin_Small_Letter_H = 874, + U_Combining_Latin_Small_Letter_M = 875, + U_Combining_Latin_Small_Letter_R = 876, + U_Combining_Latin_Small_Letter_T = 877, + U_Combining_Latin_Small_Letter_V = 878, + U_Combining_Latin_Small_Letter_X = 879, + /** + * Unicode Character 'LINE SEPARATOR' (U+2028) + * http://www.fileformat.info/info/unicode/char/2028/index.htm + */ + LINE_SEPARATOR_2028 = 8232, + U_CIRCUMFLEX = 94, + U_GRAVE_ACCENT = 96, + U_DIAERESIS = 168, + U_MACRON = 175, + U_ACUTE_ACCENT = 180, + U_CEDILLA = 184, + U_MODIFIER_LETTER_LEFT_ARROWHEAD = 706, + U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 707, + U_MODIFIER_LETTER_UP_ARROWHEAD = 708, + U_MODIFIER_LETTER_DOWN_ARROWHEAD = 709, + U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 722, + U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 723, + U_MODIFIER_LETTER_UP_TACK = 724, + U_MODIFIER_LETTER_DOWN_TACK = 725, + U_MODIFIER_LETTER_PLUS_SIGN = 726, + U_MODIFIER_LETTER_MINUS_SIGN = 727, + U_BREVE = 728, + U_DOT_ABOVE = 729, + U_RING_ABOVE = 730, + U_OGONEK = 731, + U_SMALL_TILDE = 732, + U_DOUBLE_ACUTE_ACCENT = 733, + U_MODIFIER_LETTER_RHOTIC_HOOK = 734, + U_MODIFIER_LETTER_CROSS_ACCENT = 735, + U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 741, + U_MODIFIER_LETTER_HIGH_TONE_BAR = 742, + U_MODIFIER_LETTER_MID_TONE_BAR = 743, + U_MODIFIER_LETTER_LOW_TONE_BAR = 744, + U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 745, + U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 746, + U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 747, + U_MODIFIER_LETTER_UNASPIRATED = 749, + U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 751, + U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 752, + U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 753, + U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 754, + U_MODIFIER_LETTER_LOW_RING = 755, + U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 756, + U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 757, + U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 758, + U_MODIFIER_LETTER_LOW_TILDE = 759, + U_MODIFIER_LETTER_RAISED_COLON = 760, + U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 761, + U_MODIFIER_LETTER_END_HIGH_TONE = 762, + U_MODIFIER_LETTER_BEGIN_LOW_TONE = 763, + U_MODIFIER_LETTER_END_LOW_TONE = 764, + U_MODIFIER_LETTER_SHELF = 765, + U_MODIFIER_LETTER_OPEN_SHELF = 766, + U_MODIFIER_LETTER_LOW_LEFT_ARROW = 767, + U_GREEK_LOWER_NUMERAL_SIGN = 885, + U_GREEK_TONOS = 900, + U_GREEK_DIALYTIKA_TONOS = 901, + U_GREEK_KORONIS = 8125, + U_GREEK_PSILI = 8127, + U_GREEK_PERISPOMENI = 8128, + U_GREEK_DIALYTIKA_AND_PERISPOMENI = 8129, + U_GREEK_PSILI_AND_VARIA = 8141, + U_GREEK_PSILI_AND_OXIA = 8142, + U_GREEK_PSILI_AND_PERISPOMENI = 8143, + U_GREEK_DASIA_AND_VARIA = 8157, + U_GREEK_DASIA_AND_OXIA = 8158, + U_GREEK_DASIA_AND_PERISPOMENI = 8159, + U_GREEK_DIALYTIKA_AND_VARIA = 8173, + U_GREEK_DIALYTIKA_AND_OXIA = 8174, + U_GREEK_VARIA = 8175, + U_GREEK_OXIA = 8189, + U_GREEK_DASIA = 8190, + U_OVERLINE = 8254, + /** + * UTF-8 BOM + * Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF) + * http://www.fileformat.info/info/unicode/char/feff/index.htm + */ + UTF8_BOM = 65279 +} diff --git a/packages/core/dist/charCode.js b/packages/core/dist/charCode.js new file mode 100644 index 00000000..80a9db2c --- /dev/null +++ b/packages/core/dist/charCode.js @@ -0,0 +1,410 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +'use strict'; +// Names from https://blog.codinghorror.com/ascii-pronunciation-rules-for-programmers/ +/** + * An inlined enum containing useful character codes (to be used with String.charCodeAt). + * Please leave the const keyword such that it gets inlined when compiled to JavaScript! + */ +export var CharCode; +(function (CharCode) { + CharCode[CharCode["Null"] = 0] = "Null"; + /** + * The `\t` character. + */ + CharCode[CharCode["Tab"] = 9] = "Tab"; + /** + * The `\n` character. + */ + CharCode[CharCode["LineFeed"] = 10] = "LineFeed"; + /** + * The `\r` character. + */ + CharCode[CharCode["CarriageReturn"] = 13] = "CarriageReturn"; + CharCode[CharCode["Space"] = 32] = "Space"; + /** + * The `!` character. + */ + CharCode[CharCode["ExclamationMark"] = 33] = "ExclamationMark"; + /** + * The `"` character. + */ + CharCode[CharCode["DoubleQuote"] = 34] = "DoubleQuote"; + /** + * The `#` character. + */ + CharCode[CharCode["Hash"] = 35] = "Hash"; + /** + * The `$` character. + */ + CharCode[CharCode["DollarSign"] = 36] = "DollarSign"; + /** + * The `%` character. + */ + CharCode[CharCode["PercentSign"] = 37] = "PercentSign"; + /** + * The `&` character. + */ + CharCode[CharCode["Ampersand"] = 38] = "Ampersand"; + /** + * The `'` character. + */ + CharCode[CharCode["SingleQuote"] = 39] = "SingleQuote"; + /** + * The `(` character. + */ + CharCode[CharCode["OpenParen"] = 40] = "OpenParen"; + /** + * The `)` character. + */ + CharCode[CharCode["CloseParen"] = 41] = "CloseParen"; + /** + * The `*` character. + */ + CharCode[CharCode["Asterisk"] = 42] = "Asterisk"; + /** + * The `+` character. + */ + CharCode[CharCode["Plus"] = 43] = "Plus"; + /** + * The `,` character. + */ + CharCode[CharCode["Comma"] = 44] = "Comma"; + /** + * The `-` character. + */ + CharCode[CharCode["Dash"] = 45] = "Dash"; + /** + * The `.` character. + */ + CharCode[CharCode["Period"] = 46] = "Period"; + /** + * The `/` character. + */ + CharCode[CharCode["Slash"] = 47] = "Slash"; + CharCode[CharCode["Digit0"] = 48] = "Digit0"; + CharCode[CharCode["Digit1"] = 49] = "Digit1"; + CharCode[CharCode["Digit2"] = 50] = "Digit2"; + CharCode[CharCode["Digit3"] = 51] = "Digit3"; + CharCode[CharCode["Digit4"] = 52] = "Digit4"; + CharCode[CharCode["Digit5"] = 53] = "Digit5"; + CharCode[CharCode["Digit6"] = 54] = "Digit6"; + CharCode[CharCode["Digit7"] = 55] = "Digit7"; + CharCode[CharCode["Digit8"] = 56] = "Digit8"; + CharCode[CharCode["Digit9"] = 57] = "Digit9"; + /** + * The `:` character. + */ + CharCode[CharCode["Colon"] = 58] = "Colon"; + /** + * The `;` character. + */ + CharCode[CharCode["Semicolon"] = 59] = "Semicolon"; + /** + * The `<` character. + */ + CharCode[CharCode["LessThan"] = 60] = "LessThan"; + /** + * The `=` character. + */ + CharCode[CharCode["Equals"] = 61] = "Equals"; + /** + * The `>` character. + */ + CharCode[CharCode["GreaterThan"] = 62] = "GreaterThan"; + /** + * The `?` character. + */ + CharCode[CharCode["QuestionMark"] = 63] = "QuestionMark"; + /** + * The `@` character. + */ + CharCode[CharCode["AtSign"] = 64] = "AtSign"; + CharCode[CharCode["A"] = 65] = "A"; + CharCode[CharCode["B"] = 66] = "B"; + CharCode[CharCode["C"] = 67] = "C"; + CharCode[CharCode["D"] = 68] = "D"; + CharCode[CharCode["E"] = 69] = "E"; + CharCode[CharCode["F"] = 70] = "F"; + CharCode[CharCode["G"] = 71] = "G"; + CharCode[CharCode["H"] = 72] = "H"; + CharCode[CharCode["I"] = 73] = "I"; + CharCode[CharCode["J"] = 74] = "J"; + CharCode[CharCode["K"] = 75] = "K"; + CharCode[CharCode["L"] = 76] = "L"; + CharCode[CharCode["M"] = 77] = "M"; + CharCode[CharCode["N"] = 78] = "N"; + CharCode[CharCode["O"] = 79] = "O"; + CharCode[CharCode["P"] = 80] = "P"; + CharCode[CharCode["Q"] = 81] = "Q"; + CharCode[CharCode["R"] = 82] = "R"; + CharCode[CharCode["S"] = 83] = "S"; + CharCode[CharCode["T"] = 84] = "T"; + CharCode[CharCode["U"] = 85] = "U"; + CharCode[CharCode["V"] = 86] = "V"; + CharCode[CharCode["W"] = 87] = "W"; + CharCode[CharCode["X"] = 88] = "X"; + CharCode[CharCode["Y"] = 89] = "Y"; + CharCode[CharCode["Z"] = 90] = "Z"; + /** + * The `[` character. + */ + CharCode[CharCode["OpenSquareBracket"] = 91] = "OpenSquareBracket"; + /** + * The `\` character. + */ + CharCode[CharCode["Backslash"] = 92] = "Backslash"; + /** + * The `]` character. + */ + CharCode[CharCode["CloseSquareBracket"] = 93] = "CloseSquareBracket"; + /** + * The `^` character. + */ + CharCode[CharCode["Caret"] = 94] = "Caret"; + /** + * The `_` character. + */ + CharCode[CharCode["Underline"] = 95] = "Underline"; + /** + * The ``(`)`` character. + */ + CharCode[CharCode["BackTick"] = 96] = "BackTick"; + CharCode[CharCode["a"] = 97] = "a"; + CharCode[CharCode["b"] = 98] = "b"; + CharCode[CharCode["c"] = 99] = "c"; + CharCode[CharCode["d"] = 100] = "d"; + CharCode[CharCode["e"] = 101] = "e"; + CharCode[CharCode["f"] = 102] = "f"; + CharCode[CharCode["g"] = 103] = "g"; + CharCode[CharCode["h"] = 104] = "h"; + CharCode[CharCode["i"] = 105] = "i"; + CharCode[CharCode["j"] = 106] = "j"; + CharCode[CharCode["k"] = 107] = "k"; + CharCode[CharCode["l"] = 108] = "l"; + CharCode[CharCode["m"] = 109] = "m"; + CharCode[CharCode["n"] = 110] = "n"; + CharCode[CharCode["o"] = 111] = "o"; + CharCode[CharCode["p"] = 112] = "p"; + CharCode[CharCode["q"] = 113] = "q"; + CharCode[CharCode["r"] = 114] = "r"; + CharCode[CharCode["s"] = 115] = "s"; + CharCode[CharCode["t"] = 116] = "t"; + CharCode[CharCode["u"] = 117] = "u"; + CharCode[CharCode["v"] = 118] = "v"; + CharCode[CharCode["w"] = 119] = "w"; + CharCode[CharCode["x"] = 120] = "x"; + CharCode[CharCode["y"] = 121] = "y"; + CharCode[CharCode["z"] = 122] = "z"; + /** + * The `{` character. + */ + CharCode[CharCode["OpenCurlyBrace"] = 123] = "OpenCurlyBrace"; + /** + * The `|` character. + */ + CharCode[CharCode["Pipe"] = 124] = "Pipe"; + /** + * The `}` character. + */ + CharCode[CharCode["CloseCurlyBrace"] = 125] = "CloseCurlyBrace"; + /** + * The `~` character. + */ + CharCode[CharCode["Tilde"] = 126] = "Tilde"; + CharCode[CharCode["U_Combining_Grave_Accent"] = 768] = "U_Combining_Grave_Accent"; + CharCode[CharCode["U_Combining_Acute_Accent"] = 769] = "U_Combining_Acute_Accent"; + CharCode[CharCode["U_Combining_Circumflex_Accent"] = 770] = "U_Combining_Circumflex_Accent"; + CharCode[CharCode["U_Combining_Tilde"] = 771] = "U_Combining_Tilde"; + CharCode[CharCode["U_Combining_Macron"] = 772] = "U_Combining_Macron"; + CharCode[CharCode["U_Combining_Overline"] = 773] = "U_Combining_Overline"; + CharCode[CharCode["U_Combining_Breve"] = 774] = "U_Combining_Breve"; + CharCode[CharCode["U_Combining_Dot_Above"] = 775] = "U_Combining_Dot_Above"; + CharCode[CharCode["U_Combining_Diaeresis"] = 776] = "U_Combining_Diaeresis"; + CharCode[CharCode["U_Combining_Hook_Above"] = 777] = "U_Combining_Hook_Above"; + CharCode[CharCode["U_Combining_Ring_Above"] = 778] = "U_Combining_Ring_Above"; + CharCode[CharCode["U_Combining_Double_Acute_Accent"] = 779] = "U_Combining_Double_Acute_Accent"; + CharCode[CharCode["U_Combining_Caron"] = 780] = "U_Combining_Caron"; + CharCode[CharCode["U_Combining_Vertical_Line_Above"] = 781] = "U_Combining_Vertical_Line_Above"; + CharCode[CharCode["U_Combining_Double_Vertical_Line_Above"] = 782] = "U_Combining_Double_Vertical_Line_Above"; + CharCode[CharCode["U_Combining_Double_Grave_Accent"] = 783] = "U_Combining_Double_Grave_Accent"; + CharCode[CharCode["U_Combining_Candrabindu"] = 784] = "U_Combining_Candrabindu"; + CharCode[CharCode["U_Combining_Inverted_Breve"] = 785] = "U_Combining_Inverted_Breve"; + CharCode[CharCode["U_Combining_Turned_Comma_Above"] = 786] = "U_Combining_Turned_Comma_Above"; + CharCode[CharCode["U_Combining_Comma_Above"] = 787] = "U_Combining_Comma_Above"; + CharCode[CharCode["U_Combining_Reversed_Comma_Above"] = 788] = "U_Combining_Reversed_Comma_Above"; + CharCode[CharCode["U_Combining_Comma_Above_Right"] = 789] = "U_Combining_Comma_Above_Right"; + CharCode[CharCode["U_Combining_Grave_Accent_Below"] = 790] = "U_Combining_Grave_Accent_Below"; + CharCode[CharCode["U_Combining_Acute_Accent_Below"] = 791] = "U_Combining_Acute_Accent_Below"; + CharCode[CharCode["U_Combining_Left_Tack_Below"] = 792] = "U_Combining_Left_Tack_Below"; + CharCode[CharCode["U_Combining_Right_Tack_Below"] = 793] = "U_Combining_Right_Tack_Below"; + CharCode[CharCode["U_Combining_Left_Angle_Above"] = 794] = "U_Combining_Left_Angle_Above"; + CharCode[CharCode["U_Combining_Horn"] = 795] = "U_Combining_Horn"; + CharCode[CharCode["U_Combining_Left_Half_Ring_Below"] = 796] = "U_Combining_Left_Half_Ring_Below"; + CharCode[CharCode["U_Combining_Up_Tack_Below"] = 797] = "U_Combining_Up_Tack_Below"; + CharCode[CharCode["U_Combining_Down_Tack_Below"] = 798] = "U_Combining_Down_Tack_Below"; + CharCode[CharCode["U_Combining_Plus_Sign_Below"] = 799] = "U_Combining_Plus_Sign_Below"; + CharCode[CharCode["U_Combining_Minus_Sign_Below"] = 800] = "U_Combining_Minus_Sign_Below"; + CharCode[CharCode["U_Combining_Palatalized_Hook_Below"] = 801] = "U_Combining_Palatalized_Hook_Below"; + CharCode[CharCode["U_Combining_Retroflex_Hook_Below"] = 802] = "U_Combining_Retroflex_Hook_Below"; + CharCode[CharCode["U_Combining_Dot_Below"] = 803] = "U_Combining_Dot_Below"; + CharCode[CharCode["U_Combining_Diaeresis_Below"] = 804] = "U_Combining_Diaeresis_Below"; + CharCode[CharCode["U_Combining_Ring_Below"] = 805] = "U_Combining_Ring_Below"; + CharCode[CharCode["U_Combining_Comma_Below"] = 806] = "U_Combining_Comma_Below"; + CharCode[CharCode["U_Combining_Cedilla"] = 807] = "U_Combining_Cedilla"; + CharCode[CharCode["U_Combining_Ogonek"] = 808] = "U_Combining_Ogonek"; + CharCode[CharCode["U_Combining_Vertical_Line_Below"] = 809] = "U_Combining_Vertical_Line_Below"; + CharCode[CharCode["U_Combining_Bridge_Below"] = 810] = "U_Combining_Bridge_Below"; + CharCode[CharCode["U_Combining_Inverted_Double_Arch_Below"] = 811] = "U_Combining_Inverted_Double_Arch_Below"; + CharCode[CharCode["U_Combining_Caron_Below"] = 812] = "U_Combining_Caron_Below"; + CharCode[CharCode["U_Combining_Circumflex_Accent_Below"] = 813] = "U_Combining_Circumflex_Accent_Below"; + CharCode[CharCode["U_Combining_Breve_Below"] = 814] = "U_Combining_Breve_Below"; + CharCode[CharCode["U_Combining_Inverted_Breve_Below"] = 815] = "U_Combining_Inverted_Breve_Below"; + CharCode[CharCode["U_Combining_Tilde_Below"] = 816] = "U_Combining_Tilde_Below"; + CharCode[CharCode["U_Combining_Macron_Below"] = 817] = "U_Combining_Macron_Below"; + CharCode[CharCode["U_Combining_Low_Line"] = 818] = "U_Combining_Low_Line"; + CharCode[CharCode["U_Combining_Double_Low_Line"] = 819] = "U_Combining_Double_Low_Line"; + CharCode[CharCode["U_Combining_Tilde_Overlay"] = 820] = "U_Combining_Tilde_Overlay"; + CharCode[CharCode["U_Combining_Short_Stroke_Overlay"] = 821] = "U_Combining_Short_Stroke_Overlay"; + CharCode[CharCode["U_Combining_Long_Stroke_Overlay"] = 822] = "U_Combining_Long_Stroke_Overlay"; + CharCode[CharCode["U_Combining_Short_Solidus_Overlay"] = 823] = "U_Combining_Short_Solidus_Overlay"; + CharCode[CharCode["U_Combining_Long_Solidus_Overlay"] = 824] = "U_Combining_Long_Solidus_Overlay"; + CharCode[CharCode["U_Combining_Right_Half_Ring_Below"] = 825] = "U_Combining_Right_Half_Ring_Below"; + CharCode[CharCode["U_Combining_Inverted_Bridge_Below"] = 826] = "U_Combining_Inverted_Bridge_Below"; + CharCode[CharCode["U_Combining_Square_Below"] = 827] = "U_Combining_Square_Below"; + CharCode[CharCode["U_Combining_Seagull_Below"] = 828] = "U_Combining_Seagull_Below"; + CharCode[CharCode["U_Combining_X_Above"] = 829] = "U_Combining_X_Above"; + CharCode[CharCode["U_Combining_Vertical_Tilde"] = 830] = "U_Combining_Vertical_Tilde"; + CharCode[CharCode["U_Combining_Double_Overline"] = 831] = "U_Combining_Double_Overline"; + CharCode[CharCode["U_Combining_Grave_Tone_Mark"] = 832] = "U_Combining_Grave_Tone_Mark"; + CharCode[CharCode["U_Combining_Acute_Tone_Mark"] = 833] = "U_Combining_Acute_Tone_Mark"; + CharCode[CharCode["U_Combining_Greek_Perispomeni"] = 834] = "U_Combining_Greek_Perispomeni"; + CharCode[CharCode["U_Combining_Greek_Koronis"] = 835] = "U_Combining_Greek_Koronis"; + CharCode[CharCode["U_Combining_Greek_Dialytika_Tonos"] = 836] = "U_Combining_Greek_Dialytika_Tonos"; + CharCode[CharCode["U_Combining_Greek_Ypogegrammeni"] = 837] = "U_Combining_Greek_Ypogegrammeni"; + CharCode[CharCode["U_Combining_Bridge_Above"] = 838] = "U_Combining_Bridge_Above"; + CharCode[CharCode["U_Combining_Equals_Sign_Below"] = 839] = "U_Combining_Equals_Sign_Below"; + CharCode[CharCode["U_Combining_Double_Vertical_Line_Below"] = 840] = "U_Combining_Double_Vertical_Line_Below"; + CharCode[CharCode["U_Combining_Left_Angle_Below"] = 841] = "U_Combining_Left_Angle_Below"; + CharCode[CharCode["U_Combining_Not_Tilde_Above"] = 842] = "U_Combining_Not_Tilde_Above"; + CharCode[CharCode["U_Combining_Homothetic_Above"] = 843] = "U_Combining_Homothetic_Above"; + CharCode[CharCode["U_Combining_Almost_Equal_To_Above"] = 844] = "U_Combining_Almost_Equal_To_Above"; + CharCode[CharCode["U_Combining_Left_Right_Arrow_Below"] = 845] = "U_Combining_Left_Right_Arrow_Below"; + CharCode[CharCode["U_Combining_Upwards_Arrow_Below"] = 846] = "U_Combining_Upwards_Arrow_Below"; + CharCode[CharCode["U_Combining_Grapheme_Joiner"] = 847] = "U_Combining_Grapheme_Joiner"; + CharCode[CharCode["U_Combining_Right_Arrowhead_Above"] = 848] = "U_Combining_Right_Arrowhead_Above"; + CharCode[CharCode["U_Combining_Left_Half_Ring_Above"] = 849] = "U_Combining_Left_Half_Ring_Above"; + CharCode[CharCode["U_Combining_Fermata"] = 850] = "U_Combining_Fermata"; + CharCode[CharCode["U_Combining_X_Below"] = 851] = "U_Combining_X_Below"; + CharCode[CharCode["U_Combining_Left_Arrowhead_Below"] = 852] = "U_Combining_Left_Arrowhead_Below"; + CharCode[CharCode["U_Combining_Right_Arrowhead_Below"] = 853] = "U_Combining_Right_Arrowhead_Below"; + CharCode[CharCode["U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below"] = 854] = "U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below"; + CharCode[CharCode["U_Combining_Right_Half_Ring_Above"] = 855] = "U_Combining_Right_Half_Ring_Above"; + CharCode[CharCode["U_Combining_Dot_Above_Right"] = 856] = "U_Combining_Dot_Above_Right"; + CharCode[CharCode["U_Combining_Asterisk_Below"] = 857] = "U_Combining_Asterisk_Below"; + CharCode[CharCode["U_Combining_Double_Ring_Below"] = 858] = "U_Combining_Double_Ring_Below"; + CharCode[CharCode["U_Combining_Zigzag_Above"] = 859] = "U_Combining_Zigzag_Above"; + CharCode[CharCode["U_Combining_Double_Breve_Below"] = 860] = "U_Combining_Double_Breve_Below"; + CharCode[CharCode["U_Combining_Double_Breve"] = 861] = "U_Combining_Double_Breve"; + CharCode[CharCode["U_Combining_Double_Macron"] = 862] = "U_Combining_Double_Macron"; + CharCode[CharCode["U_Combining_Double_Macron_Below"] = 863] = "U_Combining_Double_Macron_Below"; + CharCode[CharCode["U_Combining_Double_Tilde"] = 864] = "U_Combining_Double_Tilde"; + CharCode[CharCode["U_Combining_Double_Inverted_Breve"] = 865] = "U_Combining_Double_Inverted_Breve"; + CharCode[CharCode["U_Combining_Double_Rightwards_Arrow_Below"] = 866] = "U_Combining_Double_Rightwards_Arrow_Below"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_A"] = 867] = "U_Combining_Latin_Small_Letter_A"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_E"] = 868] = "U_Combining_Latin_Small_Letter_E"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_I"] = 869] = "U_Combining_Latin_Small_Letter_I"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_O"] = 870] = "U_Combining_Latin_Small_Letter_O"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_U"] = 871] = "U_Combining_Latin_Small_Letter_U"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_C"] = 872] = "U_Combining_Latin_Small_Letter_C"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_D"] = 873] = "U_Combining_Latin_Small_Letter_D"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_H"] = 874] = "U_Combining_Latin_Small_Letter_H"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_M"] = 875] = "U_Combining_Latin_Small_Letter_M"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_R"] = 876] = "U_Combining_Latin_Small_Letter_R"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_T"] = 877] = "U_Combining_Latin_Small_Letter_T"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_V"] = 878] = "U_Combining_Latin_Small_Letter_V"; + CharCode[CharCode["U_Combining_Latin_Small_Letter_X"] = 879] = "U_Combining_Latin_Small_Letter_X"; + /** + * Unicode Character 'LINE SEPARATOR' (U+2028) + * http://www.fileformat.info/info/unicode/char/2028/index.htm + */ + CharCode[CharCode["LINE_SEPARATOR_2028"] = 8232] = "LINE_SEPARATOR_2028"; + // http://www.fileformat.info/info/unicode/category/Sk/list.htm + CharCode[CharCode["U_CIRCUMFLEX"] = 94] = "U_CIRCUMFLEX"; + CharCode[CharCode["U_GRAVE_ACCENT"] = 96] = "U_GRAVE_ACCENT"; + CharCode[CharCode["U_DIAERESIS"] = 168] = "U_DIAERESIS"; + CharCode[CharCode["U_MACRON"] = 175] = "U_MACRON"; + CharCode[CharCode["U_ACUTE_ACCENT"] = 180] = "U_ACUTE_ACCENT"; + CharCode[CharCode["U_CEDILLA"] = 184] = "U_CEDILLA"; + CharCode[CharCode["U_MODIFIER_LETTER_LEFT_ARROWHEAD"] = 706] = "U_MODIFIER_LETTER_LEFT_ARROWHEAD"; + CharCode[CharCode["U_MODIFIER_LETTER_RIGHT_ARROWHEAD"] = 707] = "U_MODIFIER_LETTER_RIGHT_ARROWHEAD"; + CharCode[CharCode["U_MODIFIER_LETTER_UP_ARROWHEAD"] = 708] = "U_MODIFIER_LETTER_UP_ARROWHEAD"; + CharCode[CharCode["U_MODIFIER_LETTER_DOWN_ARROWHEAD"] = 709] = "U_MODIFIER_LETTER_DOWN_ARROWHEAD"; + CharCode[CharCode["U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING"] = 722] = "U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING"; + CharCode[CharCode["U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING"] = 723] = "U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING"; + CharCode[CharCode["U_MODIFIER_LETTER_UP_TACK"] = 724] = "U_MODIFIER_LETTER_UP_TACK"; + CharCode[CharCode["U_MODIFIER_LETTER_DOWN_TACK"] = 725] = "U_MODIFIER_LETTER_DOWN_TACK"; + CharCode[CharCode["U_MODIFIER_LETTER_PLUS_SIGN"] = 726] = "U_MODIFIER_LETTER_PLUS_SIGN"; + CharCode[CharCode["U_MODIFIER_LETTER_MINUS_SIGN"] = 727] = "U_MODIFIER_LETTER_MINUS_SIGN"; + CharCode[CharCode["U_BREVE"] = 728] = "U_BREVE"; + CharCode[CharCode["U_DOT_ABOVE"] = 729] = "U_DOT_ABOVE"; + CharCode[CharCode["U_RING_ABOVE"] = 730] = "U_RING_ABOVE"; + CharCode[CharCode["U_OGONEK"] = 731] = "U_OGONEK"; + CharCode[CharCode["U_SMALL_TILDE"] = 732] = "U_SMALL_TILDE"; + CharCode[CharCode["U_DOUBLE_ACUTE_ACCENT"] = 733] = "U_DOUBLE_ACUTE_ACCENT"; + CharCode[CharCode["U_MODIFIER_LETTER_RHOTIC_HOOK"] = 734] = "U_MODIFIER_LETTER_RHOTIC_HOOK"; + CharCode[CharCode["U_MODIFIER_LETTER_CROSS_ACCENT"] = 735] = "U_MODIFIER_LETTER_CROSS_ACCENT"; + CharCode[CharCode["U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR"] = 741] = "U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR"; + CharCode[CharCode["U_MODIFIER_LETTER_HIGH_TONE_BAR"] = 742] = "U_MODIFIER_LETTER_HIGH_TONE_BAR"; + CharCode[CharCode["U_MODIFIER_LETTER_MID_TONE_BAR"] = 743] = "U_MODIFIER_LETTER_MID_TONE_BAR"; + CharCode[CharCode["U_MODIFIER_LETTER_LOW_TONE_BAR"] = 744] = "U_MODIFIER_LETTER_LOW_TONE_BAR"; + CharCode[CharCode["U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR"] = 745] = "U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR"; + CharCode[CharCode["U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK"] = 746] = "U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK"; + CharCode[CharCode["U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK"] = 747] = "U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK"; + CharCode[CharCode["U_MODIFIER_LETTER_UNASPIRATED"] = 749] = "U_MODIFIER_LETTER_UNASPIRATED"; + CharCode[CharCode["U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD"] = 751] = "U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD"; + CharCode[CharCode["U_MODIFIER_LETTER_LOW_UP_ARROWHEAD"] = 752] = "U_MODIFIER_LETTER_LOW_UP_ARROWHEAD"; + CharCode[CharCode["U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD"] = 753] = "U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD"; + CharCode[CharCode["U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD"] = 754] = "U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD"; + CharCode[CharCode["U_MODIFIER_LETTER_LOW_RING"] = 755] = "U_MODIFIER_LETTER_LOW_RING"; + CharCode[CharCode["U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT"] = 756] = "U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT"; + CharCode[CharCode["U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT"] = 757] = "U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT"; + CharCode[CharCode["U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT"] = 758] = "U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT"; + CharCode[CharCode["U_MODIFIER_LETTER_LOW_TILDE"] = 759] = "U_MODIFIER_LETTER_LOW_TILDE"; + CharCode[CharCode["U_MODIFIER_LETTER_RAISED_COLON"] = 760] = "U_MODIFIER_LETTER_RAISED_COLON"; + CharCode[CharCode["U_MODIFIER_LETTER_BEGIN_HIGH_TONE"] = 761] = "U_MODIFIER_LETTER_BEGIN_HIGH_TONE"; + CharCode[CharCode["U_MODIFIER_LETTER_END_HIGH_TONE"] = 762] = "U_MODIFIER_LETTER_END_HIGH_TONE"; + CharCode[CharCode["U_MODIFIER_LETTER_BEGIN_LOW_TONE"] = 763] = "U_MODIFIER_LETTER_BEGIN_LOW_TONE"; + CharCode[CharCode["U_MODIFIER_LETTER_END_LOW_TONE"] = 764] = "U_MODIFIER_LETTER_END_LOW_TONE"; + CharCode[CharCode["U_MODIFIER_LETTER_SHELF"] = 765] = "U_MODIFIER_LETTER_SHELF"; + CharCode[CharCode["U_MODIFIER_LETTER_OPEN_SHELF"] = 766] = "U_MODIFIER_LETTER_OPEN_SHELF"; + CharCode[CharCode["U_MODIFIER_LETTER_LOW_LEFT_ARROW"] = 767] = "U_MODIFIER_LETTER_LOW_LEFT_ARROW"; + CharCode[CharCode["U_GREEK_LOWER_NUMERAL_SIGN"] = 885] = "U_GREEK_LOWER_NUMERAL_SIGN"; + CharCode[CharCode["U_GREEK_TONOS"] = 900] = "U_GREEK_TONOS"; + CharCode[CharCode["U_GREEK_DIALYTIKA_TONOS"] = 901] = "U_GREEK_DIALYTIKA_TONOS"; + CharCode[CharCode["U_GREEK_KORONIS"] = 8125] = "U_GREEK_KORONIS"; + CharCode[CharCode["U_GREEK_PSILI"] = 8127] = "U_GREEK_PSILI"; + CharCode[CharCode["U_GREEK_PERISPOMENI"] = 8128] = "U_GREEK_PERISPOMENI"; + CharCode[CharCode["U_GREEK_DIALYTIKA_AND_PERISPOMENI"] = 8129] = "U_GREEK_DIALYTIKA_AND_PERISPOMENI"; + CharCode[CharCode["U_GREEK_PSILI_AND_VARIA"] = 8141] = "U_GREEK_PSILI_AND_VARIA"; + CharCode[CharCode["U_GREEK_PSILI_AND_OXIA"] = 8142] = "U_GREEK_PSILI_AND_OXIA"; + CharCode[CharCode["U_GREEK_PSILI_AND_PERISPOMENI"] = 8143] = "U_GREEK_PSILI_AND_PERISPOMENI"; + CharCode[CharCode["U_GREEK_DASIA_AND_VARIA"] = 8157] = "U_GREEK_DASIA_AND_VARIA"; + CharCode[CharCode["U_GREEK_DASIA_AND_OXIA"] = 8158] = "U_GREEK_DASIA_AND_OXIA"; + CharCode[CharCode["U_GREEK_DASIA_AND_PERISPOMENI"] = 8159] = "U_GREEK_DASIA_AND_PERISPOMENI"; + CharCode[CharCode["U_GREEK_DIALYTIKA_AND_VARIA"] = 8173] = "U_GREEK_DIALYTIKA_AND_VARIA"; + CharCode[CharCode["U_GREEK_DIALYTIKA_AND_OXIA"] = 8174] = "U_GREEK_DIALYTIKA_AND_OXIA"; + CharCode[CharCode["U_GREEK_VARIA"] = 8175] = "U_GREEK_VARIA"; + CharCode[CharCode["U_GREEK_OXIA"] = 8189] = "U_GREEK_OXIA"; + CharCode[CharCode["U_GREEK_DASIA"] = 8190] = "U_GREEK_DASIA"; + CharCode[CharCode["U_OVERLINE"] = 8254] = "U_OVERLINE"; + /** + * UTF-8 BOM + * Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF) + * http://www.fileformat.info/info/unicode/char/feff/index.htm + */ + CharCode[CharCode["UTF8_BOM"] = 65279] = "UTF8_BOM"; +})(CharCode = CharCode || (CharCode = {})); +//# sourceMappingURL=charCode.js.map \ No newline at end of file diff --git a/packages/core/dist/charCode.js.map b/packages/core/dist/charCode.js.map new file mode 100644 index 00000000..06dc6bf3 --- /dev/null +++ b/packages/core/dist/charCode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"charCode.js","sourceRoot":"","sources":["../src/charCode.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAChG,YAAY,CAAC;AAEb,sFAAsF;AAEtF;;;GAGG;AACH,MAAM,CAAN,IAAkB,QAyZjB;AAzZD,WAAkB,QAAQ;IACzB,uCAAQ,CAAA;IACR;;OAEG;IACH,qCAAO,CAAA;IACP;;OAEG;IACH,gDAAa,CAAA;IACb;;OAEG;IACH,4DAAmB,CAAA;IACnB,0CAAU,CAAA;IACV;;OAEG;IACH,8DAAoB,CAAA;IACpB;;OAEG;IACH,sDAAgB,CAAA;IAChB;;OAEG;IACH,wCAAS,CAAA;IACT;;OAEG;IACH,oDAAe,CAAA;IACf;;OAEG;IACH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A;IACvC,yGAA6C,CAAA;IAC7C,mHAAkD,CAAA;IAClD,qHAAmD,CAAA;IACnD,2FAAsC,CAAA;IACtC,yGAA6C,CAAA;IAC7C,qGAA2C,CAAA;IAC3C,yGAA6C,CAAA;IAC7C,2GAA8C,CAAA;IAC9C,qFAAmC,CAAA;IACnC,2GAA8C,CAAA;IAC9C,yHAAqD,CAAA;IACrD,yHAAqD,CAAA;IACrD,uFAAoC,CAAA;IACpC,6FAAuC,CAAA;IACvC,mGAA0C,CAAA;IAC1C,+FAAwC,CAAA;IACxC,iGAAyC,CAAA;IACzC,6FAAuC,CAAA;IACvC,+EAAgC,CAAA;IAChC,yFAAqC,CAAA;IACrC,iGAAyC,CAAA;IACzC,qFAAmC,CAAA;IACnC,2DAAsB,CAAA;IACtB,+EAAgC,CAAA;IAChC,gEAAwB,CAAA;IACxB,4DAAsB,CAAA;IACtB,wEAA4B,CAAA;IAC5B,oGAA0C,CAAA;IAC1C,gFAAgC,CAAA;IAChC,8EAA+B,CAAA;IAC/B,4FAAsC,CAAA;IACtC,gFAAgC,CAAA;IAChC,8EAA+B,CAAA;IAC/B,4FAAsC,CAAA;IACtC,wFAAoC,CAAA;IACpC,sFAAmC,CAAA;IACnC,4DAAsB,CAAA;IACtB,0DAAqB,CAAA;IACrB,4DAAsB,CAAA;IAGtB,sDAAmB,CAAA;IAEnB;;;;OAIG;IACH,mDAAgB,CAAA;AACjB,CAAC,EAzZiB,QAAQ,GAAR,QAAQ,KAAR,QAAQ,QAyZzB"} \ No newline at end of file diff --git a/packages/core/dist/collections.d.ts b/packages/core/dist/collections.d.ts new file mode 100644 index 00000000..2fde39d0 --- /dev/null +++ b/packages/core/dist/collections.d.ts @@ -0,0 +1,47 @@ +/** + * An interface for a JavaScript object that + * acts a dictionary. The keys are strings. + */ +export type IStringDictionary = Record; +/** + * An interface for a JavaScript object that + * acts a dictionary. The keys are numbers. + */ +export type INumberDictionary = Record; +/** + * Groups the collection into a dictionary based on the provided + * group function. + */ +export declare function groupBy(data: V[], groupFn: (element: V) => K): Record; +export declare function diffSets(before: ReadonlySet, after: ReadonlySet): { + removed: T[]; + added: T[]; +}; +export declare function diffMaps(before: Map, after: Map): { + removed: V[]; + added: V[]; +}; +/** + * Computes the intersection of two sets. + * + * @param setA - The first set. + * @param setB - The second iterable. + * @returns A new set containing the elements that are in both `setA` and `setB`. + */ +export declare function intersection(setA: Set, setB: Iterable): Set; +export declare class SetWithKey implements Set { + private toKey; + private _map; + constructor(values: T[], toKey: (t: T) => unknown); + get size(): number; + add(value: T): this; + delete(value: T): boolean; + has(value: T): boolean; + entries(): IterableIterator<[T, T]>; + keys(): IterableIterator; + values(): IterableIterator; + clear(): void; + forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; + [Symbol.iterator](): IterableIterator; + [Symbol.toStringTag]: string; +} diff --git a/packages/core/dist/collections.js b/packages/core/dist/collections.js new file mode 100644 index 00000000..b9208005 --- /dev/null +++ b/packages/core/dist/collections.js @@ -0,0 +1,114 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +/** + * Groups the collection into a dictionary based on the provided + * group function. + */ +export function groupBy(data, groupFn) { + const result = Object.create(null); + for (const element of data) { + const key = groupFn(element); + let target = result[key]; + if (!target) { + target = result[key] = []; + } + target.push(element); + } + return result; +} +export function diffSets(before, after) { + const removed = []; + const added = []; + for (const element of before) { + if (!after.has(element)) { + removed.push(element); + } + } + for (const element of after) { + if (!before.has(element)) { + added.push(element); + } + } + return { removed, added }; +} +export function diffMaps(before, after) { + const removed = []; + const added = []; + for (const [index, value] of before) { + if (!after.has(index)) { + removed.push(value); + } + } + for (const [index, value] of after) { + if (!before.has(index)) { + added.push(value); + } + } + return { removed, added }; +} +/** + * Computes the intersection of two sets. + * + * @param setA - The first set. + * @param setB - The second iterable. + * @returns A new set containing the elements that are in both `setA` and `setB`. + */ +export function intersection(setA, setB) { + const result = new Set(); + for (const elem of setB) { + if (setA.has(elem)) { + result.add(elem); + } + } + return result; +} +export class SetWithKey { + toKey; + _map = new Map(); + constructor(values, toKey) { + this.toKey = toKey; + for (const value of values) { + this.add(value); + } + } + get size() { + return this._map.size; + } + add(value) { + const key = this.toKey(value); + this._map.set(key, value); + return this; + } + delete(value) { + return this._map.delete(this.toKey(value)); + } + has(value) { + return this._map.has(this.toKey(value)); + } + *entries() { + for (const entry of this._map.values()) { + yield [entry, entry]; + } + } + keys() { + return this.values(); + } + *values() { + for (const entry of this._map.values()) { + yield entry; + } + } + clear() { + this._map.clear(); + } + forEach(callbackfn, thisArg) { + this._map.forEach(entry => callbackfn.call(thisArg, entry, entry, this)); + } + [Symbol.iterator]() { + return this.values(); + } + [Symbol.toStringTag] = 'SetWithKey'; +} +//# sourceMappingURL=collections.js.map \ No newline at end of file diff --git a/packages/core/dist/collections.js.map b/packages/core/dist/collections.js.map new file mode 100644 index 00000000..233d8f47 --- /dev/null +++ b/packages/core/dist/collections.js.map @@ -0,0 +1 @@ +{"version":3,"file":"collections.js","sourceRoot":"","sources":["../src/collections.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAchG;;;GAGG;AACH,MAAM,UAAU,OAAO,CAAwC,IAAS,EAAE,OAA0B;IACnG,MAAM,MAAM,GAAmB,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACnD,KAAK,MAAM,OAAO,IAAI,IAAI,EAAE;QAC3B,MAAM,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;QAC7B,IAAI,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;QACzB,IAAI,CAAC,MAAM,EAAE;YACZ,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;SAC1B;QACD,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;KACrB;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,QAAQ,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F,CAAC;IAED,KAAK;QACJ,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;IAED,OAAO,CAAC,UAAsD,EAAE,OAAa;QAC5E,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IAC1E,CAAC;IAED,CAAC,MAAM,CAAC,QAAQ,CAAC;QAChB,OAAO,IAAI,CAAC,MAAM,EAAE,CAAC;IACtB,CAAC;IAED,CAAC,MAAM,CAAC,WAAW,CAAC,GAAW,YAAY,CAAC;CAC5C"} \ No newline at end of file diff --git a/packages/core/dist/constants.d.ts b/packages/core/dist/constants.d.ts new file mode 100644 index 00000000..cfd4a271 --- /dev/null +++ b/packages/core/dist/constants.d.ts @@ -0,0 +1,2 @@ +export declare const REGEX_VAR: RegExp; +export declare const REGEX_VAR_ALT: RegExp; diff --git a/packages/core/dist/constants.js b/packages/core/dist/constants.js new file mode 100644 index 00000000..5a6047a7 --- /dev/null +++ b/packages/core/dist/constants.js @@ -0,0 +1,6 @@ +// standard expression for variables, eg : ${foo} +export const REGEX_VAR = /\$\{([^\s:}]+)(?::([^\s:}]+))?\}/g; +// alternate expression for variables, eg : %{foo}. this is required +// to deal with parent expression parsers where '$' is reserved, eg: %{my_var} +export const REGEX_VAR_ALT = /&\{([^\s:}]+)(?::([^\s:}]+))?\}/g; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/packages/core/dist/constants.js.map b/packages/core/dist/constants.js.map new file mode 100644 index 00000000..d2d9bf60 --- /dev/null +++ b/packages/core/dist/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,iDAAiD;AACjD,MAAM,CAAC,MAAM,SAAS,GAAG,mCAAmC,CAAA;AAE5D,oEAAoE;AACpE,8EAA8E;AAC9E,MAAM,CAAC,MAAM,aAAa,GAAG,kCAAkC,CAAA"} \ No newline at end of file diff --git a/packages/core/dist/equals.d.ts b/packages/core/dist/equals.d.ts new file mode 100644 index 00000000..433bacec --- /dev/null +++ b/packages/core/dist/equals.d.ts @@ -0,0 +1,37 @@ +export type EqualityComparer = (a: T, b: T) => boolean; +/** + * Compares two items for equality using strict equality. +*/ +export declare const strictEquals: EqualityComparer; +/** + * Checks if the items of two arrays are equal. + * By default, strict equality is used to compare elements, but a custom equality comparer can be provided. + */ +export declare function itemsEquals(itemEquals?: EqualityComparer): EqualityComparer; +/** + * Two items are considered equal, if their stringified representations are equal. +*/ +export declare function jsonStringifyEquals(): EqualityComparer; +/** + * Uses `item.equals(other)` to determine equality. + */ +export declare function itemEquals(): EqualityComparer; +/** + * Checks if two items are both null or undefined, or are equal according to the provided equality comparer. +*/ +export declare function equalsIfDefined(v1: T | undefined | null, v2: T | undefined | null, equals: EqualityComparer): boolean; +/** + * Returns an equality comparer that checks if two items are both null or undefined, or are equal according to the provided equality comparer. +*/ +export declare function equalsIfDefined(equals: EqualityComparer): EqualityComparer; +/** + * Drills into arrays (items ordered) and objects (keys unordered) and uses strict equality on everything else. +*/ +export declare function structuralEquals(a: T, b: T): boolean; +/** + * `getStructuralKey(a) === getStructuralKey(b) <=> structuralEquals(a, b)` + * (assuming that a and b are not cyclic structures and nothing extends globalThis Array). +*/ +export declare function getStructuralKey(t: unknown): string; diff --git a/packages/core/dist/equals.js b/packages/core/dist/equals.js new file mode 100644 index 00000000..4a9c467b --- /dev/null +++ b/packages/core/dist/equals.js @@ -0,0 +1,122 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import * as arrays from './arrays.js'; +/** + * Compares two items for equality using strict equality. +*/ +export const strictEquals = (a, b) => a === b; +/** + * Checks if the items of two arrays are equal. + * By default, strict equality is used to compare elements, but a custom equality comparer can be provided. + */ +export function itemsEquals(itemEquals = strictEquals) { + return (a, b) => arrays.equals(a, b, itemEquals); +} +/** + * Two items are considered equal, if their stringified representations are equal. +*/ +export function jsonStringifyEquals() { + return (a, b) => JSON.stringify(a) === JSON.stringify(b); +} +/** + * Uses `item.equals(other)` to determine equality. + */ +export function itemEquals() { + return (a, b) => a.equals(b); +} +export function equalsIfDefined(equalsOrV1, v2, equals) { + if (equals !== undefined) { + const v1 = equalsOrV1; + if (v1 === undefined || v1 === null || v2 === undefined || v2 === null) { + return v2 === v1; + } + return equals(v1, v2); + } + else { + const equals = equalsOrV1; + return (v1, v2) => { + if (v1 === undefined || v1 === null || v2 === undefined || v2 === null) { + return v2 === v1; + } + return equals(v1, v2); + }; + } +} +/** + * Drills into arrays (items ordered) and objects (keys unordered) and uses strict equality on everything else. +*/ +export function structuralEquals(a, b) { + if (a === b) { + return true; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i++) { + if (!structuralEquals(a[i], b[i])) { + return false; + } + } + return true; + } + if (a && typeof a === 'object' && b && typeof b === 'object') { + if (Object.getPrototypeOf(a) === Object.prototype && Object.getPrototypeOf(b) === Object.prototype) { + const aObj = a; + const bObj = b; + const keysA = Object.keys(aObj); + const keysB = Object.keys(bObj); + const keysBSet = new Set(keysB); + if (keysA.length !== keysB.length) { + return false; + } + for (const key of keysA) { + if (!keysBSet.has(key)) { + return false; + } + if (!structuralEquals(aObj[key], bObj[key])) { + return false; + } + } + return true; + } + } + return false; +} +/** + * `getStructuralKey(a) === getStructuralKey(b) <=> structuralEquals(a, b)` + * (assuming that a and b are not cyclic structures and nothing extends globalThis Array). +*/ +export function getStructuralKey(t) { + return JSON.stringify(toNormalizedJsonStructure(t)); +} +let objectId = 0; +const objIds = new WeakMap(); +function toNormalizedJsonStructure(t) { + if (Array.isArray(t)) { + return t.map(toNormalizedJsonStructure); + } + if (t && typeof t === 'object') { + if (Object.getPrototypeOf(t) === Object.prototype) { + const tObj = t; + const res = Object.create(null); + for (const key of Object.keys(tObj).sort()) { + res[key] = toNormalizedJsonStructure(tObj[key]); + } + return res; + } + else { + let objId = objIds.get(t); + if (objId === undefined) { + objId = objectId++; + objIds.set(t, objId); + } + // Random string to prevent collisions + return objId + '----2b76a038c20c4bcc'; + } + } + return t; +} +//# sourceMappingURL=equals.js.map \ No newline at end of file diff --git a/packages/core/dist/equals.js.map b/packages/core/dist/equals.js.map new file mode 100644 index 00000000..76b4d94f --- /dev/null +++ b/packages/core/dist/equals.js.map @@ -0,0 +1 @@ +{"version":3,"file":"equals.js","sourceRoot":"","sources":["../src/equals.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AAItC;;EAEE;AACF,MAAM,CAAC,MAAM,YAAY,GAA0B,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC;AAErE;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAI,aAAkC,YAAY;IAC5E,OAAO,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,UAAU,CAAC,CAAC;AAClD,CAAC;AAED;;EAEE;AACF,MAAM,UAAU,mBAAmB;IAClC,OAAO,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AAC1D,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU;IACzB,OAAO,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AAC9B,CAAC;AAUD,MAAM,UAAU,eAAe,CAAI,UAAmC,EAAE,EAAyB,EAAE,MAA4B;IAC9H,IAAI,MAAM,KAAK,SAAS,EAAE;QACzB,M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AAI,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,EAAE;QAC/B,IAAI,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,SAAS,EAAE;YAClD,MAAM,IAAI,GAAG,CAA4B,CAAC;YAC1C,MAAM,GAAG,GAA4B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACzD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE;gBAC3C,GAAG,CAAC,GAAG,CAAC,GAAG,yBAAyB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;aAChD;YACD,OAAO,GAAG,CAAC;SACX;aAAM;YACN,IAAI,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;YAC1B,IAAI,KAAK,KAAK,SAAS,EAAE;gBACxB,KAAK,GAAG,QAAQ,EAAE,CAAC;gBACnB,MAAM,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;aACrB;YACD,sCAAsC;YACtC,OAAO,KAAK,GAAG,sBAAsB,CAAC;SACtC;KACD;IACD,OAAO,CAAC,CAAC;AACV,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/errors.d.ts b/packages/core/dist/errors.d.ts new file mode 100644 index 00000000..80c2c1cb --- /dev/null +++ b/packages/core/dist/errors.d.ts @@ -0,0 +1,107 @@ +export interface ErrorListenerCallback { + (error: any): void; +} +export interface ErrorListenerUnbind { + (): void; +} +export declare class ErrorHandler { + private unexpectedErrorHandler; + private listeners; + constructor(); + addListener(listener: ErrorListenerCallback): ErrorListenerUnbind; + private emit; + private _removeListener; + setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void; + getUnexpectedErrorHandler(): (e: any) => void; + onUnexpectedError(e: any): void; + onUnexpectedExternalError(e: any): void; +} +export declare const errorHandler: ErrorHandler; +/** @skipMangle */ +export declare function setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void; +/** + * Returns if the error is a SIGPIPE error. SIGPIPE errors should generally be + * logged at most once, to avoid a loop. + * + * @see https://github.com/microsoft/vscode-remote-release/issues/6481 + */ +export declare function isSigPipeError(e: unknown): e is Error; +/** + * This function should only be called with errors that indicate a bug in the product. + * E.g. buggy extensions/invalid user-input/network issues should not be able to trigger this code path. + * If they are, this indicates there is also a bug in the product. +*/ +export declare function onBugIndicatingError(e: any): undefined; +export declare function onUnexpectedError(e: any): undefined; +export declare function onUnexpectedExternalError(e: any): undefined; +export interface SerializedError { + readonly $isError: true; + readonly name: string; + readonly message: string; + readonly stack: string; + readonly noTelemetry: boolean; + readonly code?: string; + readonly cause?: SerializedError; +} +export declare function transformErrorForSerialization(error: Error): SerializedError; +export declare function transformErrorForSerialization(error: any): any; +export declare function transformErrorFromSerialization(data: SerializedError): Error; +export interface V8CallSite { + getThis(): unknown; + getTypeName(): string | null; + getFunction(): Function | undefined; + getFunctionName(): string | null; + getMethodName(): string | null; + getFileName(): string | null; + getLineNumber(): number | null; + getColumnNumber(): number | null; + getEvalOrigin(): string | undefined; + isToplevel(): boolean; + isEval(): boolean; + isNative(): boolean; + isConstructor(): boolean; + toString(): string; +} +/** + * Checks if the given error is a promise in canceled state + */ +export declare function isCancellationError(error: any): boolean; +export declare class CancellationError extends Error { + constructor(); +} +/** + * @deprecated use {@link CancellationError `new CancellationError()`} instead + */ +export declare function canceled(): Error; +export declare function illegalArgument(name?: string): Error; +export declare function illegalState(name?: string): Error; +export declare class ReadonlyError extends TypeError { + constructor(name?: string); +} +export declare function getErrorMessage(err: any): string; +export declare class NotImplementedError extends Error { + constructor(message?: string); +} +export declare class NotSupportedError extends Error { + constructor(message?: string); +} +export declare class ExpectedError extends Error { + readonly isExpected = true; +} +/** + * Error that when thrown won't be logged in telemetry as an unhandled error. + */ +export declare class ErrorNoTelemetry extends Error { + readonly name: string; + constructor(msg?: string); + static fromError(err: Error): ErrorNoTelemetry; + static isErrorNoTelemetry(err: Error): err is ErrorNoTelemetry; +} +/** + * This error indicates a bug. + * Do not throw this for invalid user input. + * Only catch this error to recover gracefully from bugs. + */ +export declare class BugIndicatingError extends Error { + constructor(message?: string); +} diff --git a/packages/core/dist/errors.js b/packages/core/dist/errors.js new file mode 100644 index 00000000..72e68708 --- /dev/null +++ b/packages/core/dist/errors.js @@ -0,0 +1,243 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +// Avoid circular dependency on EventEmitter by implementing a subset of the interface. +export class ErrorHandler { + unexpectedErrorHandler; + listeners; + constructor() { + this.listeners = []; + this.unexpectedErrorHandler = function (e) { + setTimeout(() => { + if (e.stack) { + if (ErrorNoTelemetry.isErrorNoTelemetry(e)) { + throw new ErrorNoTelemetry(e.message + '\n\n' + e.stack); + } + throw new Error(e.message + '\n\n' + e.stack); + } + throw e; + }, 0); + }; + } + addListener(listener) { + this.listeners.push(listener); + return () => { + this._removeListener(listener); + }; + } + emit(e) { + this.listeners.forEach((listener) => { + listener(e); + }); + } + _removeListener(listener) { + this.listeners.splice(this.listeners.indexOf(listener), 1); + } + setUnexpectedErrorHandler(newUnexpectedErrorHandler) { + this.unexpectedErrorHandler = newUnexpectedErrorHandler; + } + getUnexpectedErrorHandler() { + return this.unexpectedErrorHandler; + } + onUnexpectedError(e) { + this.unexpectedErrorHandler(e); + this.emit(e); + } + // For external errors, we don't want the listeners to be called + onUnexpectedExternalError(e) { + this.unexpectedErrorHandler(e); + } +} +export const errorHandler = new ErrorHandler(); +/** @skipMangle */ +export function setUnexpectedErrorHandler(newUnexpectedErrorHandler) { + errorHandler.setUnexpectedErrorHandler(newUnexpectedErrorHandler); +} +/** + * Returns if the error is a SIGPIPE error. SIGPIPE errors should generally be + * logged at most once, to avoid a loop. + * + * @see https://github.com/microsoft/vscode-remote-release/issues/6481 + */ +export function isSigPipeError(e) { + if (!e || typeof e !== 'object') { + return false; + } + const cast = e; + return cast.code === 'EPIPE' && cast.syscall?.toUpperCase() === 'WRITE'; +} +/** + * This function should only be called with errors that indicate a bug in the product. + * E.g. buggy extensions/invalid user-input/network issues should not be able to trigger this code path. + * If they are, this indicates there is also a bug in the product. +*/ +export function onBugIndicatingError(e) { + errorHandler.onUnexpectedError(e); + return undefined; +} +export function onUnexpectedError(e) { + // ignore errors from cancelled promises + if (!isCancellationError(e)) { + errorHandler.onUnexpectedError(e); + } + return undefined; +} +export function onUnexpectedExternalError(e) { + // ignore errors from cancelled promises + if (!isCancellationError(e)) { + errorHandler.onUnexpectedExternalError(e); + } + return undefined; +} +export function transformErrorForSerialization(error) { + if (error instanceof Error) { + const { name, message, cause } = error; + const stack = error.stacktrace || error.stack; + return { + $isError: true, + name, + message, + stack, + noTelemetry: ErrorNoTelemetry.isErrorNoTelemetry(error), + cause: cause ? transformErrorForSerialization(cause) : undefined, + code: error.code + }; + } + // return as is + return error; +} +export function transformErrorFromSerialization(data) { + let error; + if (data.noTelemetry) { + error = new ErrorNoTelemetry(); + } + else { + error = new Error(); + error.name = data.name; + } + error.message = data.message; + error.stack = data.stack; + if (data.code) { + error.code = data.code; + } + if (data.cause) { + error.cause = transformErrorFromSerialization(data.cause); + } + return error; +} +const canceledName = 'Canceled'; +/** + * Checks if the given error is a promise in canceled state + */ +export function isCancellationError(error) { + if (error instanceof CancellationError) { + return true; + } + return error instanceof Error && error.name === canceledName && error.message === canceledName; +} +// !!!IMPORTANT!!! +// Do NOT change this class because it is also used as an API-type. +export class CancellationError extends Error { + constructor() { + super(canceledName); + this.name = this.message; + } +} +/** + * @deprecated use {@link CancellationError `new CancellationError()`} instead + */ +export function canceled() { + const error = new Error(canceledName); + error.name = error.message; + return error; +} +export function illegalArgument(name) { + if (name) { + return new Error(`Illegal argument: ${name}`); + } + else { + return new Error('Illegal argument'); + } +} +export function illegalState(name) { + if (name) { + return new Error(`Illegal state: ${name}`); + } + else { + return new Error('Illegal state'); + } +} +export class ReadonlyError extends TypeError { + constructor(name) { + super(name ? `${name} is read-only and cannot be changed` : 'Cannot change read-only property'); + } +} +export function getErrorMessage(err) { + if (!err) { + return 'Error'; + } + if (err.message) { + return err.message; + } + if (err.stack) { + return err.stack.split('\n')[0]; + } + return String(err); +} +export class NotImplementedError extends Error { + constructor(message) { + super('NotImplemented'); + if (message) { + this.message = message; + } + } +} +export class NotSupportedError extends Error { + constructor(message) { + super('NotSupported'); + if (message) { + this.message = message; + } + } +} +export class ExpectedError extends Error { + isExpected = true; +} +/** + * Error that when thrown won't be logged in telemetry as an unhandled error. + */ +export class ErrorNoTelemetry extends Error { + name; + constructor(msg) { + super(msg); + this.name = 'CodeExpectedError'; + } + static fromError(err) { + if (err instanceof ErrorNoTelemetry) { + return err; + } + const result = new ErrorNoTelemetry(); + result.message = err.message; + result.stack = err.stack; + return result; + } + static isErrorNoTelemetry(err) { + return err.name === 'CodeExpectedError'; + } +} +/** + * This error indicates a bug. + * Do not throw this for invalid user input. + * Only catch this error to recover gracefully from bugs. + */ +export class BugIndicatingError extends Error { + constructor(message) { + super(message || 'An unexpected bug occurred.'); + Object.setPrototypeOf(this, BugIndicatingError.prototype); + // Because we know for sure only buggy code throws this, + // we definitely want to break here and fix the bug. + // debugger; + } +} +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/packages/core/dist/errors.js.map b/packages/core/dist/errors.js.map new file mode 100644 index 00000000..fc9400d5 --- /dev/null +++ b/packages/core/dist/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAUhG,uFAAuF;AACvF,MAAM,OAAO,YAAY;IAChB,sBAAsB,CAAmB;IACzC,SAAS,CAA0B;IAE3C;QAEC,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;QAEpB,IAAI,CAAC,sBAAsB,GAAG,UAAU,CAAM;YAC7C,UAAU,CAAC,GAAG,EAAE;gBACf,IAAI,C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ChD,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,kBAAkB,CAAC,SAAS,CAAC,CAAC;QAE1D,wDAAwD;QACxD,oDAAoD;QACpD,YAAY;IACb,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/event.d.ts b/packages/core/dist/event.d.ts new file mode 100644 index 00000000..9f34589a --- /dev/null +++ b/packages/core/dist/event.d.ts @@ -0,0 +1,570 @@ +import { CancellationToken } from './cancellation.js'; +import { DisposableStore, IDisposable } from './lifecycle.js'; +import { LinkedList } from './linkedList.js'; +import { IObservable } from './observable.js'; +import { MicrotaskDelay } from './symbols.js'; +/** + * An event with zero or one parameters that can be subscribed to. The event is a function itself. + */ +export interface Event { + (listener: (e: T) => unknown, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable; +} +export declare namespace Event { + const None: Event; + /** + * Given an event, returns another event which debounces calls and defers the listeners to a later task via a shared + * `setTimeout`. The event is converted into a signal (`Event`) to avoid additional object creation as a + * result of merging events and to try prevent race conditions that could arise when using related deferred and + * non-deferred events. + * + * This is useful for deferring non-critical work (eg. general UI updates) to ensure it does not block critical work + * (eg. latency of keypress to text rendered). + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param disposable A disposable store to add the new EventEmitter to. + */ + function defer(event: Event, disposable?: DisposableStore): Event; + /** + * Given an event, returns another event which only fires once. + * + * @param event The event source for the new event. + */ + function once(event: Event): Event; + /** + * Given an event, returns another event which only fires once, and only when the condition is met. + * + * @param event The event source for the new event. + */ + function onceIf(event: Event, condition: (e: T) => boolean): Event; + /** + * Maps an event of one type into an event of another type using a mapping function, similar to how + * `Array.prototype.map` works. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param map The mapping function. + * @param disposable A disposable store to add the new EventEmitter to. + */ + function map(event: Event, map: (i: I) => O, disposable?: DisposableStore): Event; + /** + * Wraps an event in another event that performs some function on the event object before firing. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param each The function to perform on the event object. + * @param disposable A disposable store to add the new EventEmitter to. + */ + function forEach(event: Event, each: (i: I) => void, disposable?: DisposableStore): Event; + /** + * Wraps an event in another event that fires only when some condition is met. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param filter The filter function that defines the condition. The event will fire for the object if this function + * returns true. + * @param disposable A disposable store to add the new EventEmitter to. + */ + function filter(event: Event, filter: (e: T | U) => e is T, disposable?: DisposableStore): Event; + function filter(event: Event, filter: (e: T) => boolean, disposable?: DisposableStore): Event; + function filter(event: Event, filter: (e: T | R) => e is R, disposable?: DisposableStore): Event; + /** + * Given an event, returns the same event but typed as `Event`. + */ + function signal(event: Event): Event; + /** + * Given a collection of events, returns a single event which emits whenever any of the provided events emit. + */ + function any(...events: Event[]): Event; + function any(...events: Event[]): Event; + /** + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + */ + function reduce(event: Event, merge: (last: O | undefined, event: I) => O, initial?: O, disposable?: DisposableStore): Event; + /** + * Given an event, creates a new emitter that event that will debounce events based on {@link delay} and give an + * array event object of all events that fired. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The original event to debounce. + * @param merge A function that reduces all events into a single event. + * @param delay The number of milliseconds to debounce. + * @param leading Whether to fire a leading event without debouncing. + * @param flushOnListenerRemove Whether to fire all debounced events when a listener is removed. If this is not + * specified, some events could go missing. Use this if it's important that all events are processed, even if the + * listener gets disposed before the debounced event fires. + * @param leakWarningThreshold See {@link EmitterOptions.leakWarningThreshold}. + * @param disposable A disposable store to register the debounce emitter to. + */ + function debounce(event: Event, merge: (last: T | undefined, event: T) => T, delay?: number | typeof MicrotaskDelay, leading?: boolean, flushOnListenerRemove?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event; + function debounce(event: Event, merge: (last: O | undefined, event: I) => O, delay?: number | typeof MicrotaskDelay, leading?: boolean, flushOnListenerRemove?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event; + /** + * Debounces an event, firing after some delay (default=0) with an array of all event original objects. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + */ + function accumulate(event: Event, delay?: number, disposable?: DisposableStore): Event; + /** + * Filters an event such that some condition is _not_ met more than once in a row, effectively ensuring duplicate + * event objects from different sources do not fire the same event object. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param equals The equality condition. + * @param disposable A disposable store to add the new EventEmitter to. + * + * @example + * ``` + * // Fire only one time when a single window is opened or focused + * Event.latch(Event.any(onDidOpenWindow, onDidFocusWindow)) + * ``` + */ + function latch(event: Event, equals?: (a: T, b: T) => boolean, disposable?: DisposableStore): Event; + /** + * Splits an event whose parameter is a union type into 2 separate events for each type in the union. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @example + * ``` + * const event = new EventEmitter().event; + * const [numberEvent, undefinedEvent] = Event.split(event, isUndefined); + * ``` + * + * @param event The event source for the new event. + * @param isT A function that determines what event is of the first type. + * @param disposable A disposable store to add the new EventEmitter to. + */ + function split(event: Event, isT: (e: T | U) => e is T, disposable?: DisposableStore): [Event, Event]; + /** + * Buffers an event until it has a listener attached. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param flushAfterTimeout Determines whether to flush the buffer after a timeout immediately or after a + * `setTimeout` when the first event listener is added. + * @param _buffer Internal: A source event array used for tests. + * + * @example + * ``` + * // Start accumulating events, when the first listener is attached, flush + * // the event after a timeout such that multiple listeners attached before + * // the timeout would receive the event + * this.onInstallExtension = Event.buffer(service.onInstallExtension, true); + * ``` + */ + function buffer(event: Event, flushAfterTimeout?: boolean, _buffer?: T[], disposable?: DisposableStore): Event; + /** + * Wraps the event in an {@link IChainableEvent}, allowing a more functional programming style. + * + * @example + * ``` + * // Normal + * const onEnterPressNormal = Event.filter( + * Event.map(onKeyPress.event, e => new StandardKeyboardEvent(e)), + * e.keyCode === KeyCode.Enter + * ).event; + * + * // Using chain + * const onEnterPressChain = Event.chain(onKeyPress.event, $ => $ + * .map(e => new StandardKeyboardEvent(e)) + * .filter(e => e.keyCode === KeyCode.Enter) + * ); + * ``` + */ + function chain(event: Event, sythensize: ($: IChainableSythensis) => IChainableSythensis): Event; + interface IChainableSythensis { + map(fn: (i: T) => O): IChainableSythensis; + forEach(fn: (i: T) => void): IChainableSythensis; + filter(fn: (e: T) => e is R): IChainableSythensis; + filter(fn: (e: T) => boolean): IChainableSythensis; + reduce(merge: (last: R, event: T) => R, initial: R): IChainableSythensis; + reduce(merge: (last: R | undefined, event: T) => R): IChainableSythensis; + latch(equals?: (a: T, b: T) => boolean): IChainableSythensis; + } + interface NodeEventEmitter { + on(event: string | symbol, listener: Function): unknown; + removeListener(event: string | symbol, listener: Function): unknown; + } + /** + * Creates an {@link Event} from a node event emitter. + */ + function fromNodeEventEmitter(emitter: NodeEventEmitter, eventName: string, map?: (...args: any[]) => T): Event; + interface DOMEventEmitter { + addEventListener(event: string | symbol, listener: Function): void; + removeEventListener(event: string | symbol, listener: Function): void; + } + /** + * Creates an {@link Event} from a DOM event emitter. + */ + function fromDOMEventEmitter(emitter: DOMEventEmitter, eventName: string, map?: (...args: any[]) => T): Event; + /** + * Creates a promise out of an event, using the {@link Event.once} helper. + */ + function toPromise(event: Event): Promise; + /** + * Creates an event out of a promise that fires once when the promise is + * resolved with the result of the promise or `undefined`. + */ + function fromPromise(promise: Promise): Event; + /** + * A convenience function for forwarding an event to another emitter which + * improves readability. + * + * This is similar to {@link Relay} but allows instantiating and forwarding + * on a single line and also allows for multiple source events. + * @param from The event to forward. + * @param to The emitter to forward the event to. + * @example + * Event.forward(event, emitter); + * // equivalent to + * event(e => emitter.fire(e)); + * // equivalent to + * event(emitter.fire, emitter); + */ + function forward(from: Event, to: Emitter): IDisposable; + /** + * Adds a listener to an event and calls the listener immediately with undefined as the event object. + * + * @example + * ``` + * // Initialize the UI and update it when dataChangeEvent fires + * runAndSubscribe(dataChangeEvent, () => this._updateUI()); + * ``` + */ + function runAndSubscribe(event: Event, handler: (e: T) => unknown, initial: T): IDisposable; + function runAndSubscribe(event: Event, handler: (e: T | undefined) => unknown): IDisposable; + /** + * Creates an event emitter that is fired when the observable changes. + * Each listeners subscribes to the emitter. + */ + function fromObservable(obs: IObservable, store?: DisposableStore): Event; + /** + * Each listener is attached to the observable directly. + */ + function fromObservableLight(observable: IObservable): Event; +} +export interface EmitterOptions { + /** + * Optional function that's called *before* the very first listener is added + */ + onWillAddFirstListener?: Function; + /** + * Optional function that's called *after* the very first listener is added + */ + onDidAddFirstListener?: Function; + /** + * Optional function that's called after a listener is added + */ + onDidAddListener?: Function; + /** + * Optional function that's called *after* remove the very last listener + */ + onDidRemoveLastListener?: Function; + /** + * Optional function that's called *before* a listener is removed + */ + onWillRemoveListener?: Function; + /** + * Optional function that's called when a listener throws an error. Defaults to + * {@link onUnexpectedError} + */ + onListenerError?: (e: any) => void; + /** + * Number of listeners that are allowed before assuming a leak. Default to + * a globally configured value + * + * @see setGlobalLeakWarningThreshold + */ + leakWarningThreshold?: number; + /** + * Pass in a delivery queue, which is useful for ensuring + * in order event delivery across multiple emitters. + */ + deliveryQueue?: EventDeliveryQueue; + /** ONLY enable this during development */ + _profName?: string; +} +export declare class EventProfiling { + static readonly all: Set; + private static _idPool; + readonly name: string; + listenerCount: number; + invocationCount: number; + elapsedOverall: number; + durations: number[]; + private _stopWatch?; + constructor(name: string); + start(listenerCount: number): void; + stop(): void; +} +export declare function setGlobalLeakWarningThreshold(n: number): IDisposable; +declare class Stacktrace { + readonly value: string; + static create(): Stacktrace; + private constructor(); + print(): void; +} +export declare class ListenerLeakError extends Error { + constructor(message: string, stack: string); +} +export declare class ListenerRefusalError extends Error { + constructor(message: string, stack: string); +} +declare class UniqueContainer { + readonly value: T; + stack?: Stacktrace; + id: number; + constructor(value: T); +} +type ListenerContainer = UniqueContainer<(data: T) => void>; +type ListenerOrListeners = (ListenerContainer | undefined)[] | ListenerContainer; +/** + * The Emitter can be used to expose an Event to the public + * to fire it from the insides. + * Sample: + class Document { + + private readonly _onDidChange = new Emitter<(value:string)=>any>(); + + public onDidChange = this._onDidChange.event; + + // getter-style + // get onDidChange(): Event<(value:string)=>any> { + // return this._onDidChange.event; + // } + + private _doIt() { + //... + this._onDidChange.fire(value); + } + } + */ +export declare class Emitter { + private readonly _options?; + private readonly _leakageMon?; + private readonly _perfMon?; + private _disposed?; + private _event?; + /** + * A listener, or list of listeners. A single listener is the most common + * for event emitters (#185789), so we optimize that special case to avoid + * wrapping it in an array (just like Node.js itself.) + * + * A list of listeners never 'downgrades' back to a plain function if + * listeners are removed, for two reasons: + * + * 1. That's complicated (especially with the deliveryQueue) + * 2. A listener with >1 listener is likely to have >1 listener again at + * some point, and swapping between arrays and functions may[citation needed] + * introduce unnecessary work and garbage. + * + * The array listeners can be 'sparse', to avoid reallocating the array + * whenever any listener is added or removed. If more than `1 / compactionThreshold` + * of the array is empty, only then is it resized. + */ + protected _listeners?: ListenerOrListeners; + /** + * Always to be defined if _listeners is an array. It's no longer a true + * queue, but holds the dispatching 'state'. If `fire()` is called on an + * emitter, any work left in the _deliveryQueue is finished first. + */ + private _deliveryQueue?; + protected _size: number; + constructor(options?: EmitterOptions); + dispose(): void; + /** + * For the public to allow to subscribe + * to events from this Emitter + */ + get event(): Event; + private _removeListener; + private _deliver; + /** Delivers items in the queue. Assumes the queue is ready to go. */ + private _deliverQueue; + /** + * To be kept private to fire an event to + * subscribers + */ + fire(event: T): void; + hasListeners(): boolean; +} +export interface EventDeliveryQueue { + _isEventDeliveryQueue: true; +} +export declare const createEventDeliveryQueue: () => EventDeliveryQueue; +export interface IWaitUntil { + token: CancellationToken; + waitUntil(thenable: Promise): void; +} +export type IWaitUntilData = Omit, 'token'>; +export declare class AsyncEmitter extends Emitter { + private _asyncDeliveryQueue?; + fireAsync(data: IWaitUntilData, token: CancellationToken, promiseJoin?: (p: Promise, listener: Function) => Promise): Promise; +} +export declare class PauseableEmitter extends Emitter { + private _isPaused; + protected _eventQueue: LinkedList; + private _mergeFn?; + get isPaused(): boolean; + constructor(options?: EmitterOptions & { + merge?: (input: T[]) => T; + }); + pause(): void; + resume(): void; + fire(event: T): void; +} +export declare class DebounceEmitter extends PauseableEmitter { + private readonly _delay; + private _handle; + constructor(options: EmitterOptions & { + merge: (input: T[]) => T; + delay?: number; + }); + fire(event: T): void; +} +/** + * An emitter which queue all events and then process them at the + * end of the event loop. + */ +export declare class MicrotaskEmitter extends Emitter { + private _queuedEvents; + private _mergeFn?; + constructor(options?: EmitterOptions & { + merge?: (input: T[]) => T; + }); + fire(event: T): void; +} +/** + * An event emitter that multiplexes many events into a single event. + * + * @example Listen to the `onData` event of all `Thing`s, dynamically adding and removing `Thing`s + * to the multiplexer as needed. + * + * ```typescript + * const anythingDataMultiplexer = new EventMultiplexer<{ data: string }>(); + * + * const thingListeners = DisposableMap(); + * + * thingService.onDidAddThing(thing => { + * thingListeners.set(thing, anythingDataMultiplexer.add(thing.onData); + * }); + * thingService.onDidRemoveThing(thing => { + * thingListeners.deleteAndDispose(thing); + * }); + * + * anythingDataMultiplexer.event(e => { + * console.log('Something fired data ' + e.data) + * }); + * ``` + */ +export declare class EventMultiplexer implements IDisposable { + private readonly emitter; + private hasListeners; + private events; + constructor(); + get event(): Event; + add(event: Event): IDisposable; + private onFirstListenerAdd; + private onLastListenerRemove; + private hook; + private unhook; + dispose(): void; +} +export interface IDynamicListEventMultiplexer extends IDisposable { + readonly event: Event; +} +export declare class DynamicListEventMultiplexer implements IDynamicListEventMultiplexer { + private readonly _store; + readonly event: Event; + constructor(items: TItem[], onAddItem: Event, onRemoveItem: Event, getEvent: (item: TItem) => Event); + dispose(): void; +} +/** + * The EventBufferer is useful in situations in which you want + * to delay firing your events during some code. + * You can wrap that code and be sure that the event will not + * be fired during that wrap. + * + * ``` + * const emitter: Emitter; + * const delayer = new EventDelayer(); + * const delayedEvent = delayer.wrapEvent(emitter.event); + * + * delayedEvent(console.log); + * + * delayer.bufferEvents(() => { + * emitter.fire(); // event will not be fired yet + * }); + * + * // event will only be fired at this point + * ``` + */ +export declare class EventBufferer { + private data; + wrapEvent(event: Event): Event; + wrapEvent(event: Event, reduce: (last: T | undefined, event: T) => T): Event; + wrapEvent(event: Event, reduce: (last: O | undefined, event: T) => O, initial: O): Event; + bufferEvents(fn: () => R): R; +} +/** + * A Relay is an event forwarder which functions as a replugabble event pipe. + * Once created, you can connect an input event to it and it will simply forward + * events from that input event through its own `event` property. The `input` + * can be changed at any point in time. + */ +export declare class Relay implements IDisposable { + private listening; + private inputEvent; + private inputEventListener; + private readonly emitter; + readonly event: Event; + set input(event: Event); + dispose(): void; +} +export interface IValueWithChangeEvent { + readonly onDidChange: Event; + get value(): T; +} +export declare class ValueWithChangeEvent implements IValueWithChangeEvent { + private _value; + static const(value: T): IValueWithChangeEvent; + private readonly _onDidChange; + readonly onDidChange: Event; + constructor(_value: T); + get value(): T; + set value(value: T); +} +/** + * @param handleItem Is called for each item in the set (but only the first time the item is seen in the set). + * The returned disposable is disposed if the item is no longer in the set. + */ +export declare function trackSetChanges(getData: () => ReadonlySet, onDidChangeData: Event, handleItem: (d: T) => IDisposable): IDisposable; +export {}; diff --git a/packages/core/dist/event.js b/packages/core/dist/event.js new file mode 100644 index 00000000..a3fcfbe6 --- /dev/null +++ b/packages/core/dist/event.js @@ -0,0 +1,1445 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { diffSets } from './collections.js'; +import { onUnexpectedError } from './errors.js'; +import { createSingleCallFunction } from './functional.js'; +import { combinedDisposable, Disposable, DisposableMap, DisposableStore, toDisposable } from './lifecycle.js'; +import { LinkedList } from './linkedList.js'; +import { StopWatch } from './stopwatch.js'; +// ----------------------------------------------------------------------------------------------------------------------- +// Uncomment the next line to print warnings whenever an emitter with listeners is disposed. That is a sign of code smell. +// ----------------------------------------------------------------------------------------------------------------------- +const _enableDisposeWithListenerWarning = false; +// ----------------------------------------------------------------------------------------------------------------------- +// Uncomment the next line to print warnings whenever a snapshotted event is used repeatedly without cleanup. +// See https://github.com/microsoft/vscode/issues/142851 +// ----------------------------------------------------------------------------------------------------------------------- +const _enableSnapshotPotentialLeakWarning = false; +export var Event; +(function (Event) { + Event.None = () => Disposable.None; + function _addLeakageTraceLogic(options) { + if (_enableSnapshotPotentialLeakWarning) { + const { onDidAddListener: origListenerDidAdd } = options; + const stack = Stacktrace.create(); + let count = 0; + options.onDidAddListener = () => { + if (++count === 2) { + console.warn('snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here'); + stack.print(); + } + origListenerDidAdd?.(); + }; + } + } + /** + * Given an event, returns another event which debounces calls and defers the listeners to a later task via a shared + * `setTimeout`. The event is converted into a signal (`Event`) to avoid additional object creation as a + * result of merging events and to try prevent race conditions that could arise when using related deferred and + * non-deferred events. + * + * This is useful for deferring non-critical work (eg. general UI updates) to ensure it does not block critical work + * (eg. latency of keypress to text rendered). + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param disposable A disposable store to add the new EventEmitter to. + */ + function defer(event, disposable) { + return debounce(event, () => void 0, 0, undefined, true, undefined, disposable); + } + Event.defer = defer; + /** + * Given an event, returns another event which only fires once. + * + * @param event The event source for the new event. + */ + function once(event) { + return (listener, thisArgs = null, disposables) => { + // we need this, in case the event fires during the listener call + let didFire = false; + let result = undefined; + result = event(e => { + if (didFire) { + return; + } + else if (result) { + result.dispose(); + } + else { + didFire = true; + } + return listener.call(thisArgs, e); + }, null, disposables); + if (didFire) { + result.dispose(); + } + return result; + }; + } + Event.once = once; + /** + * Given an event, returns another event which only fires once, and only when the condition is met. + * + * @param event The event source for the new event. + */ + function onceIf(event, condition) { + return Event.once(Event.filter(event, condition)); + } + Event.onceIf = onceIf; + /** + * Maps an event of one type into an event of another type using a mapping function, similar to how + * `Array.prototype.map` works. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param map The mapping function. + * @param disposable A disposable store to add the new EventEmitter to. + */ + function map(event, map, disposable) { + return snapshot((listener, thisArgs = null, disposables) => event(i => listener.call(thisArgs, map(i)), null, disposables), disposable); + } + Event.map = map; + /** + * Wraps an event in another event that performs some function on the event object before firing. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param each The function to perform on the event object. + * @param disposable A disposable store to add the new EventEmitter to. + */ + function forEach(event, each, disposable) { + return snapshot((listener, thisArgs = null, disposables) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables), disposable); + } + Event.forEach = forEach; + function filter(event, filter, disposable) { + return snapshot((listener, thisArgs = null, disposables) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables), disposable); + } + Event.filter = filter; + /** + * Given an event, returns the same event but typed as `Event`. + */ + function signal(event) { + return event; + } + Event.signal = signal; + function any(...events) { + return (listener, thisArgs = null, disposables) => { + const disposable = combinedDisposable(...events.map(event => event(e => listener.call(thisArgs, e)))); + return addAndReturnDisposable(disposable, disposables); + }; + } + Event.any = any; + /** + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + */ + function reduce(event, merge, initial, disposable) { + let output = initial; + return map(event, e => { + output = merge(output, e); + return output; + }, disposable); + } + Event.reduce = reduce; + function snapshot(event, disposable) { + let listener; + const options = { + onWillAddFirstListener() { + listener = event(emitter.fire, emitter); + }, + onDidRemoveLastListener() { + listener?.dispose(); + } + }; + if (!disposable) { + _addLeakageTraceLogic(options); + } + const emitter = new Emitter(options); + disposable?.add(emitter); + return emitter.event; + } + /** + * Adds the IDisposable to the store if it's set, and returns it. Useful to + * Event function implementation. + */ + function addAndReturnDisposable(d, store) { + if (store instanceof Array) { + store.push(d); + } + else if (store) { + store.add(d); + } + return d; + } + function debounce(event, merge, delay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold, disposable) { + let subscription; + let output = undefined; + let handle = undefined; + let numDebouncedCalls = 0; + let doFire; + const options = { + leakWarningThreshold, + onWillAddFirstListener() { + subscription = event(cur => { + numDebouncedCalls++; + output = merge(output, cur); + if (leading && !handle) { + emitter.fire(output); + output = undefined; + } + doFire = () => { + const _output = output; + output = undefined; + handle = undefined; + if (!leading || numDebouncedCalls > 1) { + emitter.fire(_output); + } + numDebouncedCalls = 0; + }; + if (typeof delay === 'number') { + clearTimeout(handle); + handle = setTimeout(doFire, delay); + } + else { + if (handle === undefined) { + handle = 0; + queueMicrotask(doFire); + } + } + }); + }, + onWillRemoveListener() { + if (flushOnListenerRemove && numDebouncedCalls > 0) { + doFire?.(); + } + }, + onDidRemoveLastListener() { + doFire = undefined; + subscription.dispose(); + } + }; + if (!disposable) { + _addLeakageTraceLogic(options); + } + const emitter = new Emitter(options); + disposable?.add(emitter); + return emitter.event; + } + Event.debounce = debounce; + /** + * Debounces an event, firing after some delay (default=0) with an array of all event original objects. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + */ + function accumulate(event, delay = 0, disposable) { + return Event.debounce(event, (last, e) => { + if (!last) { + return [e]; + } + last.push(e); + return last; + }, delay, undefined, true, undefined, disposable); + } + Event.accumulate = accumulate; + /** + * Filters an event such that some condition is _not_ met more than once in a row, effectively ensuring duplicate + * event objects from different sources do not fire the same event object. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param equals The equality condition. + * @param disposable A disposable store to add the new EventEmitter to. + * + * @example + * ``` + * // Fire only one time when a single window is opened or focused + * Event.latch(Event.any(onDidOpenWindow, onDidFocusWindow)) + * ``` + */ + function latch(event, equals = (a, b) => a === b, disposable) { + let firstCall = true; + let cache; + return filter(event, value => { + const shouldEmit = firstCall || !equals(value, cache); + firstCall = false; + cache = value; + return shouldEmit; + }, disposable); + } + Event.latch = latch; + /** + * Splits an event whose parameter is a union type into 2 separate events for each type in the union. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @example + * ``` + * const event = new EventEmitter().event; + * const [numberEvent, undefinedEvent] = Event.split(event, isUndefined); + * ``` + * + * @param event The event source for the new event. + * @param isT A function that determines what event is of the first type. + * @param disposable A disposable store to add the new EventEmitter to. + */ + function split(event, isT, disposable) { + return [ + Event.filter(event, isT, disposable), + Event.filter(event, e => !isT(e), disposable), + ]; + } + Event.split = split; + /** + * Buffers an event until it has a listener attached. + * + * *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned + * event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the + * returned event causes this utility to leak a listener on the original event. + * + * @param event The event source for the new event. + * @param flushAfterTimeout Determines whether to flush the buffer after a timeout immediately or after a + * `setTimeout` when the first event listener is added. + * @param _buffer Internal: A source event array used for tests. + * + * @example + * ``` + * // Start accumulating events, when the first listener is attached, flush + * // the event after a timeout such that multiple listeners attached before + * // the timeout would receive the event + * this.onInstallExtension = Event.buffer(service.onInstallExtension, true); + * ``` + */ + function buffer(event, flushAfterTimeout = false, _buffer = [], disposable) { + let buffer = _buffer.slice(); + let listener = event(e => { + if (buffer) { + buffer.push(e); + } + else { + emitter.fire(e); + } + }); + if (disposable) { + disposable.add(listener); + } + const flush = () => { + buffer?.forEach(e => emitter.fire(e)); + buffer = null; + }; + const emitter = new Emitter({ + onWillAddFirstListener() { + if (!listener) { + listener = event(e => emitter.fire(e)); + if (disposable) { + disposable.add(listener); + } + } + }, + onDidAddFirstListener() { + if (buffer) { + if (flushAfterTimeout) { + setTimeout(flush); + } + else { + flush(); + } + } + }, + onDidRemoveLastListener() { + if (listener) { + listener.dispose(); + } + listener = null; + } + }); + if (disposable) { + disposable.add(emitter); + } + return emitter.event; + } + Event.buffer = buffer; + /** + * Wraps the event in an {@link IChainableEvent}, allowing a more functional programming style. + * + * @example + * ``` + * // Normal + * const onEnterPressNormal = Event.filter( + * Event.map(onKeyPress.event, e => new StandardKeyboardEvent(e)), + * e.keyCode === KeyCode.Enter + * ).event; + * + * // Using chain + * const onEnterPressChain = Event.chain(onKeyPress.event, $ => $ + * .map(e => new StandardKeyboardEvent(e)) + * .filter(e => e.keyCode === KeyCode.Enter) + * ); + * ``` + */ + function chain(event, sythensize) { + const fn = (listener, thisArgs, disposables) => { + const cs = sythensize(new ChainableSynthesis()); + return event(function (value) { + const result = cs.evaluate(value); + if (result !== HaltChainable) { + listener.call(thisArgs, result); + } + }, undefined, disposables); + }; + return fn; + } + Event.chain = chain; + const HaltChainable = Symbol('HaltChainable'); + class ChainableSynthesis { + steps = []; + map(fn) { + this.steps.push(fn); + return this; + } + forEach(fn) { + this.steps.push(v => { + fn(v); + return v; + }); + return this; + } + filter(fn) { + this.steps.push(v => fn(v) ? v : HaltChainable); + return this; + } + reduce(merge, initial) { + let last = initial; + this.steps.push(v => { + last = merge(last, v); + return last; + }); + return this; + } + latch(equals = (a, b) => a === b) { + let firstCall = true; + let cache; + this.steps.push(value => { + const shouldEmit = firstCall || !equals(value, cache); + firstCall = false; + cache = value; + return shouldEmit ? value : HaltChainable; + }); + return this; + } + evaluate(value) { + for (const step of this.steps) { + value = step(value); + if (value === HaltChainable) { + break; + } + } + return value; + } + } + /** + * Creates an {@link Event} from a node event emitter. + */ + function fromNodeEventEmitter(emitter, eventName, map = id => id) { + const fn = (...args) => result.fire(map(...args)); + const onFirstListenerAdd = () => emitter.on(eventName, fn); + const onLastListenerRemove = () => emitter.removeListener(eventName, fn); + const result = new Emitter({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove }); + return result.event; + } + Event.fromNodeEventEmitter = fromNodeEventEmitter; + /** + * Creates an {@link Event} from a DOM event emitter. + */ + function fromDOMEventEmitter(emitter, eventName, map = id => id) { + const fn = (...args) => result.fire(map(...args)); + const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn); + const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn); + const result = new Emitter({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove }); + return result.event; + } + Event.fromDOMEventEmitter = fromDOMEventEmitter; + /** + * Creates a promise out of an event, using the {@link Event.once} helper. + */ + function toPromise(event) { + return new Promise(resolve => once(event)(resolve)); + } + Event.toPromise = toPromise; + /** + * Creates an event out of a promise that fires once when the promise is + * resolved with the result of the promise or `undefined`. + */ + function fromPromise(promise) { + const result = new Emitter(); + promise.then(res => { + result.fire(res); + }, () => { + result.fire(undefined); + }).finally(() => { + result.dispose(); + }); + return result.event; + } + Event.fromPromise = fromPromise; + /** + * A convenience function for forwarding an event to another emitter which + * improves readability. + * + * This is similar to {@link Relay} but allows instantiating and forwarding + * on a single line and also allows for multiple source events. + * @param from The event to forward. + * @param to The emitter to forward the event to. + * @example + * Event.forward(event, emitter); + * // equivalent to + * event(e => emitter.fire(e)); + * // equivalent to + * event(emitter.fire, emitter); + */ + function forward(from, to) { + return from(e => to.fire(e)); + } + Event.forward = forward; + function runAndSubscribe(event, handler, initial) { + handler(initial); + return event(e => handler(e)); + } + Event.runAndSubscribe = runAndSubscribe; + class EmitterObserver { + _observable; + emitter; + _counter = 0; + _hasChanged = false; + constructor(_observable, store) { + this._observable = _observable; + const options = { + onWillAddFirstListener: () => { + _observable.addObserver(this); + // Communicate to the observable that we received its current value and would like to be notified about future changes. + this._observable.reportChanges(); + }, + onDidRemoveLastListener: () => { + _observable.removeObserver(this); + } + }; + if (!store) { + _addLeakageTraceLogic(options); + } + this.emitter = new Emitter(options); + if (store) { + store.add(this.emitter); + } + } + beginUpdate(_observable) { + // assert(_observable === this.obs); + this._counter++; + } + handlePossibleChange(_observable) { + // assert(_observable === this.obs); + } + handleChange(_observable, _change) { + // assert(_observable === this.obs); + this._hasChanged = true; + } + endUpdate(_observable) { + // assert(_observable === this.obs); + this._counter--; + if (this._counter === 0) { + this._observable.reportChanges(); + if (this._hasChanged) { + this._hasChanged = false; + this.emitter.fire(this._observable.get()); + } + } + } + } + /** + * Creates an event emitter that is fired when the observable changes. + * Each listeners subscribes to the emitter. + */ + function fromObservable(obs, store) { + const observer = new EmitterObserver(obs, store); + return observer.emitter.event; + } + Event.fromObservable = fromObservable; + /** + * Each listener is attached to the observable directly. + */ + function fromObservableLight(observable) { + return (listener, thisArgs, disposables) => { + let count = 0; + let didChange = false; + const observer = { + beginUpdate() { + count++; + }, + endUpdate() { + count--; + if (count === 0) { + observable.reportChanges(); + if (didChange) { + didChange = false; + listener.call(thisArgs); + } + } + }, + handlePossibleChange() { + // noop + }, + handleChange() { + didChange = true; + } + }; + observable.addObserver(observer); + observable.reportChanges(); + const disposable = { + dispose() { + observable.removeObserver(observer); + } + }; + if (disposables instanceof DisposableStore) { + disposables.add(disposable); + } + else if (Array.isArray(disposables)) { + disposables.push(disposable); + } + return disposable; + }; + } + Event.fromObservableLight = fromObservableLight; +})(Event = Event || (Event = {})); +export class EventProfiling { + static all = new Set(); + static _idPool = 0; + name; + listenerCount = 0; + invocationCount = 0; + elapsedOverall = 0; + durations = []; + _stopWatch; + constructor(name) { + this.name = `${name}_${EventProfiling._idPool++}`; + EventProfiling.all.add(this); + } + start(listenerCount) { + this._stopWatch = new StopWatch(); + this.listenerCount = listenerCount; + } + stop() { + if (this._stopWatch) { + const elapsed = this._stopWatch.elapsed(); + this.durations.push(elapsed); + this.elapsedOverall += elapsed; + this.invocationCount += 1; + this._stopWatch = undefined; + } + } +} +let _globalLeakWarningThreshold = -1; +export function setGlobalLeakWarningThreshold(n) { + const oldValue = _globalLeakWarningThreshold; + _globalLeakWarningThreshold = n; + return { + dispose() { + _globalLeakWarningThreshold = oldValue; + } + }; +} +class LeakageMonitor { + _errorHandler; + threshold; + name; + static _idPool = 1; + _stacks; + _warnCountdown = 0; + constructor(_errorHandler, threshold, name = (LeakageMonitor._idPool++).toString(16).padStart(3, '0')) { + this._errorHandler = _errorHandler; + this.threshold = threshold; + this.name = name; + } + dispose() { + this._stacks?.clear(); + } + check(stack, listenerCount) { + const threshold = this.threshold; + if (threshold <= 0 || listenerCount < threshold) { + return undefined; + } + if (!this._stacks) { + this._stacks = new Map(); + } + const count = (this._stacks.get(stack.value) || 0); + this._stacks.set(stack.value, count + 1); + this._warnCountdown -= 1; + if (this._warnCountdown <= 0) { + // only warn on first exceed and then every time the limit + // is exceeded by 50% again + this._warnCountdown = threshold * 0.5; + const [topStack, topCount] = this.getMostFrequentStack(); + const message = `[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`; + console.warn(message); + console.warn(topStack); + const error = new ListenerLeakError(message, topStack); + this._errorHandler(error); + } + return () => { + const count = (this._stacks.get(stack.value) || 0); + this._stacks.set(stack.value, count - 1); + }; + } + getMostFrequentStack() { + if (!this._stacks) { + return undefined; + } + let topStack; + let topCount = 0; + for (const [stack, count] of this._stacks) { + if (!topStack || topCount < count) { + topStack = [stack, count]; + topCount = count; + } + } + return topStack; + } +} +class Stacktrace { + value; + static create() { + const err = new Error(); + return new Stacktrace(err.stack ?? ''); + } + constructor(value) { + this.value = value; + } + print() { + console.warn(this.value.split('\n').slice(2).join('\n')); + } +} +// error that is logged when going over the configured listener threshold +export class ListenerLeakError extends Error { + constructor(message, stack) { + super(message); + this.name = 'ListenerLeakError'; + this.stack = stack; + } +} +// SEVERE error that is logged when having gone way over the configured listener +// threshold so that the emitter refuses to accept more listeners +export class ListenerRefusalError extends Error { + constructor(message, stack) { + super(message); + this.name = 'ListenerRefusalError'; + this.stack = stack; + } +} +let id = 0; +class UniqueContainer { + value; + stack; + id = id++; + constructor(value) { + this.value = value; + } +} +const compactionThreshold = 2; +const forEachListener = (listeners, fn) => { + if (listeners instanceof UniqueContainer) { + fn(listeners); + } + else { + for (let i = 0; i < listeners.length; i++) { + const l = listeners[i]; + if (l) { + fn(l); + } + } + } +}; +/** + * The Emitter can be used to expose an Event to the public + * to fire it from the insides. + * Sample: + class Document { + + private readonly _onDidChange = new Emitter<(value:string)=>any>(); + + public onDidChange = this._onDidChange.event; + + // getter-style + // get onDidChange(): Event<(value:string)=>any> { + // return this._onDidChange.event; + // } + + private _doIt() { + //... + this._onDidChange.fire(value); + } + } + */ +export class Emitter { + _options; + _leakageMon; + _perfMon; + _disposed; + _event; + /** + * A listener, or list of listeners. A single listener is the most common + * for event emitters (#185789), so we optimize that special case to avoid + * wrapping it in an array (just like Node.js itself.) + * + * A list of listeners never 'downgrades' back to a plain function if + * listeners are removed, for two reasons: + * + * 1. That's complicated (especially with the deliveryQueue) + * 2. A listener with >1 listener is likely to have >1 listener again at + * some point, and swapping between arrays and functions may[citation needed] + * introduce unnecessary work and garbage. + * + * The array listeners can be 'sparse', to avoid reallocating the array + * whenever any listener is added or removed. If more than `1 / compactionThreshold` + * of the array is empty, only then is it resized. + */ + _listeners; + /** + * Always to be defined if _listeners is an array. It's no longer a true + * queue, but holds the dispatching 'state'. If `fire()` is called on an + * emitter, any work left in the _deliveryQueue is finished first. + */ + _deliveryQueue; + _size = 0; + constructor(options) { + this._options = options; + this._leakageMon = (_globalLeakWarningThreshold > 0 || this._options?.leakWarningThreshold) + ? new LeakageMonitor(options?.onListenerError ?? onUnexpectedError, this._options?.leakWarningThreshold ?? _globalLeakWarningThreshold) : + undefined; + this._perfMon = this._options?._profName ? new EventProfiling(this._options._profName) : undefined; + this._deliveryQueue = this._options?.deliveryQueue; + } + dispose() { + if (!this._disposed) { + this._disposed = true; + // It is bad to have listeners at the time of disposing an emitter, it is worst to have listeners keep the emitter + // alive via the reference that's embedded in their disposables. Therefore we loop over all remaining listeners and + // unset their subscriptions/disposables. Looping and blaming remaining listeners is done on next tick because the + // the following programming pattern is very popular: + // + // const someModel = this._disposables.add(new ModelObject()); // (1) create and register model + // this._disposables.add(someModel.onDidChange(() => { ... }); // (2) subscribe and register model-event listener + // ...later... + // this._disposables.dispose(); disposes (1) then (2): don't warn after (1) but after the "overall dispose" is done + if (this._deliveryQueue?.current === this) { + this._deliveryQueue.reset(); + } + if (this._listeners) { + if (_enableDisposeWithListenerWarning) { + const listeners = this._listeners; + queueMicrotask(() => { + forEachListener(listeners, l => l.stack?.print()); + }); + } + this._listeners = undefined; + this._size = 0; + } + this._options?.onDidRemoveLastListener?.(); + this._leakageMon?.dispose(); + } + } + /** + * For the public to allow to subscribe + * to events from this Emitter + */ + get event() { + this._event ??= (callback, thisArgs, disposables) => { + if (this._leakageMon && this._size > this._leakageMon.threshold ** 2) { + const message = `[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`; + console.warn(message); + const tuple = this._leakageMon.getMostFrequentStack() ?? ['UNKNOWN stack', -1]; + const error = new ListenerRefusalError(`${message}. HINT: Stack shows most frequent listener (${tuple[1]}-times)`, tuple[0]); + const errorHandler = this._options?.onListenerError || onUnexpectedError; + errorHandler(error); + return Disposable.None; + } + if (this._disposed) { + // todo: should we warn if a listener is added to a disposed emitter? This happens often + return Disposable.None; + } + if (thisArgs) { + callback = callback.bind(thisArgs); + } + const contained = new UniqueContainer(callback); + let removeMonitor; + let stack; + if (this._leakageMon && this._size >= Math.ceil(this._leakageMon.threshold * 0.2)) { + // check and record this emitter for potential leakage + contained.stack = Stacktrace.create(); + removeMonitor = this._leakageMon.check(contained.stack, this._size + 1); + } + if (_enableDisposeWithListenerWarning) { + contained.stack = stack ?? Stacktrace.create(); + } + if (!this._listeners) { + this._options?.onWillAddFirstListener?.(this); + this._listeners = contained; + this._options?.onDidAddFirstListener?.(this); + } + else if (this._listeners instanceof UniqueContainer) { + this._deliveryQueue ??= new EventDeliveryQueuePrivate(); + this._listeners = [this._listeners, contained]; + } + else { + this._listeners.push(contained); + } + this._options?.onDidAddListener?.(this); + this._size++; + const result = toDisposable(() => { + removeMonitor?.(); + this._removeListener(contained); + }); + if (disposables instanceof DisposableStore) { + disposables.add(result); + } + else if (Array.isArray(disposables)) { + disposables.push(result); + } + return result; + }; + return this._event; + } + _removeListener(listener) { + this._options?.onWillRemoveListener?.(this); + if (!this._listeners) { + return; // expected if a listener gets disposed + } + if (this._size === 1) { + this._listeners = undefined; + this._options?.onDidRemoveLastListener?.(this); + this._size = 0; + return; + } + // size > 1 which requires that listeners be a list: + const listeners = this._listeners; + const index = listeners.indexOf(listener); + if (index === -1) { + console.log('disposed?', this._disposed); + console.log('size?', this._size); + console.log('arr?', JSON.stringify(this._listeners)); + throw new Error('Attempted to dispose unknown listener'); + } + this._size--; + listeners[index] = undefined; + const adjustDeliveryQueue = this._deliveryQueue.current === this; + if (this._size * compactionThreshold <= listeners.length) { + let n = 0; + for (let i = 0; i < listeners.length; i++) { + if (listeners[i]) { + listeners[n++] = listeners[i]; + } + else if (adjustDeliveryQueue && n < this._deliveryQueue.end) { + this._deliveryQueue.end--; + if (n < this._deliveryQueue.i) { + this._deliveryQueue.i--; + } + } + } + listeners.length = n; + } + } + _deliver(listener, value) { + if (!listener) { + return; + } + const errorHandler = this._options?.onListenerError || onUnexpectedError; + if (!errorHandler) { + listener.value(value); + return; + } + try { + listener.value(value); + } + catch (e) { + errorHandler(e); + } + } + /** Delivers items in the queue. Assumes the queue is ready to go. */ + _deliverQueue(dq) { + const listeners = dq.current._listeners; + while (dq.i < dq.end) { + // important: dq.i is incremented before calling deliver() because it might reenter deliverQueue() + this._deliver(listeners[dq.i++], dq.value); + } + dq.reset(); + } + /** + * To be kept private to fire an event to + * subscribers + */ + fire(event) { + if (this._deliveryQueue?.current) { + this._deliverQueue(this._deliveryQueue); + this._perfMon?.stop(); // last fire() will have starting perfmon, stop it before starting the next dispatch + } + this._perfMon?.start(this._size); + if (!this._listeners) { + // no-op + } + else if (this._listeners instanceof UniqueContainer) { + this._deliver(this._listeners, event); + } + else { + const dq = this._deliveryQueue; + dq.enqueue(this, event, this._listeners.length); + this._deliverQueue(dq); + } + this._perfMon?.stop(); + } + hasListeners() { + return this._size > 0; + } +} +export const createEventDeliveryQueue = () => new EventDeliveryQueuePrivate(); +class EventDeliveryQueuePrivate { + /** + * Index in current's listener list. + */ + i = -1; + /** + * The last index in the listener's list to deliver. + */ + end = 0; + /** + * Emitter currently being dispatched on. Emitter._listeners is always an array. + */ + current; + /** + * Currently emitting value. Defined whenever `current` is. + */ + value; + enqueue(emitter, value, end) { + this.i = 0; + this.end = end; + this.current = emitter; + this.value = value; + } + reset() { + this.i = this.end; // force any current emission loop to stop, mainly for during dispose + this.current = undefined; + this.value = undefined; + } +} +export class AsyncEmitter extends Emitter { + _asyncDeliveryQueue; + async fireAsync(data, token, promiseJoin) { + if (!this._listeners) { + return; + } + if (!this._asyncDeliveryQueue) { + this._asyncDeliveryQueue = new LinkedList(); + } + forEachListener(this._listeners, listener => this._asyncDeliveryQueue.push([listener.value, data])); + while (this._asyncDeliveryQueue.size > 0 && !token.isCancellationRequested) { + const [listener, data] = this._asyncDeliveryQueue.shift(); + const thenables = []; + // eslint-disable-next-line local/code-no-dangerous-type-assertions + const event = { + ...data, + token, + waitUntil: (p) => { + if (Object.isFrozen(thenables)) { + throw new Error('waitUntil can NOT be called asynchronous'); + } + if (promiseJoin) { + p = promiseJoin(p, listener); + } + thenables.push(p); + } + }; + try { + listener(event); + } + catch (e) { + onUnexpectedError(e); + continue; + } + // freeze thenables-collection to enforce sync-calls to + // wait until and then wait for all thenables to resolve + Object.freeze(thenables); + await Promise.allSettled(thenables).then(values => { + for (const value of values) { + if (value.status === 'rejected') { + onUnexpectedError(value.reason); + } + } + }); + } + } +} +export class PauseableEmitter extends Emitter { + _isPaused = 0; + _eventQueue = new LinkedList(); + _mergeFn; + get isPaused() { + return this._isPaused !== 0; + } + constructor(options) { + super(options); + this._mergeFn = options?.merge; + } + pause() { + this._isPaused++; + } + resume() { + if (this._isPaused !== 0 && --this._isPaused === 0) { + if (this._mergeFn) { + // use the merge function to create a single composite + // event. make a copy in case firing pauses this emitter + if (this._eventQueue.size > 0) { + const events = Array.from(this._eventQueue); + this._eventQueue.clear(); + super.fire(this._mergeFn(events)); + } + } + else { + // no merging, fire each event individually and test + // that this emitter isn't paused halfway through + while (!this._isPaused && this._eventQueue.size !== 0) { + super.fire(this._eventQueue.shift()); + } + } + } + } + fire(event) { + if (this._size) { + if (this._isPaused !== 0) { + this._eventQueue.push(event); + } + else { + super.fire(event); + } + } + } +} +export class DebounceEmitter extends PauseableEmitter { + _delay; + _handle; + constructor(options) { + super(options); + this._delay = options.delay ?? 100; + } + fire(event) { + if (!this._handle) { + this.pause(); + this._handle = setTimeout(() => { + this._handle = undefined; + this.resume(); + }, this._delay); + } + super.fire(event); + } +} +/** + * An emitter which queue all events and then process them at the + * end of the event loop. + */ +export class MicrotaskEmitter extends Emitter { + _queuedEvents = []; + _mergeFn; + constructor(options) { + super(options); + this._mergeFn = options?.merge; + } + fire(event) { + if (!this.hasListeners()) { + return; + } + this._queuedEvents.push(event); + if (this._queuedEvents.length === 1) { + queueMicrotask(() => { + if (this._mergeFn) { + super.fire(this._mergeFn(this._queuedEvents)); + } + else { + this._queuedEvents.forEach(e => super.fire(e)); + } + this._queuedEvents = []; + }); + } + } +} +/** + * An event emitter that multiplexes many events into a single event. + * + * @example Listen to the `onData` event of all `Thing`s, dynamically adding and removing `Thing`s + * to the multiplexer as needed. + * + * ```typescript + * const anythingDataMultiplexer = new EventMultiplexer<{ data: string }>(); + * + * const thingListeners = DisposableMap(); + * + * thingService.onDidAddThing(thing => { + * thingListeners.set(thing, anythingDataMultiplexer.add(thing.onData); + * }); + * thingService.onDidRemoveThing(thing => { + * thingListeners.deleteAndDispose(thing); + * }); + * + * anythingDataMultiplexer.event(e => { + * console.log('Something fired data ' + e.data) + * }); + * ``` + */ +export class EventMultiplexer { + emitter; + hasListeners = false; + events = []; + constructor() { + this.emitter = new Emitter({ + onWillAddFirstListener: () => this.onFirstListenerAdd(), + onDidRemoveLastListener: () => this.onLastListenerRemove() + }); + } + get event() { + return this.emitter.event; + } + add(event) { + const e = { event: event, listener: null }; + this.events.push(e); + if (this.hasListeners) { + this.hook(e); + } + const dispose = () => { + if (this.hasListeners) { + this.unhook(e); + } + const idx = this.events.indexOf(e); + this.events.splice(idx, 1); + }; + return toDisposable(createSingleCallFunction(dispose)); + } + onFirstListenerAdd() { + this.hasListeners = true; + this.events.forEach(e => this.hook(e)); + } + onLastListenerRemove() { + this.hasListeners = false; + this.events.forEach(e => this.unhook(e)); + } + hook(e) { + e.listener = e.event(r => this.emitter.fire(r)); + } + unhook(e) { + e.listener?.dispose(); + e.listener = null; + } + dispose() { + this.emitter.dispose(); + for (const e of this.events) { + e.listener?.dispose(); + } + this.events = []; + } +} +export class DynamicListEventMultiplexer { + _store = new DisposableStore(); + event; + constructor(items, onAddItem, onRemoveItem, getEvent) { + const multiplexer = this._store.add(new EventMultiplexer()); + const itemListeners = this._store.add(new DisposableMap()); + function addItem(instance) { + itemListeners.set(instance, multiplexer.add(getEvent(instance))); + } + // Existing items + for (const instance of items) { + addItem(instance); + } + // Added items + this._store.add(onAddItem(instance => { + addItem(instance); + })); + // Removed items + this._store.add(onRemoveItem(instance => { + itemListeners.deleteAndDispose(instance); + })); + this.event = multiplexer.event; + } + dispose() { + this._store.dispose(); + } +} +/** + * The EventBufferer is useful in situations in which you want + * to delay firing your events during some code. + * You can wrap that code and be sure that the event will not + * be fired during that wrap. + * + * ``` + * const emitter: Emitter; + * const delayer = new EventDelayer(); + * const delayedEvent = delayer.wrapEvent(emitter.event); + * + * delayedEvent(console.log); + * + * delayer.bufferEvents(() => { + * emitter.fire(); // event will not be fired yet + * }); + * + * // event will only be fired at this point + * ``` + */ +export class EventBufferer { + data = []; + wrapEvent(event, reduce, initial) { + return (listener, thisArgs, disposables) => { + return event(i => { + const data = this.data[this.data.length - 1]; + // Non-reduce scenario + if (!reduce) { + // Buffering case + if (data) { + data.buffers.push(() => listener.call(thisArgs, i)); + } + else { + // Not buffering case + listener.call(thisArgs, i); + } + return; + } + // Reduce scenario + const reduceData = data; + // Not buffering case + if (!reduceData) { + // TODO: Is there a way to cache this reduce call for all listeners? + listener.call(thisArgs, reduce(initial, i)); + return; + } + // Buffering case + reduceData.items ??= []; + reduceData.items.push(i); + if (reduceData.buffers.length === 0) { + // Include a single buffered function that will reduce all events when we're done buffering events + data.buffers.push(() => { + // cache the reduced result so that the value can be shared across all listeners + reduceData.reducedResult ??= initial + ? reduceData.items.reduce(reduce, initial) + : reduceData.items.reduce(reduce); + listener.call(thisArgs, reduceData.reducedResult); + }); + } + }, undefined, disposables); + }; + } + bufferEvents(fn) { + const data = { buffers: new Array() }; + this.data.push(data); + const r = fn(); + this.data.pop(); + data.buffers.forEach(flush => flush()); + return r; + } +} +/** + * A Relay is an event forwarder which functions as a replugabble event pipe. + * Once created, you can connect an input event to it and it will simply forward + * events from that input event through its own `event` property. The `input` + * can be changed at any point in time. + */ +export class Relay { + listening = false; + inputEvent = Event.None; + inputEventListener = Disposable.None; + emitter = new Emitter({ + onDidAddFirstListener: () => { + this.listening = true; + this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter); + }, + onDidRemoveLastListener: () => { + this.listening = false; + this.inputEventListener.dispose(); + } + }); + event = this.emitter.event; + set input(event) { + this.inputEvent = event; + if (this.listening) { + this.inputEventListener.dispose(); + this.inputEventListener = event(this.emitter.fire, this.emitter); + } + } + dispose() { + this.inputEventListener.dispose(); + this.emitter.dispose(); + } +} +export class ValueWithChangeEvent { + _value; + static const(value) { + return new ConstValueWithChangeEvent(value); + } + _onDidChange = new Emitter(); + onDidChange = this._onDidChange.event; + constructor(_value) { + this._value = _value; + } + get value() { + return this._value; + } + set value(value) { + if (value !== this._value) { + this._value = value; + this._onDidChange.fire(undefined); + } + } +} +class ConstValueWithChangeEvent { + value; + onDidChange = Event.None; + constructor(value) { + this.value = value; + } +} +/** + * @param handleItem Is called for each item in the set (but only the first time the item is seen in the set). + * The returned disposable is disposed if the item is no longer in the set. + */ +export function trackSetChanges(getData, onDidChangeData, handleItem) { + const map = new DisposableMap(); + let oldData = new Set(getData()); + for (const d of oldData) { + map.set(d, handleItem(d)); + } + const store = new DisposableStore(); + store.add(onDidChangeData(() => { + const newData = getData(); + const diff = diffSets(oldData, newData); + for (const r of diff.removed) { + map.deleteAndDispose(r); + } + for (const a of diff.added) { + map.set(a, handleItem(a)); + } + oldData = new Set(newData); + })); + store.add(map); + return store; +} +//# sourceMappingURL=event.js.map \ No newline at end of file diff --git a/packages/core/dist/event.js.map b/packages/core/dist/event.js.map new file mode 100644 index 00000000..ac1d0caa --- /dev/null +++ b/packages/core/dist/event.js.map @@ -0,0 +1 @@ +{"version":3,"file":"event.js","sourceRoot":"","sources":["../src/event.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAGhG,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,UAAU,EAAE,aAAa,EAAE,eAAe,EAAe,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC3H,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAI3C,0HAA0H;AAC1H,0HAA0H;AAC1H,0HAA0H;AAC1H,MAAM,iCAAiC,GAAG,KAAK,CAE7C;AAGF,0HAA0H;AAC1H,6GAA6G;AAC7G,wDAAwD;AACxD,0HAA0H;AAC1H,MAAM,mCAAmC,GAAG,KAAK,CAE/C;AASF,MAAM,KAAW,KAAK,CAqtBrB;AArtBD,WAAiB,KAAK;IACR,UAAI,GAAe,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;IAEtD,SAAS,qBAAqB,CAAC,OAAuB;QACrD,IAAI,mCAAmC,EAAE;YACxC,MAAM,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,GAAG,OAAO,CAAC;YACzD,MAAM,KAAK,GAAG,UAA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,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC,CAAC;IACJ,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACf,OAAO,KAAK,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/extpath.d.ts b/packages/core/dist/extpath.d.ts new file mode 100644 index 00000000..82d360be --- /dev/null +++ b/packages/core/dist/extpath.d.ts @@ -0,0 +1,56 @@ +export declare function isPathSeparator(code: number): boolean; +/** + * Takes a Windows OS path and changes backward slashes to forward slashes. + * This should only be done for OS paths from Windows (or user provided paths potentially from Windows). + * Using it on a Linux or MaxOS path might change it. + */ +export declare function toSlashes(osPath: string): string; +/** + * Takes a Windows OS path (using backward or forward slashes) and turns it into a posix path: + * - turns backward slashes into forward slashes + * - makes it absolute if it starts with a drive letter + * This should only be done for OS paths from Windows (or user provided paths potentially from Windows). + * Using it on a Linux or MaxOS path might change it. + */ +export declare function toPosixPath(osPath: string): string; +/** + * Computes the _root_ this path, like `getRoot('c:\files') === c:\`, + * `getRoot('files:///files/path') === files:///`, + * or `getRoot('\\server\shares\path') === \\server\shares\` + */ +export declare function getRoot(path: string, sep?: string): string; +/** + * Check if the path follows this pattern: `\\hostname\sharename`. + * + * @see https://msdn.microsoft.com/en-us/library/gg465305.aspx + * @return A boolean indication if the path is a UNC path, on none-windows + * always false. + */ +export declare function isUNC(path: string): boolean; +export declare function isValidBasename(name: string | null | undefined, isWindowsOS?: boolean): boolean; +/** + * @deprecated please use `IUriIdentityService.extUri.isEqual` instead. If you are + * in a context without services, consider to pass down the `extUri` from the outside + * or use `extUriBiasedIgnorePathCase` if you know what you are doing. + */ +export declare function isEqual(pathA: string, pathB: string, ignoreCase?: boolean): boolean; +/** + * @deprecated please use `IUriIdentityService.extUri.isEqualOrParent` instead. If + * you are in a context without services, consider to pass down the `extUri` from the + * outside, or use `extUriBiasedIgnorePathCase` if you know what you are doing. + */ +export declare function isEqualOrParent(base: string, parentCandidate: string, ignoreCase?: boolean, separator?: "/" | "\\"): boolean; +export declare function isWindowsDriveLetter(char0: number): boolean; +export declare function sanitizeFilePath(candidate: string, cwd: string): string; +export declare function removeTrailingPathSeparator(candidate: string): string; +export declare function isRootOrDriveLetter(path: string): boolean; +export declare function hasDriveLetter(path: string, isWindowsOS?: boolean): boolean; +export declare function getDriveLetter(path: string, isWindowsOS?: boolean): string | undefined; +export declare function indexOfPath(path: string, candidate: string, ignoreCase?: boolean): number; +export interface IPathWithLineAndColumn { + path: string; + line?: number; + column?: number; +} +export declare function parseLineAndColumnAware(rawPath: string): IPathWithLineAndColumn; +export declare function randomPath(parent?: string, prefix?: string, randomLength?: number): string; diff --git a/packages/core/dist/extpath.js b/packages/core/dist/extpath.js new file mode 100644 index 00000000..1a04b1a3 --- /dev/null +++ b/packages/core/dist/extpath.js @@ -0,0 +1,347 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { isAbsolute, join, normalize, posix, sep } from './path.js'; +import { isWindows } from './platform.js'; +import { equalsIgnoreCase, rtrim, startsWithIgnoreCase } from './strings.js'; +import { isNumber } from './types.js'; +export function isPathSeparator(code) { + return code === 47 /* CharCode.Slash */ || code === 92 /* CharCode.Backslash */; +} +/** + * Takes a Windows OS path and changes backward slashes to forward slashes. + * This should only be done for OS paths from Windows (or user provided paths potentially from Windows). + * Using it on a Linux or MaxOS path might change it. + */ +export function toSlashes(osPath) { + return osPath.replace(/[\\/]/g, posix.sep); +} +/** + * Takes a Windows OS path (using backward or forward slashes) and turns it into a posix path: + * - turns backward slashes into forward slashes + * - makes it absolute if it starts with a drive letter + * This should only be done for OS paths from Windows (or user provided paths potentially from Windows). + * Using it on a Linux or MaxOS path might change it. + */ +export function toPosixPath(osPath) { + if (osPath.indexOf('/') === -1) { + osPath = toSlashes(osPath); + } + if (/^[a-zA-Z]:(\/|$)/.test(osPath)) { // starts with a drive letter + osPath = '/' + osPath; + } + return osPath; +} +/** + * Computes the _root_ this path, like `getRoot('c:\files') === c:\`, + * `getRoot('files:///files/path') === files:///`, + * or `getRoot('\\server\shares\path') === \\server\shares\` + */ +export function getRoot(path, sep = posix.sep) { + if (!path) { + return ''; + } + const len = path.length; + const firstLetter = path.charCodeAt(0); + if (isPathSeparator(firstLetter)) { + if (isPathSeparator(path.charCodeAt(1))) { + // UNC candidate \\localhost\shares\ddd + // ^^^^^^^^^^^^^^^^^^^ + if (!isPathSeparator(path.charCodeAt(2))) { + let pos = 3; + const start = pos; + for (; pos < len; pos++) { + if (isPathSeparator(path.charCodeAt(pos))) { + break; + } + } + if (start !== pos && !isPathSeparator(path.charCodeAt(pos + 1))) { + pos += 1; + for (; pos < len; pos++) { + if (isPathSeparator(path.charCodeAt(pos))) { + return path.slice(0, pos + 1) // consume this separator + .replace(/[\\/]/g, sep); + } + } + } + } + } + // /user/far + // ^ + return sep; + } + else if (isWindowsDriveLetter(firstLetter)) { + // check for windows drive letter c:\ or c: + if (path.charCodeAt(1) === 58 /* CharCode.Colon */) { + if (isPathSeparator(path.charCodeAt(2))) { + // C:\fff + // ^^^ + return path.slice(0, 2) + sep; + } + else { + // C: + // ^^ + return path.slice(0, 2); + } + } + } + // check for URI + // scheme://authority/path + // ^^^^^^^^^^^^^^^^^^^ + let pos = path.indexOf('://'); + if (pos !== -1) { + pos += 3; // 3 -> "://".length + for (; pos < len; pos++) { + if (isPathSeparator(path.charCodeAt(pos))) { + return path.slice(0, pos + 1); // consume this separator + } + } + } + return ''; +} +/** + * Check if the path follows this pattern: `\\hostname\sharename`. + * + * @see https://msdn.microsoft.com/en-us/library/gg465305.aspx + * @return A boolean indication if the path is a UNC path, on none-windows + * always false. + */ +export function isUNC(path) { + if (!isWindows) { + // UNC is a windows concept + return false; + } + if (!path || path.length < 5) { + // at least \\a\b + return false; + } + let code = path.charCodeAt(0); + if (code !== 92 /* CharCode.Backslash */) { + return false; + } + code = path.charCodeAt(1); + if (code !== 92 /* CharCode.Backslash */) { + return false; + } + let pos = 2; + const start = pos; + for (; pos < path.length; pos++) { + code = path.charCodeAt(pos); + if (code === 92 /* CharCode.Backslash */) { + break; + } + } + if (start === pos) { + return false; + } + code = path.charCodeAt(pos + 1); + if (isNaN(code) || code === 92 /* CharCode.Backslash */) { + return false; + } + return true; +} +// Reference: https://en.wikipedia.org/wiki/Filename +const WINDOWS_INVALID_FILE_CHARS = /[\\/:\*\?"<>\|]/g; +const UNIX_INVALID_FILE_CHARS = /[/]/g; +const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])(\.(.*?))?$/i; +export function isValidBasename(name, isWindowsOS = isWindows) { + const invalidFileChars = isWindowsOS ? WINDOWS_INVALID_FILE_CHARS : UNIX_INVALID_FILE_CHARS; + if (!name || name.length === 0 || /^\s+$/.test(name)) { + return false; // require a name that is not just whitespace + } + invalidFileChars.lastIndex = 0; // the holy grail of software development + if (invalidFileChars.test(name)) { + return false; // check for certain invalid file characters + } + if (isWindowsOS && WINDOWS_FORBIDDEN_NAMES.test(name)) { + return false; // check for certain invalid file names + } + if (name === '.' || name === '..') { + return false; // check for reserved values + } + if (isWindowsOS && name[name.length - 1] === '.') { + return false; // Windows: file cannot end with a "." + } + if (isWindowsOS && name.length !== name.trim().length) { + return false; // Windows: file cannot end with a whitespace + } + if (name.length > 255) { + return false; // most file systems do not allow files > 255 length + } + return true; +} +/** + * @deprecated please use `IUriIdentityService.extUri.isEqual` instead. If you are + * in a context without services, consider to pass down the `extUri` from the outside + * or use `extUriBiasedIgnorePathCase` if you know what you are doing. + */ +export function isEqual(pathA, pathB, ignoreCase) { + const identityEquals = (pathA === pathB); + if (!ignoreCase || identityEquals) { + return identityEquals; + } + if (!pathA || !pathB) { + return false; + } + return equalsIgnoreCase(pathA, pathB); +} +/** + * @deprecated please use `IUriIdentityService.extUri.isEqualOrParent` instead. If + * you are in a context without services, consider to pass down the `extUri` from the + * outside, or use `extUriBiasedIgnorePathCase` if you know what you are doing. + */ +export function isEqualOrParent(base, parentCandidate, ignoreCase, separator = sep) { + if (base === parentCandidate) { + return true; + } + if (!base || !parentCandidate) { + return false; + } + if (parentCandidate.length > base.length) { + return false; + } + if (ignoreCase) { + const beginsWith = startsWithIgnoreCase(base, parentCandidate); + if (!beginsWith) { + return false; + } + if (parentCandidate.length === base.length) { + return true; // same path, different casing + } + let sepOffset = parentCandidate.length; + if (parentCandidate.charAt(parentCandidate.length - 1) === separator) { + sepOffset--; // adjust the expected sep offset in case our candidate already ends in separator character + } + return base.charAt(sepOffset) === separator; + } + if (parentCandidate.charAt(parentCandidate.length - 1) !== separator) { + parentCandidate += separator; + } + return base.indexOf(parentCandidate) === 0; +} +export function isWindowsDriveLetter(char0) { + return char0 >= 65 /* CharCode.A */ && char0 <= 90 /* CharCode.Z */ || char0 >= 97 /* CharCode.a */ && char0 <= 122 /* CharCode.z */; +} +export function sanitizeFilePath(candidate, cwd) { + // Special case: allow to open a drive letter without trailing backslash + if (isWindows && candidate.endsWith(':')) { + candidate += sep; + } + // Ensure absolute + if (!isAbsolute(candidate)) { + candidate = join(cwd, candidate); + } + // Ensure normalized + candidate = normalize(candidate); + // Ensure no trailing slash/backslash + return removeTrailingPathSeparator(candidate); +} +export function removeTrailingPathSeparator(candidate) { + if (isWindows) { + candidate = rtrim(candidate, sep); + // Special case: allow to open drive root ('C:\') + if (candidate.endsWith(':')) { + candidate += sep; + } + } + else { + candidate = rtrim(candidate, sep); + // Special case: allow to open root ('/') + if (!candidate) { + candidate = sep; + } + } + return candidate; +} +export function isRootOrDriveLetter(path) { + const pathNormalized = normalize(path); + if (isWindows) { + if (path.length > 3) { + return false; + } + return hasDriveLetter(pathNormalized) && + (path.length === 2 || pathNormalized.charCodeAt(2) === 92 /* CharCode.Backslash */); + } + return pathNormalized === posix.sep; +} +export function hasDriveLetter(path, isWindowsOS = isWindows) { + if (isWindowsOS) { + return isWindowsDriveLetter(path.charCodeAt(0)) && path.charCodeAt(1) === 58 /* CharCode.Colon */; + } + return false; +} +export function getDriveLetter(path, isWindowsOS = isWindows) { + return hasDriveLetter(path, isWindowsOS) ? path[0] : undefined; +} +export function indexOfPath(path, candidate, ignoreCase) { + if (candidate.length > path.length) { + return -1; + } + if (path === candidate) { + return 0; + } + if (ignoreCase) { + path = path.toLowerCase(); + candidate = candidate.toLowerCase(); + } + return path.indexOf(candidate); +} +export function parseLineAndColumnAware(rawPath) { + const segments = rawPath.split(':'); // C:\file.txt:: + let path = undefined; + let line = undefined; + let column = undefined; + for (const segment of segments) { + const segmentAsNumber = Number(segment); + if (!isNumber(segmentAsNumber)) { + path = !!path ? [path, segment].join(':') : segment; // a colon can well be part of a path (e.g. C:\...) + } + else if (line === undefined) { + line = segmentAsNumber; + } + else if (column === undefined) { + column = segmentAsNumber; + } + } + if (!path) { + throw new Error('Format for `--goto` should be: `FILE:LINE(:COLUMN)`'); + } + return { + path, + line: line !== undefined ? line : undefined, + column: column !== undefined ? column : line !== undefined ? 1 : undefined // if we have a line, make sure column is also set + }; +} +const pathChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; +const windowsSafePathFirstChars = 'BDEFGHIJKMOQRSTUVWXYZbdefghijkmoqrstuvwxyz0123456789'; +export function randomPath(parent, prefix, randomLength = 8) { + let suffix = ''; + for (let i = 0; i < randomLength; i++) { + let pathCharsTouse; + if (i === 0 && isWindows && !prefix && (randomLength === 3 || randomLength === 4)) { + // Windows has certain reserved file names that cannot be used, such + // as AUX, CON, PRN, etc. We want to avoid generating a random name + // that matches that pattern, so we use a different set of characters + // for the first character of the name that does not include any of + // the reserved names first characters. + pathCharsTouse = windowsSafePathFirstChars; + } + else { + pathCharsTouse = pathChars; + } + suffix += pathCharsTouse.charAt(Math.floor(Math.random() * pathCharsTouse.length)); + } + let randomFileName; + if (prefix) { + randomFileName = `${prefix}-${suffix}`; + } + else { + randomFileName = suffix; + } + if (parent) { + return join(parent, randomFileName); + } + return randomFileName; +} +//# sourceMappingURL=extpath.js.map \ No newline at end of file diff --git a/packages/core/dist/extpath.js.map b/packages/core/dist/extpath.js.map new file mode 100644 index 00000000..2facd2b9 --- /dev/null +++ b/packages/core/dist/extpath.js.map @@ -0,0 +1 @@ +{"version":3,"file":"extpath.js","sourceRoot":"","sources":["../src/extpath.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAGhG,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAC7E,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,MAAM,UAAU,eAAe,CAAC,IAAY;IAC3C,OAAO,IAAI,4BAAmB,IAAI,IAAI,gCAAuB,CAAC;AAC/D,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,SAAS,CAAC,MAAc;IACvC,OAAO,MAAM,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;AAC5C,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,MAAc;IACzC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE;QAC/B,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;KAC3B;IACD,IAAI,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,6BAA6B;QACnE,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC;KACtB;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,OAAO,CAAC,IAAY,EAAE,MAAc,KAAK,CAAC,GAAG;IAC5D,IAAI,CAAC,IAAI,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,CAAC;AACvB,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/functional.d.ts b/packages/core/dist/functional.d.ts new file mode 100644 index 00000000..6186556a --- /dev/null +++ b/packages/core/dist/functional.d.ts @@ -0,0 +1,4 @@ +/** + * Given a function, returns a function that is only calling that function once. + */ +export declare function createSingleCallFunction(this: unknown, fn: T, fnDidRunCallback?: () => void): T; diff --git a/packages/core/dist/functional.js b/packages/core/dist/functional.js new file mode 100644 index 00000000..4ddd7ffe --- /dev/null +++ b/packages/core/dist/functional.js @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +/** + * Given a function, returns a function that is only calling that function once. + */ +export function createSingleCallFunction(fn, fnDidRunCallback) { + const _this = this; + let didCall = false; + let result; + return function () { + if (didCall) { + return result; + } + didCall = true; + if (fnDidRunCallback) { + try { + result = fn.apply(_this, arguments); + } + finally { + fnDidRunCallback(); + } + } + else { + result = fn.apply(_this, arguments); + } + return result; + }; +} +//# sourceMappingURL=functional.js.map \ No newline at end of file diff --git a/packages/core/dist/functional.js.map b/packages/core/dist/functional.js.map new file mode 100644 index 00000000..6d89a56a --- /dev/null +++ b/packages/core/dist/functional.js.map @@ -0,0 +1 @@ +{"version":3,"file":"functional.js","sourceRoot":"","sources":["../src/functional.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG;;GAEG;AACH,MAAM,UAAU,wBAAwB,CAAoC,EAAK,EAAE,gBAA6B;IAC/G,MAAM,KAAK,GAAG,IAAI,CAAC;IACnB,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,IAAI,MAAe,CAAC;IAEpB,OAAO;QACN,IAAI,OAAO,EAAE;YACZ,OAAO,MAAM,CAAC;SACd;QAED,OAAO,GAAG,IAAI,CAAC;QACf,IAAI,gBAAgB,EAAE;YACrB,IAAI;gBACH,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;aACpC;oBAAS;gBACT,gBAAgB,EAAE,CAAC;aACnB;SACD;aAAM;YACN,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;SACpC;QAED,OAAO,MAAM,CAAC;IACf,CAAiB,CAAC;AACnB,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/index.d.ts b/packages/core/dist/index.d.ts new file mode 100644 index 00000000..ff6562a2 --- /dev/null +++ b/packages/core/dist/index.d.ts @@ -0,0 +1,12 @@ +export type Hash = Record; +export interface List { + [index: number]: T; + length: number; +} +/** + * Interface of the simple literal object with any string keys. + */ +export type IObjectLiteral = Record; +export type JSONPathExpression = string; +export declare const resolveConfig: (config: any) => any; +export { substitute } from './strings.js'; diff --git a/packages/core/dist/index.js b/packages/core/dist/index.js new file mode 100644 index 00000000..ecbc8d65 --- /dev/null +++ b/packages/core/dist/index.js @@ -0,0 +1,17 @@ +import { substitute } from './strings.js'; +const _resolve = (config) => { + for (const key in config) { + if (config[key] && typeof config[key] == 'string') { + const resolved = substitute(config[key], config); + config[key] = resolved; + } + } + return config; +}; +export const resolveConfig = (config) => { + config = _resolve(config); + config = _resolve(config); + return config; +}; +export { substitute } from './strings.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/core/dist/index.js.map b/packages/core/dist/index.js.map new file mode 100644 index 00000000..b324f24d --- /dev/null +++ b/packages/core/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAgBzC,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,EAAE;IAC1B,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE;QACxB,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,OAAO,MAAM,CAAC,GAAG,CAAC,IAAI,QAAQ,EAAE;YACjD,MAAM,QAAQ,GAAG,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC;YACjD,MAAM,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC;SACxB;KACF;IACD,OAAO,MAAM,CAAC;AAChB,CAAC,CAAA;AACD,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,MAAM,EAAE,EAAE;IACtC,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC1B,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC1B,OAAO,MAAM,CAAC;AAChB,CAAC,CAAA;AAED,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA"} \ No newline at end of file diff --git a/packages/core/dist/iterator.d.ts b/packages/core/dist/iterator.d.ts new file mode 100644 index 00000000..f8d05ebf --- /dev/null +++ b/packages/core/dist/iterator.d.ts @@ -0,0 +1,74 @@ +export declare namespace Iterable { + function is(thing: any): thing is Iterable; + function empty(): Iterable; + function single(element: T): Iterable; + function wrap(iterableOrElement: Iterable | T): Iterable; + function from(iterable: Iterable | undefined | null): Iterable; + function reverse(array: Array): Iterable; + function isEmpty(iterable: Iterable | undefined | null): boolean; + function first(iterable: Iterable): T | undefined; + function some(iterable: Iterable, predicate: (t: T, i: number) => unknown): boolean; + function find(iterable: Iterable, predicate: (t: T) => t is R): R | undefined; + function find(iterable: Iterable, predicate: (t: T) => boolean): T | undefined; + function filter(iterable: Iterable, predicate: (t: T) => t is R): Iterable; + function filter(iterable: Iterable, predicate: (t: T) => boolean): Iterable; + function map(iterable: Iterable, fn: (t: T, index: number) => R): Iterable; + function flatMap(iterable: Iterable, fn: (t: T, index: number) => Iterable): Iterable; + function concat(...iterables: Iterable[]): Iterable; + function reduce(iterable: Iterable, reducer: (previousValue: R, currentValue: T) => R, initialValue: R): R; + /** + * Returns an iterable slice of the array, with the same semantics as `array.slice()`. + */ + function slice(arr: ReadonlyArray, from: number, to?: number): Iterable; + /** + * Consumes `atMost` elements from iterable and returns the consumed elements, + * and an iterable for the rest of the elements. + */ + function consume(iterable: Iterable, atMost?: number): [T[], Iterable]; + function asyncToArray(iterable: AsyncIterable): Promise; +} +export interface IIterator { + next(): T; +} +export declare class ArrayIterator implements IIterator { + private items; + protected start: number; + protected end: number; + protected index: number; + constructor(items: T[], start?: number, end?: number); + first(): T; + next(): T; + protected current(): T; +} +export declare class ArrayNavigator extends ArrayIterator implements INavigator { + constructor(items: T[], start?: number, end?: number); + current(): T; + previous(): T; + first(): T; + last(): T; + parent(): T; +} +export declare class MappedIterator implements IIterator { + protected iterator: IIterator; + protected fn: (item: T) => R; + constructor(iterator: IIterator, fn: (item: T) => R); + next(): R; +} +export interface INavigator extends IIterator { + current(): T; + previous(): T; + parent(): T; + first(): T; + last(): T; + next(): T; +} +export declare class MappedNavigator extends MappedIterator implements INavigator { + protected navigator: INavigator; + constructor(navigator: INavigator, fn: (item: T) => R); + current(): R; + previous(): R; + parent(): R; + first(): R; + last(): R; + next(): R; +} diff --git a/packages/core/dist/iterator.js b/packages/core/dist/iterator.js new file mode 100644 index 00000000..68bb1a44 --- /dev/null +++ b/packages/core/dist/iterator.js @@ -0,0 +1,224 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +export var Iterable; +(function (Iterable) { + function is(thing) { + return thing && typeof thing === 'object' && typeof thing[Symbol.iterator] === 'function'; + } + Iterable.is = is; + const _empty = Object.freeze([]); + function empty() { + return _empty; + } + Iterable.empty = empty; + function* single(element) { + yield element; + } + Iterable.single = single; + function wrap(iterableOrElement) { + if (is(iterableOrElement)) { + return iterableOrElement; + } + else { + return single(iterableOrElement); + } + } + Iterable.wrap = wrap; + function from(iterable) { + return iterable || _empty; + } + Iterable.from = from; + function* reverse(array) { + for (let i = array.length - 1; i >= 0; i--) { + yield array[i]; + } + } + Iterable.reverse = reverse; + function isEmpty(iterable) { + return !iterable || iterable[Symbol.iterator]().next().done === true; + } + Iterable.isEmpty = isEmpty; + function first(iterable) { + return iterable[Symbol.iterator]().next().value; + } + Iterable.first = first; + function some(iterable, predicate) { + let i = 0; + for (const element of iterable) { + if (predicate(element, i++)) { + return true; + } + } + return false; + } + Iterable.some = some; + function find(iterable, predicate) { + for (const element of iterable) { + if (predicate(element)) { + return element; + } + } + return undefined; + } + Iterable.find = find; + function* filter(iterable, predicate) { + for (const element of iterable) { + if (predicate(element)) { + yield element; + } + } + } + Iterable.filter = filter; + function* map(iterable, fn) { + let index = 0; + for (const element of iterable) { + yield fn(element, index++); + } + } + Iterable.map = map; + function* flatMap(iterable, fn) { + let index = 0; + for (const element of iterable) { + yield* fn(element, index++); + } + } + Iterable.flatMap = flatMap; + function* concat(...iterables) { + for (const iterable of iterables) { + yield* iterable; + } + } + Iterable.concat = concat; + function reduce(iterable, reducer, initialValue) { + let value = initialValue; + for (const element of iterable) { + value = reducer(value, element); + } + return value; + } + Iterable.reduce = reduce; + /** + * Returns an iterable slice of the array, with the same semantics as `array.slice()`. + */ + function* slice(arr, from, to = arr.length) { + if (from < -arr.length) { + from = 0; + } + if (from < 0) { + from += arr.length; + } + if (to < 0) { + to += arr.length; + } + else if (to > arr.length) { + to = arr.length; + } + for (; from < to; from++) { + yield arr[from]; + } + } + Iterable.slice = slice; + /** + * Consumes `atMost` elements from iterable and returns the consumed elements, + * and an iterable for the rest of the elements. + */ + function consume(iterable, atMost = Number.POSITIVE_INFINITY) { + const consumed = []; + if (atMost === 0) { + return [consumed, iterable]; + } + const iterator = iterable[Symbol.iterator](); + for (let i = 0; i < atMost; i++) { + const next = iterator.next(); + if (next.done) { + return [consumed, Iterable.empty()]; + } + consumed.push(next.value); + } + return [consumed, { [Symbol.iterator]() { return iterator; } }]; + } + Iterable.consume = consume; + async function asyncToArray(iterable) { + const result = []; + for await (const item of iterable) { + result.push(item); + } + return Promise.resolve(result); + } + Iterable.asyncToArray = asyncToArray; +})(Iterable = Iterable || (Iterable = {})); +export class ArrayIterator { + items; + start; + end; + index; + constructor(items, start = 0, end = items.length) { + this.items = items; + this.start = start; + this.end = end; + this.index = start - 1; + } + first() { + this.index = this.start; + return this.current(); + } + next() { + this.index = Math.min(this.index + 1, this.end); + return this.current(); + } + current() { + if (this.index === this.start - 1 || this.index === this.end) { + return null; + } + return this.items[this.index]; + } +} +export class ArrayNavigator extends ArrayIterator { + constructor(items, start = 0, end = items.length) { + super(items, start, end); + } + current() { + return super.current(); + } + previous() { + this.index = Math.max(this.index - 1, this.start - 1); + return this.current(); + } + first() { + this.index = this.start; + return this.current(); + } + last() { + this.index = this.end - 1; + return this.current(); + } + parent() { + return null; + } +} +export class MappedIterator { + iterator; + fn; + constructor(iterator, fn) { + this.iterator = iterator; + this.fn = fn; + // noop + } + next() { return this.fn(this.iterator.next()); } +} +export class MappedNavigator extends MappedIterator { + navigator; + constructor(navigator, fn) { + super(navigator, fn); + this.navigator = navigator; + } + current() { return this.fn(this.navigator.current()); } + previous() { return this.fn(this.navigator.previous()); } + parent() { return this.fn(this.navigator.parent()); } + first() { return this.fn(this.navigator.first()); } + last() { return this.fn(this.navigator.last()); } + next() { return this.fn(this.navigator.next()); } +} +//# sourceMappingURL=iterator.js.map \ No newline at end of file diff --git a/packages/core/dist/iterator.js.map b/packages/core/dist/iterator.js.map new file mode 100644 index 00000000..3e6fe657 --- /dev/null +++ b/packages/core/dist/iterator.js.map @@ -0,0 +1 @@ +{"version":3,"file":"iterator.js","sourceRoot":"","sources":["../src/iterator.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,MAAM,KAAW,QAAQ,CA4JxB;AA5JD,WAAiB,QAAQ;IAExB,SAAgB,EAAE,CAAU,KAAU;QACrC,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,UAAU,CAAC;IAC3F,CAAC;IAFe,WAAE,KAEjB,CAAA;IAED,MA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c;IAEJ;IAAkC;IAAxD,YAAsB,QAAsB,EAAY,EAAkB;QAApD,aAAQ,GAAR,QAAQ,CAAc;QAAY,OAAE,GAAF,EAAE,CAAgB;QACzE,OAAO;IACR,CAAC;IAED,IAAI,KAAK,OAAO,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;CAChD;AAWD,MAAM,OAAO,eAAsB,SAAQ,cAAoB;IAExC;IAAtB,YAAsB,SAAwB,EAAE,EAAkB;QACjE,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;QADA,cAAS,GAAT,SAAS,CAAe;IAE9C,CAAC;IAED,OAAO,KAAK,OAAO,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC;IACvD,QAAQ,KAAK,OAAO,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;IACzD,MAAM,KAAK,OAAO,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC;IACrD,KAAK,KAAK,OAAO,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;IACnD,IAAI,KAAK,OAAO,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;IACjD,IAAI,KAAK,OAAO,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;CACjD"} \ No newline at end of file diff --git a/packages/core/dist/labels.d.ts b/packages/core/dist/labels.d.ts new file mode 100644 index 00000000..d42315fa --- /dev/null +++ b/packages/core/dist/labels.d.ts @@ -0,0 +1,81 @@ +import { OperatingSystem } from './platform.js'; +import { URI } from './uri.js'; +export interface IPathLabelFormatting { + /** + * The OS the path label is from to produce a label + * that matches OS expectations. + */ + readonly os: OperatingSystem; + /** + * Whether to add a `~` when the path is in the + * user home directory. + * + * Note: this only applies to Linux, macOS but not + * Windows. + */ + readonly tildify?: IUserHomeProvider; + /** + * Whether to convert to a relative path if the path + * is within any of the opened workspace folders. + */ + readonly relative?: IRelativePathProvider; +} +export interface IRelativePathProvider { + /** + * Whether to not add a prefix when in multi-root workspace. + */ + readonly noPrefix?: boolean; + getWorkspace(): { + folders: { + uri: URI; + name?: string; + }[]; + }; + getWorkspaceFolder(resource: URI): { + uri: URI; + name?: string; + } | null; +} +export interface IUserHomeProvider { + userHome: URI; +} +export declare function getPathLabel(resource: URI, formatting: IPathLabelFormatting): string; +export declare function normalizeDriveLetter(path: string, isWindowsOS?: boolean): string; +export declare function tildify(path: string, userHome: string, os?: OperatingSystem): string; +export declare function untildify(path: string, userHome: string): string; +export declare function shorten(paths: string[], pathSeparator?: string): string[]; +export interface ISeparator { + label: string; +} +/** + * Helper to insert values for specific template variables into the string. E.g. "this $(is) a $(template)" can be + * passed to this function together with an object that maps "is" and "template" to strings to have them replaced. + * @param value string to which template is applied + * @param values the values of the templates to use + */ +export declare function template(template: string, values?: { + [key: string]: string | ISeparator | undefined | null; +}): string; +/** + * Handles mnemonics for menu items. Depending on OS: + * - Windows: Supported via & character (replace && with &) + * - Linux: Supported via & character (replace && with &) + * - macOS: Unsupported (replace && with empty string) + */ +export declare function mnemonicMenuLabel(label: string, forceDisableMnemonics?: boolean): string; +/** + * Handles mnemonics for buttons. Depending on OS: + * - Windows: Supported via & character (replace && with & and & with && for escaping) + * - Linux: Supported via _ character (replace && with _) + * - macOS: Unsupported (replace && with empty string) + */ +export declare function mnemonicButtonLabel(label: string, forceDisableMnemonics?: boolean): string; +export declare function unmnemonicLabel(label: string): string; +/** + * Splits a recent label in name and parent path, supporting both '/' and '\' and workspace suffixes. + * If the location is remote, the remote name is included in the name part. + */ +export declare function splitRecentLabel(recentLabel: string): { + name: string; + parentPath: string; +}; diff --git a/packages/core/dist/labels.js b/packages/core/dist/labels.js new file mode 100644 index 00000000..2d8deb60 --- /dev/null +++ b/packages/core/dist/labels.js @@ -0,0 +1,354 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { hasDriveLetter, toSlashes } from './extpath.js'; +import { posix, sep, win32 } from './path.js'; +import { isMacintosh, isWindows, OS } from './platform.js'; +import { extUri, extUriIgnorePathCase } from './resources.js'; +import { rtrim, startsWithIgnoreCase } from './strings.js'; +export function getPathLabel(resource, formatting) { + const { os, tildify: tildifier, relative: relatifier } = formatting; + // return early with a relative path if we can resolve one + if (relatifier) { + const relativePath = getRelativePathLabel(resource, relatifier, os); + if (typeof relativePath === 'string') { + return relativePath; + } + } + // otherwise try to resolve a absolute path label and + // apply target OS standard path separators if target + // OS differs from actual OS we are running in + let absolutePath = resource.fsPath; + if (os === 1 /* OperatingSystem.Windows */ && !isWindows) { + absolutePath = absolutePath.replace(/\//g, '\\'); + } + else if (os !== 1 /* OperatingSystem.Windows */ && isWindows) { + absolutePath = absolutePath.replace(/\\/g, '/'); + } + // macOS/Linux: tildify with provided user home directory + if (os !== 1 /* OperatingSystem.Windows */ && tildifier?.userHome) { + const userHome = tildifier.userHome.fsPath; + // This is a bit of a hack, but in order to figure out if the + // resource is in the user home, we need to make sure to convert it + // to a user home resource. We cannot assume that the resource is + // already a user home resource. + let userHomeCandidate; + if (resource.scheme !== tildifier.userHome.scheme && resource.path[0] === posix.sep && resource.path[1] !== posix.sep) { + userHomeCandidate = tildifier.userHome.with({ path: resource.path }).fsPath; + } + else { + userHomeCandidate = absolutePath; + } + absolutePath = tildify(userHomeCandidate, userHome, os); + } + // normalize + const pathLib = os === 1 /* OperatingSystem.Windows */ ? win32 : posix; + return pathLib.normalize(normalizeDriveLetter(absolutePath, os === 1 /* OperatingSystem.Windows */)); +} +function getRelativePathLabel(resource, relativePathProvider, os) { + const pathLib = os === 1 /* OperatingSystem.Windows */ ? win32 : posix; + const extUriLib = os === 3 /* OperatingSystem.Linux */ ? extUri : extUriIgnorePathCase; + const workspace = relativePathProvider.getWorkspace(); + const firstFolder = workspace.folders.at(0); + if (!firstFolder) { + return undefined; + } + // This is a bit of a hack, but in order to figure out the folder + // the resource belongs to, we need to make sure to convert it + // to a workspace resource. We cannot assume that the resource is + // already matching the workspace. + if (resource.scheme !== firstFolder.uri.scheme && resource.path[0] === posix.sep && resource.path[1] !== posix.sep) { + resource = firstFolder.uri.with({ path: resource.path }); + } + const folder = relativePathProvider.getWorkspaceFolder(resource); + if (!folder) { + return undefined; + } + let relativePathLabel = undefined; + if (extUriLib.isEqual(folder.uri, resource)) { + relativePathLabel = ''; // no label if paths are identical + } + else { + relativePathLabel = extUriLib.relativePath(folder.uri, resource) ?? ''; + } + // normalize + if (relativePathLabel) { + relativePathLabel = pathLib.normalize(relativePathLabel); + } + // always show root basename if there are multiple folders + if (workspace.folders.length > 1 && !relativePathProvider.noPrefix) { + const rootName = folder.name ? folder.name : extUriLib.basenameOrAuthority(folder.uri); + relativePathLabel = relativePathLabel ? `${rootName} • ${relativePathLabel}` : rootName; + } + return relativePathLabel; +} +export function normalizeDriveLetter(path, isWindowsOS = isWindows) { + if (hasDriveLetter(path, isWindowsOS)) { + return path.charAt(0).toUpperCase() + path.slice(1); + } + return path; +} +let normalizedUserHomeCached = Object.create(null); +export function tildify(path, userHome, os = OS) { + if (os === 1 /* OperatingSystem.Windows */ || !path || !userHome) { + return path; // unsupported on Windows + } + let normalizedUserHome = normalizedUserHomeCached.original === userHome ? normalizedUserHomeCached.normalized : undefined; + if (!normalizedUserHome) { + normalizedUserHome = userHome; + if (isWindows) { + normalizedUserHome = toSlashes(normalizedUserHome); // make sure that the path is POSIX normalized on Windows + } + normalizedUserHome = `${rtrim(normalizedUserHome, posix.sep)}${posix.sep}`; + normalizedUserHomeCached = { original: userHome, normalized: normalizedUserHome }; + } + let normalizedPath = path; + if (isWindows) { + normalizedPath = toSlashes(normalizedPath); // make sure that the path is POSIX normalized on Windows + } + // Linux: case sensitive, macOS: case insensitive + if (os === 3 /* OperatingSystem.Linux */ ? normalizedPath.startsWith(normalizedUserHome) : startsWithIgnoreCase(normalizedPath, normalizedUserHome)) { + return `~/${normalizedPath.substr(normalizedUserHome.length)}`; + } + return path; +} +export function untildify(path, userHome) { + return path.replace(/^~($|\/|\\)/, `${userHome}$1`); +} +/** + * Shortens the paths but keeps them easy to distinguish. + * Replaces not important parts with ellipsis. + * Every shorten path matches only one original path and vice versa. + * + * Algorithm for shortening paths is as follows: + * 1. For every path in list, find unique substring of that path. + * 2. Unique substring along with ellipsis is shortened path of that path. + * 3. To find unique substring of path, consider every segment of length from 1 to path.length of path from end of string + * and if present segment is not substring to any other paths then present segment is unique path, + * else check if it is not present as suffix of any other path and present segment is suffix of path itself, + * if it is true take present segment as unique path. + * 4. Apply ellipsis to unique segment according to whether segment is present at start/in-between/end of path. + * + * Example 1 + * 1. consider 2 paths i.e. ['a\\b\\c\\d', 'a\\f\\b\\c\\d'] + * 2. find unique path of first path, + * a. 'd' is present in path2 and is suffix of path2, hence not unique of present path. + * b. 'c' is present in path2 and 'c' is not suffix of present path, similarly for 'b' and 'a' also. + * c. 'd\\c' is suffix of path2. + * d. 'b\\c' is not suffix of present path. + * e. 'a\\b' is not present in path2, hence unique path is 'a\\b...'. + * 3. for path2, 'f' is not present in path1 hence unique is '...\\f\\...'. + * + * Example 2 + * 1. consider 2 paths i.e. ['a\\b', 'a\\b\\c']. + * a. Even if 'b' is present in path2, as 'b' is suffix of path1 and is not suffix of path2, unique path will be '...\\b'. + * 2. for path2, 'c' is not present in path1 hence unique path is '..\\c'. + */ +const ellipsis = '\u2026'; +const unc = '\\\\'; +const home = '~'; +export function shorten(paths, pathSeparator = sep) { + const shortenedPaths = new Array(paths.length); + // for every path + let match = false; + for (let pathIndex = 0; pathIndex < paths.length; pathIndex++) { + const originalPath = paths[pathIndex]; + if (originalPath === '') { + shortenedPaths[pathIndex] = `.${pathSeparator}`; + continue; + } + if (!originalPath) { + shortenedPaths[pathIndex] = originalPath; + continue; + } + match = true; + // trim for now and concatenate unc path (e.g. \\network) or root path (/etc, ~/etc) later + let prefix = ''; + let trimmedPath = originalPath; + if (trimmedPath.indexOf(unc) === 0) { + prefix = trimmedPath.substr(0, trimmedPath.indexOf(unc) + unc.length); + trimmedPath = trimmedPath.substr(trimmedPath.indexOf(unc) + unc.length); + } + else if (trimmedPath.indexOf(pathSeparator) === 0) { + prefix = trimmedPath.substr(0, trimmedPath.indexOf(pathSeparator) + pathSeparator.length); + trimmedPath = trimmedPath.substr(trimmedPath.indexOf(pathSeparator) + pathSeparator.length); + } + else if (trimmedPath.indexOf(home) === 0) { + prefix = trimmedPath.substr(0, trimmedPath.indexOf(home) + home.length); + trimmedPath = trimmedPath.substr(trimmedPath.indexOf(home) + home.length); + } + // pick the first shortest subpath found + const segments = trimmedPath.split(pathSeparator); + for (let subpathLength = 1; match && subpathLength <= segments.length; subpathLength++) { + for (let start = segments.length - subpathLength; match && start >= 0; start--) { + match = false; + let subpath = segments.slice(start, start + subpathLength).join(pathSeparator); + // that is unique to any other path + for (let otherPathIndex = 0; !match && otherPathIndex < paths.length; otherPathIndex++) { + // suffix subpath treated specially as we consider no match 'x' and 'x/...' + if (otherPathIndex !== pathIndex && paths[otherPathIndex] && paths[otherPathIndex].indexOf(subpath) > -1) { + const isSubpathEnding = (start + subpathLength === segments.length); + // Adding separator as prefix for subpath, such that 'endsWith(src, trgt)' considers subpath as directory name instead of plain string. + // prefix is not added when either subpath is root directory or path[otherPathIndex] does not have multiple directories. + const subpathWithSep = (start > 0 && paths[otherPathIndex].indexOf(pathSeparator) > -1) ? pathSeparator + subpath : subpath; + const isOtherPathEnding = paths[otherPathIndex].endsWith(subpathWithSep); + match = !isSubpathEnding || isOtherPathEnding; + } + } + // found unique subpath + if (!match) { + let result = ''; + // preserve disk drive or root prefix + if (segments[0].endsWith(':') || prefix !== '') { + if (start === 1) { + // extend subpath to include disk drive prefix + start = 0; + subpathLength++; + subpath = segments[0] + pathSeparator + subpath; + } + if (start > 0) { + result = segments[0] + pathSeparator; + } + result = prefix + result; + } + // add ellipsis at the beginning if needed + if (start > 0) { + result = result + ellipsis + pathSeparator; + } + result = result + subpath; + // add ellipsis at the end if needed + if (start + subpathLength < segments.length) { + result = result + pathSeparator + ellipsis; + } + shortenedPaths[pathIndex] = result; + } + } + } + if (match) { + shortenedPaths[pathIndex] = originalPath; // use original path if no unique subpaths found + } + } + return shortenedPaths; +} +var Type; +(function (Type) { + Type[Type["TEXT"] = 0] = "TEXT"; + Type[Type["VARIABLE"] = 1] = "VARIABLE"; + Type[Type["SEPARATOR"] = 2] = "SEPARATOR"; +})(Type || (Type = {})); +/** + * Helper to insert values for specific template variables into the string. E.g. "this $(is) a $(template)" can be + * passed to this function together with an object that maps "is" and "template" to strings to have them replaced. + * @param value string to which template is applied + * @param values the values of the templates to use + */ +export function template(template, values = Object.create(null)) { + const segments = []; + let inVariable = false; + let curVal = ''; + for (const char of template) { + // Beginning of variable + if (char === '$' || (inVariable && char === '{')) { + if (curVal) { + segments.push({ value: curVal, type: Type.TEXT }); + } + curVal = ''; + inVariable = true; + } + // End of variable + else if (char === '}' && inVariable) { + const resolved = values[curVal]; + // Variable + if (typeof resolved === 'string') { + if (resolved.length) { + segments.push({ value: resolved, type: Type.VARIABLE }); + } + } + // Separator + else if (resolved) { + const prevSegment = segments[segments.length - 1]; + if (!prevSegment || prevSegment.type !== Type.SEPARATOR) { + segments.push({ value: resolved.label, type: Type.SEPARATOR }); // prevent duplicate separators + } + } + curVal = ''; + inVariable = false; + } + // Text or Variable Name + else { + curVal += char; + } + } + // Tail + if (curVal && !inVariable) { + segments.push({ value: curVal, type: Type.TEXT }); + } + return segments.filter((segment, index) => { + // Only keep separator if we have values to the left and right + if (segment.type === Type.SEPARATOR) { + const left = segments[index - 1]; + const right = segments[index + 1]; + return [left, right].every(segment => segment && (segment.type === Type.VARIABLE || segment.type === Type.TEXT) && segment.value.length > 0); + } + // accept any TEXT and VARIABLE + return true; + }).map(segment => segment.value).join(''); +} +/** + * Handles mnemonics for menu items. Depending on OS: + * - Windows: Supported via & character (replace && with &) + * - Linux: Supported via & character (replace && with &) + * - macOS: Unsupported (replace && with empty string) + */ +export function mnemonicMenuLabel(label, forceDisableMnemonics) { + if (isMacintosh || forceDisableMnemonics) { + return label.replace(/\(&&\w\)|&&/g, '').replace(/&/g, isMacintosh ? '&' : '&&'); + } + return label.replace(/&&|&/g, m => m === '&' ? '&&' : '&'); +} +/** + * Handles mnemonics for buttons. Depending on OS: + * - Windows: Supported via & character (replace && with & and & with && for escaping) + * - Linux: Supported via _ character (replace && with _) + * - macOS: Unsupported (replace && with empty string) + */ +export function mnemonicButtonLabel(label, forceDisableMnemonics) { + if (isMacintosh || forceDisableMnemonics) { + return label.replace(/\(&&\w\)|&&/g, ''); + } + if (isWindows) { + return label.replace(/&&|&/g, m => m === '&' ? '&&' : '&'); + } + return label.replace(/&&/g, '_'); +} +export function unmnemonicLabel(label) { + return label.replace(/&/g, '&&'); +} +/** + * Splits a recent label in name and parent path, supporting both '/' and '\' and workspace suffixes. + * If the location is remote, the remote name is included in the name part. + */ +export function splitRecentLabel(recentLabel) { + if (recentLabel.endsWith(']')) { + // label with workspace suffix + const lastIndexOfSquareBracket = recentLabel.lastIndexOf(' [', recentLabel.length - 2); + if (lastIndexOfSquareBracket !== -1) { + const split = splitName(recentLabel.substring(0, lastIndexOfSquareBracket)); + const remoteNameWithSpace = recentLabel.substring(lastIndexOfSquareBracket); + return { name: split.name + remoteNameWithSpace, parentPath: split.parentPath }; + } + } + return splitName(recentLabel); +} +function splitName(fullPath) { + const p = fullPath.indexOf('/') !== -1 ? posix : win32; + const name = p.basename(fullPath); + const parentPath = p.dirname(fullPath); + if (name.length) { + return { name, parentPath }; + } + // only the root segment + return { name: parentPath, parentPath: '' }; +} +//# sourceMappingURL=labels.js.map \ No newline at end of file diff --git a/packages/core/dist/labels.js.map b/packages/core/dist/labels.js.map new file mode 100644 index 00000000..dd9131cd --- /dev/null +++ b/packages/core/dist/labels.js.map @@ -0,0 +1 @@ +{"version":3,"file":"labels.js","sourceRoot":"","sources":["../src/labels.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,SAAS,EAAmB,EAAE,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EAAE,MAAM,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC9D,OAAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AA0C3D,MAAM,UAAU,YAAY,CAAC,QAAa,EAAE,UAAgC;IAC3E,MAAM,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,UAAU,CAAC;IAEpE,0DAA0D;IAC1D,IAAI,UAAU,EAAE;QACf,MAAM,YAAY,GAAG,oBAAoB,CAAC,QAAQ,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC;QACpE,IAAI,OAAO,YAAY,KAAK,QAAQ,EAAE;YACrC,OAAO,YAAY,CAAC;SACpB;KACD;IAED,qDAAqD;IACrD,qDAAqD;IACrD,8CAA8C;IAC9C,IAAI,YAAY,GAAG,QAAQ,CAAC,MAAM,CAAC;IACnC,IAAI,EAAE,oCAA4B,IAAI,CAAC,SAAS,EAAE;QACjD,YAAY,GAAG,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;KACjD;SAAM,IAAI,EAAE,oCAA4B,IAAI,SAAS,EAAE;QACvD,YAAY,GAAG,YAAY,CAAC,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C/B,CAAC;AAED,SAAS,SAAS,CAAC,QAAgB;IAClC,MAAM,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC;IACvD,MAAM,IAAI,GAAG,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAClC,MAAM,UAAU,GAAG,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACvC,IAAI,IAAI,CAAC,MAAM,EAAE;QAChB,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;KAC5B;IACD,wBAAwB;IACxB,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;AAC7C,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/lazy.d.ts b/packages/core/dist/lazy.d.ts new file mode 100644 index 00000000..47ff2d9b --- /dev/null +++ b/packages/core/dist/lazy.d.ts @@ -0,0 +1,22 @@ +export declare class Lazy { + private readonly executor; + private _didRun; + private _value?; + private _error; + constructor(executor: () => T); + /** + * True if the lazy value has been resolved. + */ + get hasValue(): boolean; + /** + * Get the wrapped value. + * + * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only + * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value + */ + get value(): T; + /** + * Get the wrapped value without forcing evaluation. + */ + get rawValue(): T | undefined; +} diff --git a/packages/core/dist/lazy.js b/packages/core/dist/lazy.js new file mode 100644 index 00000000..070258b2 --- /dev/null +++ b/packages/core/dist/lazy.js @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +export class Lazy { + executor; + _didRun = false; + _value; + _error; + constructor(executor) { + this.executor = executor; + } + /** + * True if the lazy value has been resolved. + */ + get hasValue() { return this._didRun; } + /** + * Get the wrapped value. + * + * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only + * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value + */ + get value() { + if (!this._didRun) { + try { + this._value = this.executor(); + } + catch (err) { + this._error = err; + } + finally { + this._didRun = true; + } + } + if (this._error) { + throw this._error; + } + return this._value; + } + /** + * Get the wrapped value without forcing evaluation. + */ + get rawValue() { return this._value; } +} +//# sourceMappingURL=lazy.js.map \ No newline at end of file diff --git a/packages/core/dist/lazy.js.map b/packages/core/dist/lazy.js.map new file mode 100644 index 00000000..3c96fcf7 --- /dev/null +++ b/packages/core/dist/lazy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lazy.js","sourceRoot":"","sources":["../src/lazy.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,MAAM,OAAO,IAAI;IAOE;IALV,OAAO,GAAY,KAAK,CAAC;IACzB,MAAM,CAAK;IACX,MAAM,CAAoB;IAElC,YACkB,QAAiB;QAAjB,aAAQ,GAAR,QAAQ,CAAS;IAC/B,CAAC;IAEL;;OAEG;IACH,IAAI,QAAQ,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAEvC;;;;;OAKG;IACH,IAAI,KAAK;QACR,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;YAClB,IAAI;gBACH,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC;aAC9B;YAAC,OAAO,GAAG,EAAE;gBACb,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC;aAClB;oBAAS;gBACT,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;aACpB;SACD;QACD,IAAI,IAAI,CAAC,MAAM,EAAE;YAChB,MAAM,IAAI,CAAC,MAAM,CAAC;SAClB;QACD,OAAO,IAAI,CAAC,MAAO,CAAC;IACrB,CAAC;IAED;;OAEG;IACH,IAAI,QAAQ,KAAoB,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;CACrD"} \ No newline at end of file diff --git a/packages/core/dist/lifecycle.d.ts b/packages/core/dist/lifecycle.d.ts new file mode 100644 index 00000000..9969a3d1 --- /dev/null +++ b/packages/core/dist/lifecycle.d.ts @@ -0,0 +1,261 @@ +export interface IDisposableTracker { + /** + * Is called on construction of a disposable. + */ + trackDisposable(disposable: IDisposable): void; + /** + * Is called when a disposable is registered as child of another disposable (e.g. {@link DisposableStore}). + * If parent is `null`, the disposable is removed from its former parent. + */ + setParent(child: IDisposable, parent: IDisposable | null): void; + /** + * Is called after a disposable is disposed. + */ + markAsDisposed(disposable: IDisposable): void; + /** + * Indicates that the given object is a singleton which does not need to be disposed. + */ + markAsSingleton(disposable: IDisposable): void; +} +export declare class GCBasedDisposableTracker implements IDisposableTracker { + private readonly _registry; + trackDisposable(disposable: IDisposable): void; + setParent(child: IDisposable, parent: IDisposable | null): void; + markAsDisposed(disposable: IDisposable): void; + markAsSingleton(disposable: IDisposable): void; +} +export interface DisposableInfo { + value: IDisposable; + source: string | null; + parent: IDisposable | null; + isSingleton: boolean; + idx: number; +} +export declare class DisposableTracker implements IDisposableTracker { + private static idx; + private readonly livingDisposables; + private getDisposableData; + trackDisposable(d: IDisposable): void; + setParent(child: IDisposable, parent: IDisposable | null): void; + markAsDisposed(x: IDisposable): void; + markAsSingleton(disposable: IDisposable): void; + private getRootParent; + getTrackedDisposables(): IDisposable[]; + computeLeakingDisposables(maxReported?: number, preComputedLeaks?: DisposableInfo[]): { + leaks: DisposableInfo[]; + details: string; + } | undefined; +} +export declare function setDisposableTracker(tracker: IDisposableTracker | null): void; +export declare function trackDisposable(x: T): T; +export declare function markAsDisposed(disposable: IDisposable): void; +/** + * Indicates that the given object is a singleton which does not need to be disposed. +*/ +export declare function markAsSingleton(singleton: T): T; +/** + * An object that performs a cleanup operation when `.dispose()` is called. + * + * Some examples of how disposables are used: + * + * - An event listener that removes itself when `.dispose()` is called. + * - A resource such as a file system watcher that cleans up the resource when `.dispose()` is called. + * - The return value from registering a provider. When `.dispose()` is called, the provider is unregistered. + */ +export interface IDisposable { + dispose(): void; +} +/** + * Check if `thing` is {@link IDisposable disposable}. + */ +export declare function isDisposable(thing: E): thing is E & IDisposable; +/** + * Disposes of the value(s) passed in. + */ +export declare function dispose(disposable: T): T; +export declare function dispose(disposable: T | undefined): T | undefined; +export declare function dispose = Iterable>(disposables: A): A; +export declare function dispose(disposables: Array): Array; +export declare function dispose(disposables: ReadonlyArray): ReadonlyArray; +export declare function disposeIfDisposable(disposables: Array): Array; +/** + * Combine multiple disposable values into a single {@link IDisposable}. + */ +export declare function combinedDisposable(...disposables: IDisposable[]): IDisposable; +/** + * Turn a function that implements dispose into an {@link IDisposable}. + * + * @param fn Clean up function, guaranteed to be called only **once**. + */ +export declare function toDisposable(fn: () => void): IDisposable; +/** + * Manages a collection of disposable values. + * + * This is the preferred way to manage multiple disposables. A `DisposableStore` is safer to work with than an + * `IDisposable[]` as it considers edge cases, such as registering the same value multiple times or adding an item to a + * store that has already been disposed of. + */ +export declare class DisposableStore implements IDisposable { + static DISABLE_DISPOSED_WARNING: boolean; + private readonly _toDispose; + private _isDisposed; + constructor(); + /** + * Dispose of all registered disposables and mark this object as disposed. + * + * Any future disposables added to this object will be disposed of on `add`. + */ + dispose(): void; + /** + * @return `true` if this object has been disposed of. + */ + get isDisposed(): boolean; + /** + * Dispose of all registered disposables but do not mark this object as disposed. + */ + clear(): void; + /** + * Add a new {@link IDisposable disposable} to the collection. + */ + add(o: T): T; + /** + * Deletes a disposable from store and disposes of it. This will not throw or warn and proceed to dispose the + * disposable even when the disposable is not part in the store. + */ + delete(o: T): void; + /** + * Deletes the value from the store, but does not dispose it. + */ + deleteAndLeak(o: T): void; +} +/** + * Abstract base class for a {@link IDisposable disposable} object. + * + * Subclasses can {@linkcode _register} disposables that will be automatically cleaned up when this object is disposed of. + */ +export declare abstract class Disposable implements IDisposable { + /** + * A disposable that does nothing when it is disposed of. + * + * TODO: This should not be a static property. + */ + static readonly None: Readonly; + protected readonly _store: DisposableStore; + constructor(); + dispose(): void; + /** + * Adds `o` to the collection of disposables managed by this object. + */ + protected _register(o: T): T; +} +/** + * Manages the lifecycle of a disposable value that may be changed. + * + * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can + * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up. + */ +export declare class MutableDisposable implements IDisposable { + private _value?; + private _isDisposed; + constructor(); + get value(): T | undefined; + set value(value: T | undefined); + /** + * Resets the stored value and disposed of the previously stored value. + */ + clear(): void; + dispose(): void; + /** + * Clears the value, but does not dispose it. + * The old value is returned. + */ + clearAndLeak(): T | undefined; +} +/** + * Manages the lifecycle of a disposable value that may be changed like {@link MutableDisposable}, but the value must + * exist and cannot be undefined. + */ +export declare class MandatoryMutableDisposable implements IDisposable { + private readonly _disposable; + private _isDisposed; + constructor(initialValue: T); + get value(): T; + set value(value: T); + dispose(): void; +} +export declare class RefCountedDisposable { + private readonly _disposable; + private _counter; + constructor(_disposable: IDisposable); + acquire(): this; + release(): this; +} +/** + * A safe disposable can be `unset` so that a leaked reference (listener) + * can be cut-off. + */ +export declare class SafeDisposable implements IDisposable { + dispose: () => void; + unset: () => void; + isset: () => boolean; + constructor(); + set(fn: Function): this; +} +export interface IReference extends IDisposable { + readonly object: T; +} +export declare abstract class ReferenceCollection { + private readonly references; + acquire(key: string, ...args: any[]): IReference; + protected abstract createReferencedObject(key: string, ...args: any[]): T; + protected abstract destroyReferencedObject(key: string, object: T): void; +} +/** + * Unwraps a reference collection of promised values. Makes sure + * references are disposed whenever promises get rejected. + */ +export declare class AsyncReferenceCollection { + private referenceCollection; + constructor(referenceCollection: ReferenceCollection>); + acquire(key: string, ...args: any[]): Promise>; +} +export declare class ImmortalReference implements IReference { + object: T; + constructor(object: T); + dispose(): void; +} +export declare function disposeOnReturn(fn: (store: DisposableStore) => void): void; +/** + * A map the manages the lifecycle of the values that it stores. + */ +export declare class DisposableMap implements IDisposable { + private readonly _store; + private _isDisposed; + constructor(); + /** + * Disposes of all stored values and mark this object as disposed. + * + * Trying to use this object after it has been disposed of is an error. + */ + dispose(): void; + /** + * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed. + */ + clearAndDisposeAll(): void; + has(key: K): boolean; + get size(): number; + get(key: K): V | undefined; + set(key: K, value: V, skipDisposeOnOverwrite?: boolean): void; + /** + * Delete the value stored for `key` from this map and also dispose of it. + */ + deleteAndDispose(key: K): void; + /** + * Delete the value stored for `key` from this map but return it. The caller is + * responsible for disposing of the value. + */ + deleteAndLeak(key: K): V | undefined; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[K, V]>; +} diff --git a/packages/core/dist/lifecycle.js b/packages/core/dist/lifecycle.js new file mode 100644 index 00000000..1beb218b --- /dev/null +++ b/packages/core/dist/lifecycle.js @@ -0,0 +1,658 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { compareBy, numberComparator } from './arrays.js'; +import { groupBy } from './collections.js'; +import { SetMap } from './map.js'; +import { createSingleCallFunction } from './functional.js'; +import { Iterable } from './iterator.js'; +// #region Disposable Tracking +/** + * Enables logging of potentially leaked disposables. + * + * A disposable is considered leaked if it is not disposed or not registered as the child of + * another disposable. This tracking is very simple an only works for classes that either + * extend Disposable or use a DisposableStore. This means there are a lot of false positives. + */ +const TRACK_DISPOSABLES = false; +let disposableTracker = null; +export class GCBasedDisposableTracker { + _registry = new FinalizationRegistry(heldValue => { + console.warn(`[LEAKED DISPOSABLE] ${heldValue}`); + }); + trackDisposable(disposable) { + const stack = new Error('CREATED via:').stack; + this._registry.register(disposable, stack, disposable); + } + setParent(child, parent) { + if (parent) { + this._registry.unregister(child); + } + else { + this.trackDisposable(child); + } + } + markAsDisposed(disposable) { + this._registry.unregister(disposable); + } + markAsSingleton(disposable) { + this._registry.unregister(disposable); + } +} +export class DisposableTracker { + static idx = 0; + livingDisposables = new Map(); + getDisposableData(d) { + let val = this.livingDisposables.get(d); + if (!val) { + val = { parent: null, source: null, isSingleton: false, value: d, idx: DisposableTracker.idx++ }; + this.livingDisposables.set(d, val); + } + return val; + } + trackDisposable(d) { + const data = this.getDisposableData(d); + if (!data.source) { + data.source = + new Error().stack; + } + } + setParent(child, parent) { + const data = this.getDisposableData(child); + data.parent = parent; + } + markAsDisposed(x) { + this.livingDisposables.delete(x); + } + markAsSingleton(disposable) { + this.getDisposableData(disposable).isSingleton = true; + } + getRootParent(data, cache) { + const cacheValue = cache.get(data); + if (cacheValue) { + return cacheValue; + } + const result = data.parent ? this.getRootParent(this.getDisposableData(data.parent), cache) : data; + cache.set(data, result); + return result; + } + getTrackedDisposables() { + const rootParentCache = new Map(); + const leaking = [...this.livingDisposables.entries()] + .filter(([, v]) => v.source !== null && !this.getRootParent(v, rootParentCache).isSingleton) + .flatMap(([k]) => k); + return leaking; + } + computeLeakingDisposables(maxReported = 10, preComputedLeaks) { + let uncoveredLeakingObjs; + if (preComputedLeaks) { + uncoveredLeakingObjs = preComputedLeaks; + } + else { + const rootParentCache = new Map(); + const leakingObjects = [...this.livingDisposables.values()] + .filter((info) => info.source !== null && !this.getRootParent(info, rootParentCache).isSingleton); + if (leakingObjects.length === 0) { + return; + } + const leakingObjsSet = new Set(leakingObjects.map(o => o.value)); + // Remove all objects that are a child of other leaking objects. Assumes there are no cycles. + uncoveredLeakingObjs = leakingObjects.filter(l => { + return !(l.parent && leakingObjsSet.has(l.parent)); + }); + if (uncoveredLeakingObjs.length === 0) { + throw new Error('There are cyclic diposable chains!'); + } + } + if (!uncoveredLeakingObjs) { + return undefined; + } + function getStackTracePath(leaking) { + function removePrefix(array, linesToRemove) { + while (array.length > 0 && linesToRemove.some(regexp => typeof regexp === 'string' ? regexp === array[0] : array[0].match(regexp))) { + array.shift(); + } + } + const lines = leaking.source.split('\n').map(p => p.trim().replace('at ', '')).filter(l => l !== ''); + removePrefix(lines, ['Error', /^trackDisposable \(.*\)$/, /^DisposableTracker.trackDisposable \(.*\)$/]); + return lines.reverse(); + } + const stackTraceStarts = new SetMap(); + for (const leaking of uncoveredLeakingObjs) { + const stackTracePath = getStackTracePath(leaking); + for (let i = 0; i <= stackTracePath.length; i++) { + stackTraceStarts.add(stackTracePath.slice(0, i).join('\n'), leaking); + } + } + // Put earlier leaks first + uncoveredLeakingObjs.sort(compareBy(l => l.idx, numberComparator)); + let message = ''; + let i = 0; + for (const leaking of uncoveredLeakingObjs.slice(0, maxReported)) { + i++; + const stackTracePath = getStackTracePath(leaking); + const stackTraceFormattedLines = []; + for (let i = 0; i < stackTracePath.length; i++) { + let line = stackTracePath[i]; + const starts = stackTraceStarts.get(stackTracePath.slice(0, i + 1).join('\n')); + line = `(shared with ${starts.size}/${uncoveredLeakingObjs.length} leaks) at ${line}`; + const prevStarts = stackTraceStarts.get(stackTracePath.slice(0, i).join('\n')); + const continuations = groupBy([...prevStarts].map(d => getStackTracePath(d)[i]), v => v); + delete continuations[stackTracePath[i]]; + for (const [cont, set] of Object.entries(continuations)) { + stackTraceFormattedLines.unshift(` - stacktraces of ${set.length} other leaks continue with ${cont}`); + } + stackTraceFormattedLines.unshift(line); + } + message += `\n\n\n==================== Leaking disposable ${i}/${uncoveredLeakingObjs.length}: ${leaking.value.constructor.name} ====================\n${stackTraceFormattedLines.join('\n')}\n============================================================\n\n`; + } + if (uncoveredLeakingObjs.length > maxReported) { + message += `\n\n\n... and ${uncoveredLeakingObjs.length - maxReported} more leaking disposables\n\n`; + } + return { leaks: uncoveredLeakingObjs, details: message }; + } +} +export function setDisposableTracker(tracker) { + disposableTracker = tracker; +} +if (TRACK_DISPOSABLES) { + const __is_disposable_tracked__ = '__is_disposable_tracked__'; + setDisposableTracker(new class { + trackDisposable(x) { + const stack = new Error('Potentially leaked disposable').stack; + setTimeout(() => { + if (!x[__is_disposable_tracked__]) { + console.log(stack); + } + }, 3000); + } + setParent(child, parent) { + if (child && child !== Disposable.None) { + try { + child[__is_disposable_tracked__] = true; + } + catch { + // noop + } + } + } + markAsDisposed(disposable) { + if (disposable && disposable !== Disposable.None) { + try { + disposable[__is_disposable_tracked__] = true; + } + catch { + // noop + } + } + } + markAsSingleton(disposable) { } + }); +} +export function trackDisposable(x) { + disposableTracker?.trackDisposable(x); + return x; +} +export function markAsDisposed(disposable) { + disposableTracker?.markAsDisposed(disposable); +} +function setParentOfDisposable(child, parent) { + disposableTracker?.setParent(child, parent); +} +function setParentOfDisposables(children, parent) { + if (!disposableTracker) { + return; + } + for (const child of children) { + disposableTracker.setParent(child, parent); + } +} +/** + * Indicates that the given object is a singleton which does not need to be disposed. +*/ +export function markAsSingleton(singleton) { + disposableTracker?.markAsSingleton(singleton); + return singleton; +} +/** + * Check if `thing` is {@link IDisposable disposable}. + */ +export function isDisposable(thing) { + return typeof thing === 'object' && thing !== null && typeof thing.dispose === 'function' && thing.dispose.length === 0; +} +export function dispose(arg) { + if (Iterable.is(arg)) { + const errors = []; + for (const d of arg) { + if (d) { + try { + d.dispose(); + } + catch (e) { + errors.push(e); + } + } + } + if (errors.length === 1) { + throw errors[0]; + } + else if (errors.length > 1) { + throw new AggregateError(errors, 'Encountered errors while disposing of store'); + } + return Array.isArray(arg) ? [] : arg; + } + else if (arg) { + arg.dispose(); + return arg; + } +} +export function disposeIfDisposable(disposables) { + for (const d of disposables) { + if (isDisposable(d)) { + d.dispose(); + } + } + return []; +} +/** + * Combine multiple disposable values into a single {@link IDisposable}. + */ +export function combinedDisposable(...disposables) { + const parent = toDisposable(() => dispose(disposables)); + setParentOfDisposables(disposables, parent); + return parent; +} +/** + * Turn a function that implements dispose into an {@link IDisposable}. + * + * @param fn Clean up function, guaranteed to be called only **once**. + */ +export function toDisposable(fn) { + const self = trackDisposable({ + dispose: createSingleCallFunction(() => { + markAsDisposed(self); + fn(); + }) + }); + return self; +} +/** + * Manages a collection of disposable values. + * + * This is the preferred way to manage multiple disposables. A `DisposableStore` is safer to work with than an + * `IDisposable[]` as it considers edge cases, such as registering the same value multiple times or adding an item to a + * store that has already been disposed of. + */ +export class DisposableStore { + static DISABLE_DISPOSED_WARNING = false; + _toDispose = new Set(); + _isDisposed = false; + constructor() { + trackDisposable(this); + } + /** + * Dispose of all registered disposables and mark this object as disposed. + * + * Any future disposables added to this object will be disposed of on `add`. + */ + dispose() { + if (this._isDisposed) { + return; + } + markAsDisposed(this); + this._isDisposed = true; + this.clear(); + } + /** + * @return `true` if this object has been disposed of. + */ + get isDisposed() { + return this._isDisposed; + } + /** + * Dispose of all registered disposables but do not mark this object as disposed. + */ + clear() { + if (this._toDispose.size === 0) { + return; + } + try { + dispose(this._toDispose); + } + finally { + this._toDispose.clear(); + } + } + /** + * Add a new {@link IDisposable disposable} to the collection. + */ + add(o) { + if (!o) { + return o; + } + if (o === this) { + throw new Error('Cannot register a disposable on itself!'); + } + setParentOfDisposable(o, this); + if (this._isDisposed) { + if (!DisposableStore.DISABLE_DISPOSED_WARNING) { + console.warn(new Error('Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!').stack); + } + } + else { + this._toDispose.add(o); + } + return o; + } + /** + * Deletes a disposable from store and disposes of it. This will not throw or warn and proceed to dispose the + * disposable even when the disposable is not part in the store. + */ + delete(o) { + if (!o) { + return; + } + if (o === this) { + throw new Error('Cannot dispose a disposable on itself!'); + } + this._toDispose.delete(o); + o.dispose(); + } + /** + * Deletes the value from the store, but does not dispose it. + */ + deleteAndLeak(o) { + if (!o) { + return; + } + if (this._toDispose.has(o)) { + this._toDispose.delete(o); + setParentOfDisposable(o, null); + } + } +} +/** + * Abstract base class for a {@link IDisposable disposable} object. + * + * Subclasses can {@linkcode _register} disposables that will be automatically cleaned up when this object is disposed of. + */ +export class Disposable { + /** + * A disposable that does nothing when it is disposed of. + * + * TODO: This should not be a static property. + */ + static None = Object.freeze({ dispose() { } }); + _store = new DisposableStore(); + constructor() { + trackDisposable(this); + setParentOfDisposable(this._store, this); + } + dispose() { + markAsDisposed(this); + this._store.dispose(); + } + /** + * Adds `o` to the collection of disposables managed by this object. + */ + _register(o) { + if (o === this) { + throw new Error('Cannot register a disposable on itself!'); + } + return this._store.add(o); + } +} +/** + * Manages the lifecycle of a disposable value that may be changed. + * + * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can + * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up. + */ +export class MutableDisposable { + _value; + _isDisposed = false; + constructor() { + trackDisposable(this); + } + get value() { + return this._isDisposed ? undefined : this._value; + } + set value(value) { + if (this._isDisposed || value === this._value) { + return; + } + this._value?.dispose(); + if (value) { + setParentOfDisposable(value, this); + } + this._value = value; + } + /** + * Resets the stored value and disposed of the previously stored value. + */ + clear() { + this.value = undefined; + } + dispose() { + this._isDisposed = true; + markAsDisposed(this); + this._value?.dispose(); + this._value = undefined; + } + /** + * Clears the value, but does not dispose it. + * The old value is returned. + */ + clearAndLeak() { + const oldValue = this._value; + this._value = undefined; + if (oldValue) { + setParentOfDisposable(oldValue, null); + } + return oldValue; + } +} +/** + * Manages the lifecycle of a disposable value that may be changed like {@link MutableDisposable}, but the value must + * exist and cannot be undefined. + */ +export class MandatoryMutableDisposable { + _disposable = new MutableDisposable(); + _isDisposed = false; + constructor(initialValue) { + this._disposable.value = initialValue; + } + get value() { + return this._disposable.value; + } + set value(value) { + if (this._isDisposed || value === this._disposable.value) { + return; + } + this._disposable.value = value; + } + dispose() { + this._isDisposed = true; + this._disposable.dispose(); + } +} +export class RefCountedDisposable { + _disposable; + _counter = 1; + constructor(_disposable) { + this._disposable = _disposable; + } + acquire() { + this._counter++; + return this; + } + release() { + if (--this._counter === 0) { + this._disposable.dispose(); + } + return this; + } +} +/** + * A safe disposable can be `unset` so that a leaked reference (listener) + * can be cut-off. + */ +export class SafeDisposable { + dispose = () => { }; + unset = () => { }; + isset = () => false; + constructor() { + trackDisposable(this); + } + set(fn) { + let callback = fn; + this.unset = () => callback = undefined; + this.isset = () => callback !== undefined; + this.dispose = () => { + if (callback) { + callback(); + callback = undefined; + markAsDisposed(this); + } + }; + return this; + } +} +export class ReferenceCollection { + references = new Map(); + acquire(key, ...args) { + let reference = this.references.get(key); + if (!reference) { + reference = { counter: 0, object: this.createReferencedObject(key, ...args) }; + this.references.set(key, reference); + } + const { object } = reference; + const dispose = createSingleCallFunction(() => { + if (--reference.counter === 0) { + this.destroyReferencedObject(key, reference.object); + this.references.delete(key); + } + }); + reference.counter++; + return { object, dispose }; + } +} +/** + * Unwraps a reference collection of promised values. Makes sure + * references are disposed whenever promises get rejected. + */ +export class AsyncReferenceCollection { + referenceCollection; + constructor(referenceCollection) { + this.referenceCollection = referenceCollection; + } + async acquire(key, ...args) { + const ref = this.referenceCollection.acquire(key, ...args); + try { + const object = await ref.object; + return { + object, + dispose: () => ref.dispose() + }; + } + catch (error) { + ref.dispose(); + throw error; + } + } +} +export class ImmortalReference { + object; + constructor(object) { + this.object = object; + } + dispose() { } +} +export function disposeOnReturn(fn) { + const store = new DisposableStore(); + try { + fn(store); + } + finally { + store.dispose(); + } +} +/** + * A map the manages the lifecycle of the values that it stores. + */ +export class DisposableMap { + _store = new Map(); + _isDisposed = false; + constructor() { + trackDisposable(this); + } + /** + * Disposes of all stored values and mark this object as disposed. + * + * Trying to use this object after it has been disposed of is an error. + */ + dispose() { + markAsDisposed(this); + this._isDisposed = true; + this.clearAndDisposeAll(); + } + /** + * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed. + */ + clearAndDisposeAll() { + if (!this._store.size) { + return; + } + try { + dispose(this._store.values()); + } + finally { + this._store.clear(); + } + } + has(key) { + return this._store.has(key); + } + get size() { + return this._store.size; + } + get(key) { + return this._store.get(key); + } + set(key, value, skipDisposeOnOverwrite = false) { + if (this._isDisposed) { + console.warn(new Error('Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!').stack); + } + if (!skipDisposeOnOverwrite) { + this._store.get(key)?.dispose(); + } + this._store.set(key, value); + } + /** + * Delete the value stored for `key` from this map and also dispose of it. + */ + deleteAndDispose(key) { + this._store.get(key)?.dispose(); + this._store.delete(key); + } + /** + * Delete the value stored for `key` from this map but return it. The caller is + * responsible for disposing of the value. + */ + deleteAndLeak(key) { + const value = this._store.get(key); + this._store.delete(key); + return value; + } + keys() { + return this._store.keys(); + } + values() { + return this._store.values(); + } + [Symbol.iterator]() { + return this._store[Symbol.iterator](); + } +} +//# sourceMappingURL=lifecycle.js.map \ No newline at end of file diff --git a/packages/core/dist/lifecycle.js.map b/packages/core/dist/lifecycle.js.map new file mode 100644 index 00000000..22f04dd1 --- /dev/null +++ b/packages/core/dist/lifecycle.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lifecycle.js","sourceRoot":"","sources":["../src/lifecycle.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAEzC,8BAA8B;AAE9B;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAChC,IAAI,iBAAiB,GAA8B,IAAI,CAAC;AAyBxD,MAAM,OAAO,wBAAwB;IAEnB,SAAS,GAAG,IAAI,oBAAoB,CAAS,SAAS,CAAC,EAAE;QACzE,OAAO,CAAC,IAAI,CAAC,uBAAuB,SAAS,EAAE,CAAC,CAAC;IAClD,CAAC,CAAC,CAAC;IAEH,eAAe,CAAC,UAAuB;QACtC,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC,KAAM,CAAC;QAC/C,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,UAAU,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC;IACxD,CAAC;IAED,SAAS,CAAC,KAAkB,EAAE,MAA0B;QACvD,IAAI,MAAM,EAA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CAAC,QAAQ,CAAC,EAAE,CAAC;IACvC,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/linkedList.d.ts b/packages/core/dist/linkedList.d.ts new file mode 100644 index 00000000..b703293d --- /dev/null +++ b/packages/core/dist/linkedList.d.ts @@ -0,0 +1,15 @@ +export declare class LinkedList { + private _first; + private _last; + private _size; + get size(): number; + isEmpty(): boolean; + clear(): void; + unshift(element: E): () => void; + push(element: E): () => void; + private _insert; + shift(): E | undefined; + pop(): E | undefined; + private _remove; + [Symbol.iterator](): Iterator; +} diff --git a/packages/core/dist/linkedList.js b/packages/core/dist/linkedList.js new file mode 100644 index 00000000..fa623336 --- /dev/null +++ b/packages/core/dist/linkedList.js @@ -0,0 +1,126 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +class Node { + static Undefined = new Node(undefined); + element; + next; + prev; + constructor(element) { + this.element = element; + this.next = Node.Undefined; + this.prev = Node.Undefined; + } +} +export class LinkedList { + _first = Node.Undefined; + _last = Node.Undefined; + _size = 0; + get size() { + return this._size; + } + isEmpty() { + return this._first === Node.Undefined; + } + clear() { + let node = this._first; + while (node !== Node.Undefined) { + const next = node.next; + node.prev = Node.Undefined; + node.next = Node.Undefined; + node = next; + } + this._first = Node.Undefined; + this._last = Node.Undefined; + this._size = 0; + } + unshift(element) { + return this._insert(element, false); + } + push(element) { + return this._insert(element, true); + } + _insert(element, atTheEnd) { + const newNode = new Node(element); + if (this._first === Node.Undefined) { + this._first = newNode; + this._last = newNode; + } + else if (atTheEnd) { + // push + const oldLast = this._last; + this._last = newNode; + newNode.prev = oldLast; + oldLast.next = newNode; + } + else { + // unshift + const oldFirst = this._first; + this._first = newNode; + newNode.next = oldFirst; + oldFirst.prev = newNode; + } + this._size += 1; + let didRemove = false; + return () => { + if (!didRemove) { + didRemove = true; + this._remove(newNode); + } + }; + } + shift() { + if (this._first === Node.Undefined) { + return undefined; + } + else { + const res = this._first.element; + this._remove(this._first); + return res; + } + } + pop() { + if (this._last === Node.Undefined) { + return undefined; + } + else { + const res = this._last.element; + this._remove(this._last); + return res; + } + } + _remove(node) { + if (node.prev !== Node.Undefined && node.next !== Node.Undefined) { + // middle + const anchor = node.prev; + anchor.next = node.next; + node.next.prev = anchor; + } + else if (node.prev === Node.Undefined && node.next === Node.Undefined) { + // only node + this._first = Node.Undefined; + this._last = Node.Undefined; + } + else if (node.next === Node.Undefined) { + // last + this._last = this._last.prev; + this._last.next = Node.Undefined; + } + else if (node.prev === Node.Undefined) { + // first + this._first = this._first.next; + this._first.prev = Node.Undefined; + } + // done + this._size -= 1; + } + *[Symbol.iterator]() { + let node = this._first; + while (node !== Node.Undefined) { + yield node.element; + node = node.next; + } + } +} +//# sourceMappingURL=linkedList.js.map \ No newline at end of file diff --git a/packages/core/dist/linkedList.js.map b/packages/core/dist/linkedList.js.map new file mode 100644 index 00000000..e659c1fc --- /dev/null +++ b/packages/core/dist/linkedList.js.map @@ -0,0 +1 @@ +{"version":3,"file":"linkedList.js","sourceRoot":"","sources":["../src/linkedList.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,MAAM,IAAI;IAET,MAAM,CAAU,SAAS,GAAG,IAAI,IAAI,CAAM,SAAS,CAAC,CAAC;IAErD,OAAO,CAAI;IACX,IAAI,CAAU;IACd,IAAI,CAAU;IAEd,YAAY,OAAU;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC;QAC3B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC;IAC5B,CAAC;;AAGF,MAAM,OAAO,UAAU;IAEd,MAAM,GAAY,IAAI,CAAC,SAAS,CAAC;IACjC,KAAK,GAAY,IAAI,CAAC,SAAS,CAAC;IAChC,KAAK,GAAW,CAAC,CAAC;IAE1B,IAAI,IAAI;QACP,OAAO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AC,IAAI,CAAC;YACxB,IAAI,CAAC,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC;SAExB;aAAM,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,SAAS,EAAE;YACxE,YAAY;YACZ,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC;YAC7B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC;SAE5B;aAAM,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,SAAS,EAAE;YACxC,OAAO;YACP,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAK,CAAC;YAC9B,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC;SAEjC;aAAM,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,SAAS,EAAE;YACxC,QAAQ;YACR,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,IAAK,CAAC;YAChC,IAAI,CAAC,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC;SAClC;QAED,OAAO;QACP,IAAI,CAAC,KAAK,IAAI,CAAC,CAAC;IACjB,CAAC;IAED,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC;QACjB,IAAI,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;QACvB,OAAO,IAAI,KAAK,IAAI,CAAC,SAAS,EAAE;YAC/B,MAAM,IAAI,CAAC,OAAO,CAAC;YACnB,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;SACjB;IACF,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/map.d.ts b/packages/core/dist/map.d.ts new file mode 100644 index 00000000..4a58be66 --- /dev/null +++ b/packages/core/dist/map.d.ts @@ -0,0 +1,174 @@ +import { URI } from './uri.js'; +export declare function getOrSet(map: Map, key: K, value: V): V; +export declare function mapToString(map: Map): string; +export declare function setToString(set: Set): string; +interface ResourceMapKeyFn { + (resource: URI): string; +} +export declare class ResourceMap implements Map { + private static readonly defaultToKey; + readonly [Symbol.toStringTag] = "ResourceMap"; + private readonly map; + private readonly toKey; + /** + * + * @param toKey Custom uri identity function, e.g use an existing `IExtUri#getComparison`-util + */ + constructor(toKey?: ResourceMapKeyFn); + /** + * + * @param other Another resource which this maps is created from + * @param toKey Custom uri identity function, e.g use an existing `IExtUri#getComparison`-util + */ + constructor(other?: ResourceMap, toKey?: ResourceMapKeyFn); + /** + * + * @param other Another resource which this maps is created from + * @param toKey Custom uri identity function, e.g use an existing `IExtUri#getComparison`-util + */ + constructor(entries?: readonly (readonly [URI, T])[], toKey?: ResourceMapKeyFn); + set(resource: URI, value: T): this; + get(resource: URI): T | undefined; + has(resource: URI): boolean; + get size(): number; + clear(): void; + delete(resource: URI): boolean; + forEach(clb: (value: T, key: URI, map: Map) => void, thisArg?: any): void; + values(): IterableIterator; + keys(): IterableIterator; + entries(): IterableIterator<[URI, T]>; + [Symbol.iterator](): IterableIterator<[URI, T]>; +} +export declare class ResourceSet implements Set { + readonly [Symbol.toStringTag]: string; + private readonly _map; + constructor(toKey?: ResourceMapKeyFn); + constructor(entries: readonly URI[], toKey?: ResourceMapKeyFn); + get size(): number; + add(value: URI): this; + clear(): void; + delete(value: URI): boolean; + forEach(callbackfn: (value: URI, value2: URI, set: Set) => void, thisArg?: any): void; + has(value: URI): boolean; + entries(): IterableIterator<[URI, URI]>; + keys(): IterableIterator; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator; +} +export declare const enum Touch { + None = 0, + AsOld = 1, + AsNew = 2 +} +export declare class LinkedMap implements Map { + readonly [Symbol.toStringTag] = "LinkedMap"; + private _map; + private _head; + private _tail; + private _size; + private _state; + constructor(); + clear(): void; + isEmpty(): boolean; + get size(): number; + get first(): V | undefined; + get last(): V | undefined; + has(key: K): boolean; + get(key: K, touch?: Touch): V | undefined; + set(key: K, value: V, touch?: Touch): this; + delete(key: K): boolean; + remove(key: K): V | undefined; + shift(): V | undefined; + forEach(callbackfn: (value: V, key: K, map: LinkedMap) => void, thisArg?: any): void; + keys(): IterableIterator; + values(): IterableIterator; + entries(): IterableIterator<[K, V]>; + [Symbol.iterator](): IterableIterator<[K, V]>; + protected trimOld(newSize: number): void; + protected trimNew(newSize: number): void; + private addItemFirst; + private addItemLast; + private removeItem; + private touch; + toJSON(): [K, V][]; + fromJSON(data: [K, V][]): void; +} +declare abstract class Cache extends LinkedMap { + protected _limit: number; + protected _ratio: number; + constructor(limit: number, ratio?: number); + get limit(): number; + set limit(limit: number); + get ratio(): number; + set ratio(ratio: number); + get(key: K, touch?: Touch): V | undefined; + peek(key: K): V | undefined; + set(key: K, value: V): this; + protected checkTrim(): void; + protected abstract trim(newSize: number): void; +} +export declare class LRUCache extends Cache { + constructor(limit: number, ratio?: number); + protected trim(newSize: number): void; + set(key: K, value: V): this; +} +export declare class MRUCache extends Cache { + constructor(limit: number, ratio?: number); + protected trim(newSize: number): void; + set(key: K, value: V): this; +} +export declare class CounterSet { + private map; + add(value: T): CounterSet; + delete(value: T): boolean; + has(value: T): boolean; +} +/** + * A map that allows access both by keys and values. + * **NOTE**: values need to be unique. + */ +export declare class BidirectionalMap { + private readonly _m1; + private readonly _m2; + constructor(entries?: readonly (readonly [K, V])[]); + clear(): void; + set(key: K, value: V): void; + get(key: K): V | undefined; + getKey(value: V): K | undefined; + delete(key: K): boolean; + forEach(callbackfn: (value: V, key: K, map: BidirectionalMap) => void, thisArg?: any): void; + keys(): IterableIterator; + values(): IterableIterator; +} +export declare class SetMap { + private map; + add(key: K, value: V): void; + delete(key: K, value: V): void; + forEach(key: K, fn: (value: V) => void): void; + get(key: K): ReadonlySet; +} +export declare function mapsStrictEqualIgnoreOrder(a: Map, b: Map): boolean; +/** + * A map that is addressable with an arbitrary number of keys. This is useful in high performance + * scenarios where creating a composite key whenever the data is accessed is too expensive. For + * example for a very hot function, constructing a string like `first-second-third` for every call + * will cause a significant hit to performance. + */ +export declare class NKeyMap { + private _data; + /** + * Sets a value on the map. Note that unlike a standard `Map`, the first argument is the value. + * This is because the spread operator is used for the keys and must be last.. + * @param value The value to set. + * @param keys The keys for the value. + */ + set(value: TValue, ...keys: [...TKeys]): void; + get(...keys: [...TKeys]): TValue | undefined; + clear(): void; + values(): IterableIterator; + /** + * Get a textual representation of the map for debugging purposes. + */ + toString(): string; +} +export {}; diff --git a/packages/core/dist/map.js b/packages/core/dist/map.js new file mode 100644 index 00000000..3fe50d41 --- /dev/null +++ b/packages/core/dist/map.js @@ -0,0 +1,794 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +export function getOrSet(map, key, value) { + let result = map.get(key); + if (result === undefined) { + result = value; + map.set(key, result); + } + return result; +} +export function mapToString(map) { + const entries = []; + map.forEach((value, key) => { + entries.push(`${key} => ${value}`); + }); + return `Map(${map.size}) {${entries.join(', ')}}`; +} +export function setToString(set) { + const entries = []; + set.forEach(value => { + entries.push(value); + }); + return `Set(${set.size}) {${entries.join(', ')}}`; +} +class ResourceMapEntry { + uri; + value; + constructor(uri, value) { + this.uri = uri; + this.value = value; + } +} +function isEntries(arg) { + return Array.isArray(arg); +} +export class ResourceMap { + static defaultToKey = (resource) => resource.toString(); + [Symbol.toStringTag] = 'ResourceMap'; + map; + toKey; + constructor(arg, toKey) { + if (arg instanceof ResourceMap) { + this.map = new Map(arg.map); + this.toKey = toKey ?? ResourceMap.defaultToKey; + } + else if (isEntries(arg)) { + this.map = new Map(); + this.toKey = toKey ?? ResourceMap.defaultToKey; + for (const [resource, value] of arg) { + this.set(resource, value); + } + } + else { + this.map = new Map(); + this.toKey = arg ?? ResourceMap.defaultToKey; + } + } + set(resource, value) { + this.map.set(this.toKey(resource), new ResourceMapEntry(resource, value)); + return this; + } + get(resource) { + return this.map.get(this.toKey(resource))?.value; + } + has(resource) { + return this.map.has(this.toKey(resource)); + } + get size() { + return this.map.size; + } + clear() { + this.map.clear(); + } + delete(resource) { + return this.map.delete(this.toKey(resource)); + } + forEach(clb, thisArg) { + if (typeof thisArg !== 'undefined') { + clb = clb.bind(thisArg); + } + for (const [_, entry] of this.map) { + clb(entry.value, entry.uri, this); + } + } + *values() { + for (const entry of this.map.values()) { + yield entry.value; + } + } + *keys() { + for (const entry of this.map.values()) { + yield entry.uri; + } + } + *entries() { + for (const entry of this.map.values()) { + yield [entry.uri, entry.value]; + } + } + *[Symbol.iterator]() { + for (const [, entry] of this.map) { + yield [entry.uri, entry.value]; + } + } +} +export class ResourceSet { + [Symbol.toStringTag] = 'ResourceSet'; + _map; + constructor(entriesOrKey, toKey) { + if (!entriesOrKey || typeof entriesOrKey === 'function') { + this._map = new ResourceMap(entriesOrKey); + } + else { + this._map = new ResourceMap(toKey); + entriesOrKey.forEach(this.add, this); + } + } + get size() { + return this._map.size; + } + add(value) { + this._map.set(value, value); + return this; + } + clear() { + this._map.clear(); + } + delete(value) { + return this._map.delete(value); + } + forEach(callbackfn, thisArg) { + this._map.forEach((_value, key) => callbackfn.call(thisArg, key, key, this)); + } + has(value) { + return this._map.has(value); + } + entries() { + return this._map.entries(); + } + keys() { + return this._map.keys(); + } + values() { + return this._map.keys(); + } + [Symbol.iterator]() { + return this.keys(); + } +} +export var Touch; +(function (Touch) { + Touch[Touch["None"] = 0] = "None"; + Touch[Touch["AsOld"] = 1] = "AsOld"; + Touch[Touch["AsNew"] = 2] = "AsNew"; +})(Touch = Touch || (Touch = {})); +export class LinkedMap { + [Symbol.toStringTag] = 'LinkedMap'; + _map; + _head; + _tail; + _size; + _state; + constructor() { + this._map = new Map(); + this._head = undefined; + this._tail = undefined; + this._size = 0; + this._state = 0; + } + clear() { + this._map.clear(); + this._head = undefined; + this._tail = undefined; + this._size = 0; + this._state++; + } + isEmpty() { + return !this._head && !this._tail; + } + get size() { + return this._size; + } + get first() { + return this._head?.value; + } + get last() { + return this._tail?.value; + } + has(key) { + return this._map.has(key); + } + get(key, touch = 0 /* Touch.None */) { + const item = this._map.get(key); + if (!item) { + return undefined; + } + if (touch !== 0 /* Touch.None */) { + this.touch(item, touch); + } + return item.value; + } + set(key, value, touch = 0 /* Touch.None */) { + let item = this._map.get(key); + if (item) { + item.value = value; + if (touch !== 0 /* Touch.None */) { + this.touch(item, touch); + } + } + else { + item = { key, value, next: undefined, previous: undefined }; + switch (touch) { + case 0 /* Touch.None */: + this.addItemLast(item); + break; + case 1 /* Touch.AsOld */: + this.addItemFirst(item); + break; + case 2 /* Touch.AsNew */: + this.addItemLast(item); + break; + default: + this.addItemLast(item); + break; + } + this._map.set(key, item); + this._size++; + } + return this; + } + delete(key) { + return !!this.remove(key); + } + remove(key) { + const item = this._map.get(key); + if (!item) { + return undefined; + } + this._map.delete(key); + this.removeItem(item); + this._size--; + return item.value; + } + shift() { + if (!this._head && !this._tail) { + return undefined; + } + if (!this._head || !this._tail) { + throw new Error('Invalid list'); + } + const item = this._head; + this._map.delete(item.key); + this.removeItem(item); + this._size--; + return item.value; + } + forEach(callbackfn, thisArg) { + const state = this._state; + let current = this._head; + while (current) { + if (thisArg) { + callbackfn.bind(thisArg)(current.value, current.key, this); + } + else { + callbackfn(current.value, current.key, this); + } + if (this._state !== state) { + throw new Error(`LinkedMap got modified during iteration.`); + } + current = current.next; + } + } + keys() { + const map = this; + const state = this._state; + let current = this._head; + const iterator = { + [Symbol.iterator]() { + return iterator; + }, + next() { + if (map._state !== state) { + throw new Error(`LinkedMap got modified during iteration.`); + } + if (current) { + const result = { value: current.key, done: false }; + current = current.next; + return result; + } + else { + return { value: undefined, done: true }; + } + } + }; + return iterator; + } + values() { + const map = this; + const state = this._state; + let current = this._head; + const iterator = { + [Symbol.iterator]() { + return iterator; + }, + next() { + if (map._state !== state) { + throw new Error(`LinkedMap got modified during iteration.`); + } + if (current) { + const result = { value: current.value, done: false }; + current = current.next; + return result; + } + else { + return { value: undefined, done: true }; + } + } + }; + return iterator; + } + entries() { + const map = this; + const state = this._state; + let current = this._head; + const iterator = { + [Symbol.iterator]() { + return iterator; + }, + next() { + if (map._state !== state) { + throw new Error(`LinkedMap got modified during iteration.`); + } + if (current) { + const result = { value: [current.key, current.value], done: false }; + current = current.next; + return result; + } + else { + return { value: undefined, done: true }; + } + } + }; + return iterator; + } + [Symbol.iterator]() { + return this.entries(); + } + trimOld(newSize) { + if (newSize >= this.size) { + return; + } + if (newSize === 0) { + this.clear(); + return; + } + let current = this._head; + let currentSize = this.size; + while (current && currentSize > newSize) { + this._map.delete(current.key); + current = current.next; + currentSize--; + } + this._head = current; + this._size = currentSize; + if (current) { + current.previous = undefined; + } + this._state++; + } + trimNew(newSize) { + if (newSize >= this.size) { + return; + } + if (newSize === 0) { + this.clear(); + return; + } + let current = this._tail; + let currentSize = this.size; + while (current && currentSize > newSize) { + this._map.delete(current.key); + current = current.previous; + currentSize--; + } + this._tail = current; + this._size = currentSize; + if (current) { + current.next = undefined; + } + this._state++; + } + addItemFirst(item) { + // First time Insert + if (!this._head && !this._tail) { + this._tail = item; + } + else if (!this._head) { + throw new Error('Invalid list'); + } + else { + item.next = this._head; + this._head.previous = item; + } + this._head = item; + this._state++; + } + addItemLast(item) { + // First time Insert + if (!this._head && !this._tail) { + this._head = item; + } + else if (!this._tail) { + throw new Error('Invalid list'); + } + else { + item.previous = this._tail; + this._tail.next = item; + } + this._tail = item; + this._state++; + } + removeItem(item) { + if (item === this._head && item === this._tail) { + this._head = undefined; + this._tail = undefined; + } + else if (item === this._head) { + // This can only happen if size === 1 which is handled + // by the case above. + if (!item.next) { + throw new Error('Invalid list'); + } + item.next.previous = undefined; + this._head = item.next; + } + else if (item === this._tail) { + // This can only happen if size === 1 which is handled + // by the case above. + if (!item.previous) { + throw new Error('Invalid list'); + } + item.previous.next = undefined; + this._tail = item.previous; + } + else { + const next = item.next; + const previous = item.previous; + if (!next || !previous) { + throw new Error('Invalid list'); + } + next.previous = previous; + previous.next = next; + } + item.next = undefined; + item.previous = undefined; + this._state++; + } + touch(item, touch) { + if (!this._head || !this._tail) { + throw new Error('Invalid list'); + } + if ((touch !== 1 /* Touch.AsOld */ && touch !== 2 /* Touch.AsNew */)) { + return; + } + if (touch === 1 /* Touch.AsOld */) { + if (item === this._head) { + return; + } + const next = item.next; + const previous = item.previous; + // Unlink the item + if (item === this._tail) { + // previous must be defined since item was not head but is tail + // So there are more than on item in the map + previous.next = undefined; + this._tail = previous; + } + else { + // Both next and previous are not undefined since item was neither head nor tail. + next.previous = previous; + previous.next = next; + } + // Insert the node at head + item.previous = undefined; + item.next = this._head; + this._head.previous = item; + this._head = item; + this._state++; + } + else if (touch === 2 /* Touch.AsNew */) { + if (item === this._tail) { + return; + } + const next = item.next; + const previous = item.previous; + // Unlink the item. + if (item === this._head) { + // next must be defined since item was not tail but is head + // So there are more than on item in the map + next.previous = undefined; + this._head = next; + } + else { + // Both next and previous are not undefined since item was neither head nor tail. + next.previous = previous; + previous.next = next; + } + item.next = undefined; + item.previous = this._tail; + this._tail.next = item; + this._tail = item; + this._state++; + } + } + toJSON() { + const data = []; + this.forEach((value, key) => { + data.push([key, value]); + }); + return data; + } + fromJSON(data) { + this.clear(); + for (const [key, value] of data) { + this.set(key, value); + } + } +} +class Cache extends LinkedMap { + _limit; + _ratio; + constructor(limit, ratio = 1) { + super(); + this._limit = limit; + this._ratio = Math.min(Math.max(0, ratio), 1); + } + get limit() { + return this._limit; + } + set limit(limit) { + this._limit = limit; + this.checkTrim(); + } + get ratio() { + return this._ratio; + } + set ratio(ratio) { + this._ratio = Math.min(Math.max(0, ratio), 1); + this.checkTrim(); + } + get(key, touch = 2 /* Touch.AsNew */) { + return super.get(key, touch); + } + peek(key) { + return super.get(key, 0 /* Touch.None */); + } + set(key, value) { + super.set(key, value, 2 /* Touch.AsNew */); + return this; + } + checkTrim() { + if (this.size > this._limit) { + this.trim(Math.round(this._limit * this._ratio)); + } + } +} +export class LRUCache extends Cache { + constructor(limit, ratio = 1) { + super(limit, ratio); + } + trim(newSize) { + this.trimOld(newSize); + } + set(key, value) { + super.set(key, value); + this.checkTrim(); + return this; + } +} +export class MRUCache extends Cache { + constructor(limit, ratio = 1) { + super(limit, ratio); + } + trim(newSize) { + this.trimNew(newSize); + } + set(key, value) { + if (this._limit <= this.size && !this.has(key)) { + this.trim(Math.round(this._limit * this._ratio) - 1); + } + super.set(key, value); + return this; + } +} +export class CounterSet { + map = new Map(); + add(value) { + this.map.set(value, (this.map.get(value) || 0) + 1); + return this; + } + delete(value) { + let counter = this.map.get(value) || 0; + if (counter === 0) { + return false; + } + counter--; + if (counter === 0) { + this.map.delete(value); + } + else { + this.map.set(value, counter); + } + return true; + } + has(value) { + return this.map.has(value); + } +} +/** + * A map that allows access both by keys and values. + * **NOTE**: values need to be unique. + */ +export class BidirectionalMap { + _m1 = new Map(); + _m2 = new Map(); + constructor(entries) { + if (entries) { + for (const [key, value] of entries) { + this.set(key, value); + } + } + } + clear() { + this._m1.clear(); + this._m2.clear(); + } + set(key, value) { + this._m1.set(key, value); + this._m2.set(value, key); + } + get(key) { + return this._m1.get(key); + } + getKey(value) { + return this._m2.get(value); + } + delete(key) { + const value = this._m1.get(key); + if (value === undefined) { + return false; + } + this._m1.delete(key); + this._m2.delete(value); + return true; + } + forEach(callbackfn, thisArg) { + this._m1.forEach((value, key) => { + callbackfn.call(thisArg, value, key, this); + }); + } + keys() { + return this._m1.keys(); + } + values() { + return this._m1.values(); + } +} +export class SetMap { + map = new Map(); + add(key, value) { + let values = this.map.get(key); + if (!values) { + values = new Set(); + this.map.set(key, values); + } + values.add(value); + } + delete(key, value) { + const values = this.map.get(key); + if (!values) { + return; + } + values.delete(value); + if (values.size === 0) { + this.map.delete(key); + } + } + forEach(key, fn) { + const values = this.map.get(key); + if (!values) { + return; + } + values.forEach(fn); + } + get(key) { + const values = this.map.get(key); + if (!values) { + return new Set(); + } + return values; + } +} +export function mapsStrictEqualIgnoreOrder(a, b) { + if (a === b) { + return true; + } + if (a.size !== b.size) { + return false; + } + for (const [key, value] of a) { + if (!b.has(key) || b.get(key) !== value) { + return false; + } + } + for (const [key] of b) { + if (!a.has(key)) { + return false; + } + } + return true; +} +/** + * A map that is addressable with an arbitrary number of keys. This is useful in high performance + * scenarios where creating a composite key whenever the data is accessed is too expensive. For + * example for a very hot function, constructing a string like `first-second-third` for every call + * will cause a significant hit to performance. + */ +export class NKeyMap { + _data = new Map(); + /** + * Sets a value on the map. Note that unlike a standard `Map`, the first argument is the value. + * This is because the spread operator is used for the keys and must be last.. + * @param value The value to set. + * @param keys The keys for the value. + */ + set(value, ...keys) { + let currentMap = this._data; + for (let i = 0; i < keys.length - 1; i++) { + if (!currentMap.has(keys[i])) { + currentMap.set(keys[i], new Map()); + } + currentMap = currentMap.get(keys[i]); + } + currentMap.set(keys[keys.length - 1], value); + } + get(...keys) { + let currentMap = this._data; + for (let i = 0; i < keys.length - 1; i++) { + if (!currentMap.has(keys[i])) { + return undefined; + } + currentMap = currentMap.get(keys[i]); + } + return currentMap.get(keys[keys.length - 1]); + } + clear() { + this._data.clear(); + } + *values() { + function* iterate(map) { + for (const value of map.values()) { + if (value instanceof Map) { + yield* iterate(value); + } + else { + yield value; + } + } + } + yield* iterate(this._data); + } + /** + * Get a textual representation of the map for debugging purposes. + */ + toString() { + const printMap = (map, depth) => { + let result = ''; + for (const [key, value] of map) { + result += `${' '.repeat(depth)}${key}: `; + if (value instanceof Map) { + result += '\n' + printMap(value, depth + 1); + } + else { + result += `${value}\n`; + } + } + return result; + }; + return printMap(this._data, 0); + } +} +//# sourceMappingURL=map.js.map \ No newline at end of file diff --git a/packages/core/dist/map.js.map b/packages/core/dist/map.js.map new file mode 100644 index 00000000..f6fd50df --- /dev/null +++ b/packages/core/dist/map.js.map @@ -0,0 +1 @@ +{"version":3,"file":"map.js","sourceRoot":"","sources":["../src/map.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAIhG,MAAM,UAAU,QAAQ,CAAO,GAAc,EAAE,GAAM,EAAE,KAAQ;IAC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,CAAC;IAEM,KAAK;QACX,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAEM,CAAC,MAAM;QACb,QAAQ,CAAC,CAAC,OAAO,CAAC,GAAkB;YACnC,KAAK,MAAM,KAAK,IAAI,GAAG,CAAC,MAAM,EAAE,EAAE;gBACjC,IAAI,KAAK,YAAY,GAAG,EAAE;oBACzB,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;iBACtB;qBAAM;oBACN,MAAM,KAAK,CAAC;iBACZ;aACD;QACF,CAAC;QACD,KAAK,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED;;OAEG;IACI,QAAQ;QACd,MAAM,QAAQ,GAAG,CAAC,GAAkB,EAAE,KAAa,EAAU,EAAE;YAC9D,IAAI,MAAM,GAAG,EAAE,CAAC;YAChB,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,GAAG,EAAE;gBAC/B,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,GAAG,IAAI,CAAC;gBAC1C,IAAI,KAAK,YAAY,GAAG,EAAE;oBACzB,MAAM,IAAI,IAAI,GAAG,QAAQ,CAAC,KAAK,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;iBAC5C;qBAAM;oBACN,MAAM,IAAI,GAAG,KAAK,IAAI,CAAC;iBACvB;aACD;YACD,OAAO,MAAM,CAAC;QACf,CAAC,CAAC;QAEF,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IAChC,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/marshallingIds.d.ts b/packages/core/dist/marshallingIds.d.ts new file mode 100644 index 00000000..74be4e2a --- /dev/null +++ b/packages/core/dist/marshallingIds.d.ts @@ -0,0 +1,24 @@ +export declare const enum MarshalledId { + Uri = 1, + Regexp = 2, + ScmResource = 3, + ScmResourceGroup = 4, + ScmProvider = 5, + CommentController = 6, + CommentThread = 7, + CommentThreadInstance = 8, + CommentThreadReply = 9, + CommentNode = 10, + CommentThreadNode = 11, + TimelineActionContext = 12, + NotebookCellActionContext = 13, + NotebookActionContext = 14, + TerminalContext = 15, + TestItemContext = 16, + Date = 17, + TestMessageMenuArgs = 18, + ChatViewContext = 19, + LanguageModelToolResult = 20, + LanguageModelTextPart = 21, + LanguageModelPromptTsxPart = 22 +} diff --git a/packages/core/dist/marshallingIds.js b/packages/core/dist/marshallingIds.js new file mode 100644 index 00000000..70574725 --- /dev/null +++ b/packages/core/dist/marshallingIds.js @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +export var MarshalledId; +(function (MarshalledId) { + MarshalledId[MarshalledId["Uri"] = 1] = "Uri"; + MarshalledId[MarshalledId["Regexp"] = 2] = "Regexp"; + MarshalledId[MarshalledId["ScmResource"] = 3] = "ScmResource"; + MarshalledId[MarshalledId["ScmResourceGroup"] = 4] = "ScmResourceGroup"; + MarshalledId[MarshalledId["ScmProvider"] = 5] = "ScmProvider"; + MarshalledId[MarshalledId["CommentController"] = 6] = "CommentController"; + MarshalledId[MarshalledId["CommentThread"] = 7] = "CommentThread"; + MarshalledId[MarshalledId["CommentThreadInstance"] = 8] = "CommentThreadInstance"; + MarshalledId[MarshalledId["CommentThreadReply"] = 9] = "CommentThreadReply"; + MarshalledId[MarshalledId["CommentNode"] = 10] = "CommentNode"; + MarshalledId[MarshalledId["CommentThreadNode"] = 11] = "CommentThreadNode"; + MarshalledId[MarshalledId["TimelineActionContext"] = 12] = "TimelineActionContext"; + MarshalledId[MarshalledId["NotebookCellActionContext"] = 13] = "NotebookCellActionContext"; + MarshalledId[MarshalledId["NotebookActionContext"] = 14] = "NotebookActionContext"; + MarshalledId[MarshalledId["TerminalContext"] = 15] = "TerminalContext"; + MarshalledId[MarshalledId["TestItemContext"] = 16] = "TestItemContext"; + MarshalledId[MarshalledId["Date"] = 17] = "Date"; + MarshalledId[MarshalledId["TestMessageMenuArgs"] = 18] = "TestMessageMenuArgs"; + MarshalledId[MarshalledId["ChatViewContext"] = 19] = "ChatViewContext"; + MarshalledId[MarshalledId["LanguageModelToolResult"] = 20] = "LanguageModelToolResult"; + MarshalledId[MarshalledId["LanguageModelTextPart"] = 21] = "LanguageModelTextPart"; + MarshalledId[MarshalledId["LanguageModelPromptTsxPart"] = 22] = "LanguageModelPromptTsxPart"; +})(MarshalledId = MarshalledId || (MarshalledId = {})); +//# sourceMappingURL=marshallingIds.js.map \ No newline at end of file diff --git a/packages/core/dist/marshallingIds.js.map b/packages/core/dist/marshallingIds.js.map new file mode 100644 index 00000000..d37a07bb --- /dev/null +++ b/packages/core/dist/marshallingIds.js.map @@ -0,0 +1 @@ +{"version":3,"file":"marshallingIds.js","sourceRoot":"","sources":["../src/marshallingIds.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,MAAM,CAAN,IAAkB,YAuBjB;AAvBD,WAAkB,YAAY;IAC7B,6CAAO,CAAA;IACP,mDAAM,CAAA;IACN,6DAAW,CAAA;IACX,uEAAgB,CAAA;IAChB,6DAAW,CAAA;IACX,yEAAiB,CAAA;IACjB,iEAAa,CAAA;IACb,iFAAqB,CAAA;IACrB,2EAAkB,CAAA;IAClB,8DAAW,CAAA;IACX,0EAAiB,CAAA;IACjB,kFAAqB,CAAA;IACrB,0FAAyB,CAAA;IACzB,kFAAqB,CAAA;IACrB,sEAAe,CAAA;IACf,sEAAe,CAAA;IACf,gDAAI,CAAA;IACJ,8EAAmB,CAAA;IACnB,sEAAe,CAAA;IACf,sFAAuB,CAAA;IACvB,kFAAqB,CAAA;IACrB,4FAA0B,CAAA;AAC3B,CAAC,EAvBiB,YAAY,GAAZ,YAAY,KAAZ,YAAY,QAuB7B"} \ No newline at end of file diff --git a/packages/core/dist/mime.d.ts b/packages/core/dist/mime.d.ts new file mode 100644 index 00000000..e9f8a53b --- /dev/null +++ b/packages/core/dist/mime.d.ts @@ -0,0 +1,13 @@ +export declare const Mimes: Readonly<{ + text: "text/plain"; + binary: "application/octet-stream"; + unknown: "application/unknown"; + markdown: "text/markdown"; + latex: "text/latex"; + uriList: "text/uri-list"; +}>; +export declare function getMediaOrTextMime(path: string): string | undefined; +export declare function getMediaMime(path: string): string | undefined; +export declare function getExtensionForMimeType(mimeType: string): string | undefined; +export declare function normalizeMimeType(mimeType: string): string; +export declare function normalizeMimeType(mimeType: string, strict: true): string | undefined; diff --git a/packages/core/dist/mime.js b/packages/core/dist/mime.js new file mode 100644 index 00000000..ae23b223 --- /dev/null +++ b/packages/core/dist/mime.js @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { extname } from './path.js'; +export const Mimes = Object.freeze({ + text: 'text/plain', + binary: 'application/octet-stream', + unknown: 'application/unknown', + markdown: 'text/markdown', + latex: 'text/latex', + uriList: 'text/uri-list', +}); +const mapExtToTextMimes = { + '.css': 'text/css', + '.csv': 'text/csv', + '.htm': 'text/html', + '.html': 'text/html', + '.ics': 'text/calendar', + '.js': 'text/javascript', + '.mjs': 'text/javascript', + '.txt': 'text/plain', + '.xml': 'text/xml' +}; +// Known media mimes that we can handle +const mapExtToMediaMimes = { + '.aac': 'audio/x-aac', + '.avi': 'video/x-msvideo', + '.bmp': 'image/bmp', + '.flv': 'video/x-flv', + '.gif': 'image/gif', + '.ico': 'image/x-icon', + '.jpe': 'image/jpg', + '.jpeg': 'image/jpg', + '.jpg': 'image/jpg', + '.m1v': 'video/mpeg', + '.m2a': 'audio/mpeg', + '.m2v': 'video/mpeg', + '.m3a': 'audio/mpeg', + '.mid': 'audio/midi', + '.midi': 'audio/midi', + '.mk3d': 'video/x-matroska', + '.mks': 'video/x-matroska', + '.mkv': 'video/x-matroska', + '.mov': 'video/quicktime', + '.movie': 'video/x-sgi-movie', + '.mp2': 'audio/mpeg', + '.mp2a': 'audio/mpeg', + '.mp3': 'audio/mpeg', + '.mp4': 'video/mp4', + '.mp4a': 'audio/mp4', + '.mp4v': 'video/mp4', + '.mpe': 'video/mpeg', + '.mpeg': 'video/mpeg', + '.mpg': 'video/mpeg', + '.mpg4': 'video/mp4', + '.mpga': 'audio/mpeg', + '.oga': 'audio/ogg', + '.ogg': 'audio/ogg', + '.opus': 'audio/opus', + '.ogv': 'video/ogg', + '.png': 'image/png', + '.psd': 'image/vnd.adobe.photoshop', + '.qt': 'video/quicktime', + '.spx': 'audio/ogg', + '.svg': 'image/svg+xml', + '.tga': 'image/x-tga', + '.tif': 'image/tiff', + '.tiff': 'image/tiff', + '.wav': 'audio/x-wav', + '.webm': 'video/webm', + '.webp': 'image/webp', + '.wma': 'audio/x-ms-wma', + '.wmv': 'video/x-ms-wmv', + '.woff': 'application/font-woff', +}; +export function getMediaOrTextMime(path) { + const ext = extname(path); + const textMime = mapExtToTextMimes[ext.toLowerCase()]; + if (textMime !== undefined) { + return textMime; + } + else { + return getMediaMime(path); + } +} +export function getMediaMime(path) { + const ext = extname(path); + return mapExtToMediaMimes[ext.toLowerCase()]; +} +export function getExtensionForMimeType(mimeType) { + for (const extension in mapExtToMediaMimes) { + if (mapExtToMediaMimes[extension] === mimeType) { + return extension; + } + } + return undefined; +} +const _simplePattern = /^(.+)\/(.+?)(;.+)?$/; +export function normalizeMimeType(mimeType, strict) { + const match = _simplePattern.exec(mimeType); + if (!match) { + return strict + ? undefined + : mimeType; + } + // https://datatracker.ietf.org/doc/html/rfc2045#section-5.1 + // media and subtype must ALWAYS be lowercase, parameter not + return `${match[1].toLowerCase()}/${match[2].toLowerCase()}${match[3] ?? ''}`; +} +//# sourceMappingURL=mime.js.map \ No newline at end of file diff --git a/packages/core/dist/mime.js.map b/packages/core/dist/mime.js.map new file mode 100644 index 00000000..ca324104 --- /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,IAAI,kBAAkB,EAAE;QAC3C,IAAI,kBAAkB,CAAC,SAAS,CAAC,KAAK,QAAQ,EAAE;YAC/C,OAAO,SAAS,CAAC;SACjB;KACD;IAED,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,MAAM,cAAc,GAAG,qBAAqB,CAAC;AAI7C,MAAM,UAAU,iBAAiB,CAAC,QAAgB,EAAE,MAAa;IAEhE,MAAM,KAAK,GAAG,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC5C,IAAI,CAAC,KAAK,EAAE;QACX,OAAO,MAAM;YACZ,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,QAAQ,CAAC;KACZ;IACD,4DAA4D;IAC5D,4DAA4D;IAC5D,OAAO,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;AAC/E,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/network.d.ts b/packages/core/dist/network.d.ts new file mode 100644 index 00000000..05d86c75 --- /dev/null +++ b/packages/core/dist/network.d.ts @@ -0,0 +1,177 @@ +import { URI } from './uri.js'; +export declare namespace Schemas { + /** + * A schema that is used for models that exist in memory + * only and that have no correspondence on a server or such. + */ + const inMemory = "inmemory"; + /** + * A schema that is used for setting files + */ + const vscode = "vscode"; + /** + * A schema that is used for internal private files + */ + const internal = "private"; + /** + * A walk-through document. + */ + const walkThrough = "walkThrough"; + /** + * An embedded code snippet. + */ + const walkThroughSnippet = "walkThroughSnippet"; + const http = "http"; + const https = "https"; + const file = "file"; + const mailto = "mailto"; + const untitled = "untitled"; + const data = "data"; + const command = "command"; + const vscodeRemote = "vscode-remote"; + const vscodeRemoteResource = "vscode-remote-resource"; + const vscodeManagedRemoteResource = "vscode-managed-remote-resource"; + const vscodeUserData = "vscode-userdata"; + const vscodeCustomEditor = "vscode-custom-editor"; + const vscodeNotebookCell = "vscode-notebook-cell"; + const vscodeNotebookCellMetadata = "vscode-notebook-cell-metadata"; + const vscodeNotebookCellMetadataDiff = "vscode-notebook-cell-metadata-diff"; + const vscodeNotebookCellOutput = "vscode-notebook-cell-output"; + const vscodeNotebookCellOutputDiff = "vscode-notebook-cell-output-diff"; + const vscodeNotebookMetadata = "vscode-notebook-metadata"; + const vscodeInteractiveInput = "vscode-interactive-input"; + const vscodeSettings = "vscode-settings"; + const vscodeWorkspaceTrust = "vscode-workspace-trust"; + const vscodeTerminal = "vscode-terminal"; + /** Scheme used for code blocks in chat. */ + const vscodeChatCodeBlock = "vscode-chat-code-block"; + /** Scheme used for LHS of code compare (aka diff) blocks in chat. */ + const vscodeChatCodeCompareBlock = "vscode-chat-code-compare-block"; + /** Scheme used for the chat input editor. */ + const vscodeChatSesssion = "vscode-chat-editor"; + /** + * Scheme used internally for webviews that aren't linked to a resource (i.e. not custom editors) + */ + const webviewPanel = "webview-panel"; + /** + * Scheme used for loading the wrapper html and script in webviews. + */ + const vscodeWebview = "vscode-webview"; + /** + * Scheme used for extension pages + */ + const extension = "extension"; + /** + * Scheme used as a replacement of `file` scheme to load + * files with our custom protocol handler (desktop only). + */ + const vscodeFileResource = "vscode-file"; + /** + * Scheme used for temporary resources + */ + const tmp = "tmp"; + /** + * Scheme used vs live share + */ + const vsls = "vsls"; + /** + * Scheme used for the Source Control commit input's text document + */ + const vscodeSourceControl = "vscode-scm"; + /** + * Scheme used for input box for creating comments. + */ + const commentsInput = "comment"; + /** + * Scheme used for special rendering of settings in the release notes + */ + const codeSetting = "code-setting"; + /** + * Scheme used for output panel resources + */ + const outputChannel = "output"; + /** + * Scheme used for the accessible view + */ + const accessibleView = "accessible-view"; +} +export declare function matchesScheme(target: URI | string, scheme: string): boolean; +export declare function matchesSomeScheme(target: URI | string, ...schemes: string[]): boolean; +export declare const connectionTokenCookieName = "vscode-tkn"; +export declare const connectionTokenQueryName = "tkn"; +declare class RemoteAuthoritiesImpl { + private readonly _hosts; + private readonly _ports; + private readonly _connectionTokens; + private _preferredWebSchema; + private _delegate; + private _serverRootPath; + setPreferredWebSchema(schema: 'http' | 'https'): void; + setDelegate(delegate: (uri: URI) => URI): void; + setServerRootPath(product: { + quality?: string; + commit?: string; + }, serverBasePath: string | undefined): void; + getServerRootPath(): string; + private get _remoteResourcesPath(); + set(authority: string, host: string, port: number): void; + setConnectionToken(authority: string, connectionToken: string): void; + getPreferredWebSchema(): 'http' | 'https'; + rewrite(uri: URI): URI; +} +export declare const RemoteAuthorities: RemoteAuthoritiesImpl; +export declare function getServerProductSegment(product: { + quality?: string; + commit?: string; +}): string; +/** + * A string pointing to a path inside the app. It should not begin with ./ or ../ + */ +export type AppResourcePath = (`a${string}` | `b${string}` | `c${string}` | `d${string}` | `e${string}` | `f${string}` | `g${string}` | `h${string}` | `i${string}` | `j${string}` | `k${string}` | `l${string}` | `m${string}` | `n${string}` | `o${string}` | `p${string}` | `q${string}` | `r${string}` | `s${string}` | `t${string}` | `u${string}` | `v${string}` | `w${string}` | `x${string}` | `y${string}` | `z${string}`); +export declare const builtinExtensionsPath: AppResourcePath; +export declare const nodeModulesPath: AppResourcePath; +export declare const nodeModulesAsarPath: AppResourcePath; +export declare const nodeModulesAsarUnpackedPath: AppResourcePath; +export declare const VSCODE_AUTHORITY = "vscode-app"; +declare class FileAccessImpl { + private static readonly FALLBACK_AUTHORITY; + /** + * Returns a URI to use in contexts where the browser is responsible + * for loading (e.g. fetch()) or when used within the DOM. + * + * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context. + */ + asBrowserUri(resourcePath: AppResourcePath | ''): URI; + /** + * Returns a URI to use in contexts where the browser is responsible + * for loading (e.g. fetch()) or when used within the DOM. + * + * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context. + */ + uriToBrowserUri(uri: URI): URI; + /** + * Returns the `file` URI to use in contexts where node.js + * is responsible for loading. + */ + asFileUri(resourcePath: AppResourcePath | ''): URI; + /** + * Returns the `file` URI to use in contexts where node.js + * is responsible for loading. + */ + uriToFileUri(uri: URI): URI; + private toUri; +} +export declare const FileAccess: FileAccessImpl; +export declare namespace COI { + const CoopAndCoep: Readonly>; + /** + * Extract desired headers from `vscode-coi` invocation + */ + function getHeadersFromQuery(url: string | URI | URL): Record | undefined; + /** + * Add the `vscode-coi` query attribute based on wanting `COOP` and `COEP`. Will be a noop when `crossOriginIsolated` + * isn't enabled the current context + */ + function addSearchParam(urlOrSearch: URLSearchParams | Record, coop: boolean, coep: boolean): void; +} +export {}; diff --git a/packages/core/dist/network.js b/packages/core/dist/network.js new file mode 100644 index 00000000..6501c968 --- /dev/null +++ b/packages/core/dist/network.js @@ -0,0 +1,329 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import * as errors from './errors.js'; +import * as platform from './platform.js'; +import { equalsIgnoreCase, startsWithIgnoreCase } from './strings.js'; +import { URI } from './uri.js'; +import * as paths from './path.js'; +export var Schemas; +(function (Schemas) { + /** + * A schema that is used for models that exist in memory + * only and that have no correspondence on a server or such. + */ + Schemas.inMemory = 'inmemory'; + /** + * A schema that is used for setting files + */ + Schemas.vscode = 'vscode'; + /** + * A schema that is used for internal private files + */ + Schemas.internal = 'private'; + /** + * A walk-through document. + */ + Schemas.walkThrough = 'walkThrough'; + /** + * An embedded code snippet. + */ + Schemas.walkThroughSnippet = 'walkThroughSnippet'; + Schemas.http = 'http'; + Schemas.https = 'https'; + Schemas.file = 'file'; + Schemas.mailto = 'mailto'; + Schemas.untitled = 'untitled'; + Schemas.data = 'data'; + Schemas.command = 'command'; + Schemas.vscodeRemote = 'vscode-remote'; + Schemas.vscodeRemoteResource = 'vscode-remote-resource'; + Schemas.vscodeManagedRemoteResource = 'vscode-managed-remote-resource'; + Schemas.vscodeUserData = 'vscode-userdata'; + Schemas.vscodeCustomEditor = 'vscode-custom-editor'; + Schemas.vscodeNotebookCell = 'vscode-notebook-cell'; + Schemas.vscodeNotebookCellMetadata = 'vscode-notebook-cell-metadata'; + Schemas.vscodeNotebookCellMetadataDiff = 'vscode-notebook-cell-metadata-diff'; + Schemas.vscodeNotebookCellOutput = 'vscode-notebook-cell-output'; + Schemas.vscodeNotebookCellOutputDiff = 'vscode-notebook-cell-output-diff'; + Schemas.vscodeNotebookMetadata = 'vscode-notebook-metadata'; + Schemas.vscodeInteractiveInput = 'vscode-interactive-input'; + Schemas.vscodeSettings = 'vscode-settings'; + Schemas.vscodeWorkspaceTrust = 'vscode-workspace-trust'; + Schemas.vscodeTerminal = 'vscode-terminal'; + /** Scheme used for code blocks in chat. */ + Schemas.vscodeChatCodeBlock = 'vscode-chat-code-block'; + /** Scheme used for LHS of code compare (aka diff) blocks in chat. */ + Schemas.vscodeChatCodeCompareBlock = 'vscode-chat-code-compare-block'; + /** Scheme used for the chat input editor. */ + Schemas.vscodeChatSesssion = 'vscode-chat-editor'; + /** + * Scheme used internally for webviews that aren't linked to a resource (i.e. not custom editors) + */ + Schemas.webviewPanel = 'webview-panel'; + /** + * Scheme used for loading the wrapper html and script in webviews. + */ + Schemas.vscodeWebview = 'vscode-webview'; + /** + * Scheme used for extension pages + */ + Schemas.extension = 'extension'; + /** + * Scheme used as a replacement of `file` scheme to load + * files with our custom protocol handler (desktop only). + */ + Schemas.vscodeFileResource = 'vscode-file'; + /** + * Scheme used for temporary resources + */ + Schemas.tmp = 'tmp'; + /** + * Scheme used vs live share + */ + Schemas.vsls = 'vsls'; + /** + * Scheme used for the Source Control commit input's text document + */ + Schemas.vscodeSourceControl = 'vscode-scm'; + /** + * Scheme used for input box for creating comments. + */ + Schemas.commentsInput = 'comment'; + /** + * Scheme used for special rendering of settings in the release notes + */ + Schemas.codeSetting = 'code-setting'; + /** + * Scheme used for output panel resources + */ + Schemas.outputChannel = 'output'; + /** + * Scheme used for the accessible view + */ + Schemas.accessibleView = 'accessible-view'; +})(Schemas = Schemas || (Schemas = {})); +export function matchesScheme(target, scheme) { + if (URI.isUri(target)) { + return equalsIgnoreCase(target.scheme, scheme); + } + else { + return startsWithIgnoreCase(target, scheme + ':'); + } +} +export function matchesSomeScheme(target, ...schemes) { + return schemes.some(scheme => matchesScheme(target, scheme)); +} +export const connectionTokenCookieName = 'vscode-tkn'; +export const connectionTokenQueryName = 'tkn'; +class RemoteAuthoritiesImpl { + _hosts = Object.create(null); + _ports = Object.create(null); + _connectionTokens = Object.create(null); + _preferredWebSchema = 'http'; + _delegate = null; + _serverRootPath = '/'; + setPreferredWebSchema(schema) { + this._preferredWebSchema = schema; + } + setDelegate(delegate) { + this._delegate = delegate; + } + setServerRootPath(product, serverBasePath) { + this._serverRootPath = paths.posix.join(serverBasePath ?? '/', getServerProductSegment(product)); + } + getServerRootPath() { + return this._serverRootPath; + } + get _remoteResourcesPath() { + return paths.posix.join(this._serverRootPath, Schemas.vscodeRemoteResource); + } + set(authority, host, port) { + this._hosts[authority] = host; + this._ports[authority] = port; + } + setConnectionToken(authority, connectionToken) { + this._connectionTokens[authority] = connectionToken; + } + getPreferredWebSchema() { + return this._preferredWebSchema; + } + rewrite(uri) { + if (this._delegate) { + try { + return this._delegate(uri); + } + catch (err) { + errors.onUnexpectedError(err); + return uri; + } + } + const authority = uri.authority; + let host = this._hosts[authority]; + if (host && host.indexOf(':') !== -1 && host.indexOf('[') === -1) { + host = `[${host}]`; + } + const port = this._ports[authority]; + const connectionToken = this._connectionTokens[authority]; + let query = `path=${encodeURIComponent(uri.path)}`; + if (typeof connectionToken === 'string') { + query += `&${connectionTokenQueryName}=${encodeURIComponent(connectionToken)}`; + } + return URI.from({ + scheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource, + authority: `${host}:${port}`, + path: this._remoteResourcesPath, + query + }); + } +} +export const RemoteAuthorities = new RemoteAuthoritiesImpl(); +export function getServerProductSegment(product) { + return `${product.quality ?? 'oss'}-${product.commit ?? 'dev'}`; +} +export const builtinExtensionsPath = 'vs/../../extensions'; +export const nodeModulesPath = 'vs/../../node_modules'; +export const nodeModulesAsarPath = 'vs/../../node_modules.asar'; +export const nodeModulesAsarUnpackedPath = 'vs/../../node_modules.asar.unpacked'; +export const VSCODE_AUTHORITY = 'vscode-app'; +class FileAccessImpl { + static FALLBACK_AUTHORITY = VSCODE_AUTHORITY; + /** + * Returns a URI to use in contexts where the browser is responsible + * for loading (e.g. fetch()) or when used within the DOM. + * + * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context. + */ + asBrowserUri(resourcePath) { + const uri = this.toUri(resourcePath); + return this.uriToBrowserUri(uri); + } + /** + * Returns a URI to use in contexts where the browser is responsible + * for loading (e.g. fetch()) or when used within the DOM. + * + * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context. + */ + uriToBrowserUri(uri) { + // Handle remote URIs via `RemoteAuthorities` + if (uri.scheme === Schemas.vscodeRemote) { + return RemoteAuthorities.rewrite(uri); + } + // Convert to `vscode-file` resource.. + if ( + // ...only ever for `file` resources + uri.scheme === Schemas.file && + ( + // ...and we run in native environments + platform.isNative || + // ...or web worker extensions on desktop + (platform.webWorkerOrigin === `${Schemas.vscodeFileResource}://${FileAccessImpl.FALLBACK_AUTHORITY}`))) { + return uri.with({ + scheme: Schemas.vscodeFileResource, + // We need to provide an authority here so that it can serve + // as origin for network and loading matters in chromium. + // If the URI is not coming with an authority already, we + // add our own + authority: uri.authority || FileAccessImpl.FALLBACK_AUTHORITY, + query: null, + fragment: null + }); + } + return uri; + } + /** + * Returns the `file` URI to use in contexts where node.js + * is responsible for loading. + */ + asFileUri(resourcePath) { + const uri = this.toUri(resourcePath); + return this.uriToFileUri(uri); + } + /** + * Returns the `file` URI to use in contexts where node.js + * is responsible for loading. + */ + uriToFileUri(uri) { + // Only convert the URI if it is `vscode-file:` scheme + if (uri.scheme === Schemas.vscodeFileResource) { + return uri.with({ + scheme: Schemas.file, + // Only preserve the `authority` if it is different from + // our fallback authority. This ensures we properly preserve + // Windows UNC paths that come with their own authority. + authority: uri.authority !== FileAccessImpl.FALLBACK_AUTHORITY ? uri.authority : null, + query: null, + fragment: null + }); + } + return uri; + } + toUri(uriOrModule, moduleIdToUrl) { + if (URI.isUri(uriOrModule)) { + return uriOrModule; + } + if (globalThis._VSCODE_FILE_ROOT) { + const rootUriOrPath = globalThis._VSCODE_FILE_ROOT; + // File URL (with scheme) + if (/^\w[\w\d+.-]*:\/\//.test(rootUriOrPath)) { + return URI.joinPath(URI.parse(rootUriOrPath, true), uriOrModule); + } + // File Path (no scheme) + const modulePath = paths.join(rootUriOrPath, uriOrModule); + return URI.file(modulePath); + } + return URI.parse(moduleIdToUrl.toUrl(uriOrModule)); + } +} +export const FileAccess = new FileAccessImpl(); +export var COI; +(function (COI) { + const coiHeaders = new Map([ + ['1', { 'Cross-Origin-Opener-Policy': 'same-origin' }], + ['2', { 'Cross-Origin-Embedder-Policy': 'require-corp' }], + ['3', { 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp' }], + ]); + COI.CoopAndCoep = Object.freeze(coiHeaders.get('3')); + const coiSearchParamName = 'vscode-coi'; + /** + * Extract desired headers from `vscode-coi` invocation + */ + function getHeadersFromQuery(url) { + let params; + if (typeof url === 'string') { + params = new URL(url).searchParams; + } + else if (url instanceof URL) { + params = url.searchParams; + } + else if (URI.isUri(url)) { + params = new URL(url.toString(true)).searchParams; + } + const value = params?.get(coiSearchParamName); + if (!value) { + return undefined; + } + return coiHeaders.get(value); + } + COI.getHeadersFromQuery = getHeadersFromQuery; + /** + * Add the `vscode-coi` query attribute based on wanting `COOP` and `COEP`. Will be a noop when `crossOriginIsolated` + * isn't enabled the current context + */ + function addSearchParam(urlOrSearch, coop, coep) { + if (!globalThis.crossOriginIsolated) { + // depends on the current context being COI + return; + } + const value = coop && coep ? '3' : coep ? '2' : '1'; + if (urlOrSearch instanceof URLSearchParams) { + urlOrSearch.set(coiSearchParamName, value); + } + else { + urlOrSearch[coiSearchParamName] = value; + } + } + COI.addSearchParam = addSearchParam; +})(COI = COI || (COI = {})); +//# sourceMappingURL=network.js.map \ No newline at end of file diff --git a/packages/core/dist/network.js.map b/packages/core/dist/network.js.map new file mode 100644 index 00000000..5eaf56a2 --- /dev/null +++ b/packages/core/dist/network.js.map @@ -0,0 +1 @@ +{"version":3,"file":"network.js","sourceRoot":"","sources":["../src/network.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACtE,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,KAAK,KAAK,MAAM,WAAW,CAAC;AAEnC,MAAM,KAAW,OAAO,CAkIvB;AAlID,WAAiB,OAAO;IAEvB;;;OAGG;IACU,gBAAQ,GAAG,UAAU,CAAC;IAEnC;;OAEG;IACU,cAAM,GAAG,QAAQ,CAAC;IAE/B;;OAEG;IACU,gBAAQ,GAAG,SAAS,CAAC;IAElC;;OAEG;IACU,mBAAW,GAAG,aAAa,CAAC;IAEzC;;OAEG;IACU,0BAAkB,GAAG,oBAAoB,CAAC;IAE1C,YAAI,GAAG,MAAM,CAAC;IAEd,aAAK,GAAG,OAAO,CAAC;IAEhB,YAAI,GAAG,MAAM,CAAC;IAEd,cAAM,GAAG,QAAQ,CAAC;IAElB,gBAAQ,GAAG,UAAU,CAAC;IAEtB,YAAI,GAAG,MAAM,CAAC;IAEd,eAAO,GAAG,SAAS,CAAC;IAEpB,oBAAY,GAAG,eAAe,CAAC;IAE/B,4BAAoB,GAAG,wBAAwB,CAAC;IAEhD,mCAA2B,GAAG,gCAAgC,CAAC;IAE/D,sBAAc,GAAG,iBAAiB,CAAC;IAEnC,0BAAkB,GAAG,sBAAsB,CAAC;IAE5C,0BAAkB,GAAG,sBAAsB,CAAC;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CAAC,GAAG,CAAC,CAAC,YAAY,CAAC;SACnC;aAAM,IAAI,GAAG,YAAY,GAAG,EAAE;YAC9B,MAAM,GAAG,GAAG,CAAC,YAAY,CAAC;SAC1B;aAAM,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;YAC1B,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC;SAClD;QACD,MAAM,KAAK,GAAG,MAAM,EAAE,GAAG,CAAC,kBAAkB,CAAC,CAAC;QAC9C,IAAI,CAAC,KAAK,EAAE;YACX,OAAO,SAAS,CAAC;SACjB;QACD,OAAO,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAde,uBAAmB,sBAclC,CAAA;IAED;;;OAGG;IACH,SAAgB,cAAc,CAAC,WAAqD,EAAE,IAAa,EAAE,IAAa;QACjH,IAAI,CAAO,UAAW,CAAC,mBAAmB,EAAE;YAC3C,2CAA2C;YAC3C,OAAO;SACP;QACD,MAAM,KAAK,GAAG,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;QACpD,IAAI,WAAW,YAAY,eAAe,EAAE;YAC3C,WAAW,CAAC,GAAG,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;SAC3C;aAAM;YACmB,WAAY,CAAC,kBAAkB,CAAC,GAAG,KAAK,CAAC;SAClE;IACF,CAAC;IAXe,kBAAc,iBAW7B,CAAA;AACF,CAAC,EA/CgB,GAAG,GAAH,GAAG,KAAH,GAAG,QA+CnB"} \ No newline at end of file diff --git a/packages/core/dist/nls.d.ts b/packages/core/dist/nls.d.ts new file mode 100644 index 00000000..99ed9160 --- /dev/null +++ b/packages/core/dist/nls.d.ts @@ -0,0 +1,142 @@ +export { getNLSLanguage, getNLSMessages } from './nls.messages.js'; +export interface ILocalizeInfo { + key: string; + comment: string[]; +} +export interface ILocalizedString { + original: string; + value: string; +} +/** + * Marks a string to be localized. Returns the localized string. + * + * @param info The {@linkcode ILocalizeInfo} which describes the id and comments associated with the localized string. + * @param message The string to localize + * @param args The arguments to the string + * + * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args` + * @example `localize({ key: 'sayHello', comment: ['Welcomes user'] }, 'hello {0}', name)` + * + * @returns string The localized string. + */ +export declare function localize(info: ILocalizeInfo, message: string, ...args: (string | number | boolean | undefined | null)[]): string; +/** + * Marks a string to be localized. Returns the localized string. + * + * @param key The key to use for localizing the string + * @param message The string to localize + * @param args The arguments to the string + * + * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args` + * @example For example, `localize('sayHello', 'hello {0}', name)` + * + * @returns string The localized string. + */ +export declare function localize(key: string, message: string, ...args: (string | number | boolean | undefined | null)[]): string; +/** + * Marks a string to be localized. Returns an {@linkcode ILocalizedString} + * which contains the localized string and the original string. + * + * @param info The {@linkcode ILocalizeInfo} which describes the id and comments associated with the localized string. + * @param message The string to localize + * @param args The arguments to the string + * + * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args` + * @example `localize2({ key: 'sayHello', comment: ['Welcomes user'] }, 'hello {0}', name)` + * + * @returns ILocalizedString which contains the localized string and the original string. + */ +export declare function localize2(info: ILocalizeInfo, message: string, ...args: (string | number | boolean | undefined | null)[]): ILocalizedString; +/** + * Marks a string to be localized. Returns an {@linkcode ILocalizedString} + * which contains the localized string and the original string. + * + * @param key The key to use for localizing the string + * @param message The string to localize + * @param args The arguments to the string + * + * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args` + * @example `localize('sayHello', 'hello {0}', name)` + * + * @returns ILocalizedString which contains the localized string and the original string. + */ +export declare function localize2(key: string, message: string, ...args: (string | number | boolean | undefined | null)[]): ILocalizedString; +export interface INLSLanguagePackConfiguration { + /** + * The path to the translations config file that contains pointers to + * all message bundles for `main` and extensions. + */ + readonly translationsConfigFile: string; + /** + * The path to the file containing the translations for this language + * pack as flat string array. + */ + readonly messagesFile: string; + /** + * The path to the file that can be used to signal a corrupt language + * pack, for example when reading the `messagesFile` fails. This will + * instruct the application to re-create the cache on next startup. + */ + readonly corruptMarkerFile: string; +} +export interface INLSConfiguration { + /** + * Locale as defined in `argv.json` or `app.getLocale()`. + */ + readonly userLocale: string; + /** + * Locale as defined by the OS (e.g. `app.getPreferredSystemLanguages()`). + */ + readonly osLocale: string; + /** + * The actual language of the UI that ends up being used considering `userLocale` + * and `osLocale`. + */ + readonly resolvedLanguage: string; + /** + * Defined if a language pack is used that is not the + * default english language pack. This requires a language + * pack to be installed as extension. + */ + readonly languagePack?: INLSLanguagePackConfiguration; + /** + * The path to the file containing the default english messages + * as flat string array. The file is only present in built + * versions of the application. + */ + readonly defaultMessagesFile: string; + /** + * Below properties are deprecated and only there to continue support + * for `vscode-nls` module that depends on them. + * Refs https://github.com/microsoft/vscode-nls/blob/main/src/node/main.ts#L36-L46 + */ + /** @deprecated */ + readonly locale: string; + /** @deprecated */ + readonly availableLanguages: Record; + /** @deprecated */ + readonly _languagePackSupport?: boolean; + /** @deprecated */ + readonly _languagePackId?: string; + /** @deprecated */ + readonly _translationsConfigFile?: string; + /** @deprecated */ + readonly _cacheRoot?: string; + /** @deprecated */ + readonly _resolvedLanguagePackCoreLocation?: string; + /** @deprecated */ + readonly _corruptedFile?: string; +} +export interface ILanguagePack { + readonly hash: string; + readonly label: string | undefined; + readonly extensions: { + readonly extensionIdentifier: { + readonly id: string; + readonly uuid?: string; + }; + readonly version: string; + }[]; + readonly translations: Record; +} +export type ILanguagePacks = Record; diff --git a/packages/core/dist/nls.js b/packages/core/dist/nls.js new file mode 100644 index 00000000..c7289444 --- /dev/null +++ b/packages/core/dist/nls.js @@ -0,0 +1,76 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +// eslint-disable-next-line local/code-import-patterns +import { getNLSLanguage, getNLSMessages } from './nls.messages.js'; +// eslint-disable-next-line local/code-import-patterns +export { getNLSLanguage, getNLSMessages } from './nls.messages.js'; +const isPseudo = getNLSLanguage() === 'pseudo' || (typeof document !== 'undefined' && document.location && typeof document.location.hash === 'string' && document.location.hash.indexOf('pseudo=true') >= 0); +function _format(message, args) { + let result; + if (args.length === 0) { + result = message; + } + else { + result = message.replace(/\{(\d+)\}/g, (match, rest) => { + const index = rest[0]; + const arg = args[index]; + let result = match; + if (typeof arg === 'string') { + result = arg; + } + else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === void 0 || arg === null) { + result = String(arg); + } + return result; + }); + } + if (isPseudo) { + // FF3B and FF3D is the Unicode zenkaku representation for [ and ] + result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D'; + } + return result; +} +/** + * @skipMangle + */ +export function localize(data /* | number when built */, message /* | null when built */, ...args) { + if (typeof data === 'number') { + return _format(lookupMessage(data, message), args); + } + return _format(message, args); +} +/** + * Only used when built: Looks up the message in the global NLS table. + * This table is being made available as a global through bootstrapping + * depending on the target context. + */ +function lookupMessage(index, fallback) { + const message = getNLSMessages()?.[index]; + if (typeof message !== 'string') { + if (typeof fallback === 'string') { + return fallback; + } + throw new Error(`!!! NLS MISSING: ${index} !!!`); + } + return message; +} +/** + * @skipMangle + */ +export function localize2(data /* | number when built */, originalMessage, ...args) { + let message; + if (typeof data === 'number') { + message = lookupMessage(data, originalMessage); + } + else { + message = originalMessage; + } + const value = _format(message, args); + return { + value, + original: originalMessage === message ? value : _format(originalMessage, args) + }; +} +//# sourceMappingURL=nls.js.map \ No newline at end of file diff --git a/packages/core/dist/nls.js.map b/packages/core/dist/nls.js.map new file mode 100644 index 00000000..ef09ad53 --- /dev/null +++ b/packages/core/dist/nls.js.map @@ -0,0 +1 @@ +{"version":3,"file":"nls.js","sourceRoot":"","sources":["../src/nls.ts"],"names":[],"mappings":"AAAA;;;gGAG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CAAC"} \ No newline at end of file diff --git a/packages/core/dist/nls.messages.d.ts b/packages/core/dist/nls.messages.d.ts new file mode 100644 index 00000000..b8f9ac84 --- /dev/null +++ b/packages/core/dist/nls.messages.d.ts @@ -0,0 +1,2 @@ +export declare function getNLSMessages(): string[]; +export declare function getNLSLanguage(): string | undefined; diff --git a/packages/core/dist/nls.messages.js b/packages/core/dist/nls.messages.js new file mode 100644 index 00000000..008a5f00 --- /dev/null +++ b/packages/core/dist/nls.messages.js @@ -0,0 +1,17 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +/* + * This module exists so that the AMD build of the monaco editor can replace this with an async loader plugin. + * If you add new functions to this module make sure that they are also provided in the AMD build of the monaco editor. + * + * TODO@esm remove me once we no longer ship an AMD build. + */ +export function getNLSMessages() { + return globalThis._VSCODE_NLS_MESSAGES; +} +export function getNLSLanguage() { + return globalThis._VSCODE_NLS_LANGUAGE; +} +//# sourceMappingURL=nls.messages.js.map \ No newline at end of file diff --git a/packages/core/dist/nls.messages.js.map b/packages/core/dist/nls.messages.js.map new file mode 100644 index 00000000..b8aa5311 --- /dev/null +++ b/packages/core/dist/nls.messages.js.map @@ -0,0 +1 @@ +{"version":3,"file":"nls.messages.js","sourceRoot":"","sources":["../src/nls.messages.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG;;;;;GAKG;AAEH,MAAM,UAAU,cAAc;IAC7B,OAAO,UAAU,CAAC,oBAAoB,CAAC;AACxC,CAAC;AAED,MAAM,UAAU,cAAc;IAC7B,OAAO,UAAU,CAAC,oBAAoB,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/objects.d.ts b/packages/core/dist/objects.d.ts new file mode 100644 index 00000000..b722a516 --- /dev/null +++ b/packages/core/dist/objects.d.ts @@ -0,0 +1,38 @@ +export declare function deepClone(obj: T): T; +export declare function deepFreeze(obj: T): T; +export declare function cloneAndChange(obj: any, changer: (orig: any) => any): any; +/** + * Copies all properties of source into destination. The optional parameter "overwrite" allows to control + * if existing properties on the destination should be overwritten or not. Defaults to true (overwrite). + */ +export declare function mixin(destination: any, source: any, overwrite?: boolean): any; +export declare function equals(one: any, other: any): boolean; +/** + * Calls `JSON.Stringify` with a replacer to break apart any circular references. + * This prevents `JSON`.stringify` from throwing the exception + * "Uncaught TypeError: Converting circular structure to JSON" + */ +export declare function safeStringify(obj: any): string; +type obj = { + [key: string]: any; +}; +/** + * Returns an object that has keys for each value that is different in the base object. Keys + * that do not exist in the target but in the base object are not considered. + * + * Note: This is not a deep-diffing method, so the values are strictly taken into the resulting + * object if they differ. + * + * @param base the object to diff against + * @param obj the object to use for diffing + */ +export declare function distinct(base: obj, target: obj): obj; +export declare function getCaseInsensitive(target: obj, key: string): unknown; +export declare function filter(obj: obj, predicate: (key: string, value: any) => boolean): obj; +export declare function getAllPropertyNames(obj: object): string[]; +export declare function getAllMethodNames(obj: object): string[]; +export declare function createProxyObject(methodNames: string[], invoke: (method: string, args: unknown[]) => unknown): T; +export declare function mapValues(obj: T, fn: (value: T[keyof T], key: string) => R): { + [K in keyof T]: R; +}; +export {}; diff --git a/packages/core/dist/objects.js b/packages/core/dist/objects.js new file mode 100644 index 00000000..394f4ef0 --- /dev/null +++ b/packages/core/dist/objects.js @@ -0,0 +1,249 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { isTypedArray, isObject, isUndefinedOrNull } from './primitives.js'; +export function deepClone(obj) { + if (!obj || typeof obj !== 'object') { + return obj; + } + if (obj instanceof RegExp) { + return obj; + } + const result = Array.isArray(obj) ? [] : {}; + Object.entries(obj).forEach(([key, value]) => { + result[key] = value && typeof value === 'object' ? deepClone(value) : value; + }); + return result; +} +export function deepFreeze(obj) { + if (!obj || typeof obj !== 'object') { + return obj; + } + const stack = [obj]; + while (stack.length > 0) { + const obj = stack.shift(); + Object.freeze(obj); + for (const key in obj) { + if (_hasOwnProperty.call(obj, key)) { + const prop = obj[key]; + if (typeof prop === 'object' && !Object.isFrozen(prop) && !isTypedArray(prop)) { + stack.push(prop); + } + } + } + } + return obj; +} +const _hasOwnProperty = Object.prototype.hasOwnProperty; +export function cloneAndChange(obj, changer) { + return _cloneAndChange(obj, changer, new Set()); +} +function _cloneAndChange(obj, changer, seen) { + if (isUndefinedOrNull(obj)) { + return obj; + } + const changed = changer(obj); + if (typeof changed !== 'undefined') { + return changed; + } + if (Array.isArray(obj)) { + const r1 = []; + for (const e of obj) { + r1.push(_cloneAndChange(e, changer, seen)); + } + return r1; + } + if (isObject(obj)) { + if (seen.has(obj)) { + throw new Error('Cannot clone recursive data-structure'); + } + seen.add(obj); + const r2 = {}; + for (const i2 in obj) { + if (_hasOwnProperty.call(obj, i2)) { + r2[i2] = _cloneAndChange(obj[i2], changer, seen); + } + } + seen.delete(obj); + return r2; + } + return obj; +} +/** + * Copies all properties of source into destination. The optional parameter "overwrite" allows to control + * if existing properties on the destination should be overwritten or not. Defaults to true (overwrite). + */ +export function mixin(destination, source, overwrite = true) { + if (!isObject(destination)) { + return source; + } + if (isObject(source)) { + Object.keys(source).forEach(key => { + if (key in destination) { + if (overwrite) { + if (isObject(destination[key]) && isObject(source[key])) { + mixin(destination[key], source[key], overwrite); + } + else { + destination[key] = source[key]; + } + } + } + else { + destination[key] = source[key]; + } + }); + } + return destination; +} +export function equals(one, other) { + if (one === other) { + return true; + } + if (one === null || one === undefined || other === null || other === undefined) { + return false; + } + if (typeof one !== typeof other) { + return false; + } + if (typeof one !== 'object') { + return false; + } + if ((Array.isArray(one)) !== (Array.isArray(other))) { + return false; + } + let i; + let key; + if (Array.isArray(one)) { + if (one.length !== other.length) { + return false; + } + for (i = 0; i < one.length; i++) { + if (!equals(one[i], other[i])) { + return false; + } + } + } + else { + const oneKeys = []; + for (key in one) { + oneKeys.push(key); + } + oneKeys.sort(); + const otherKeys = []; + for (key in other) { + otherKeys.push(key); + } + otherKeys.sort(); + if (!equals(oneKeys, otherKeys)) { + return false; + } + for (i = 0; i < oneKeys.length; i++) { + if (!equals(one[oneKeys[i]], other[oneKeys[i]])) { + return false; + } + } + } + return true; +} +/** + * Calls `JSON.Stringify` with a replacer to break apart any circular references. + * This prevents `JSON`.stringify` from throwing the exception + * "Uncaught TypeError: Converting circular structure to JSON" + */ +export function safeStringify(obj) { + const seen = new Set(); + return JSON.stringify(obj, (key, value) => { + if (isObject(value) || Array.isArray(value)) { + if (seen.has(value)) { + return '[Circular]'; + } + else { + seen.add(value); + } + } + if (typeof value === 'bigint') { + return `[BigInt ${value.toString()}]`; + } + return value; + }); +} +/** + * Returns an object that has keys for each value that is different in the base object. Keys + * that do not exist in the target but in the base object are not considered. + * + * Note: This is not a deep-diffing method, so the values are strictly taken into the resulting + * object if they differ. + * + * @param base the object to diff against + * @param obj the object to use for diffing + */ +export function distinct(base, target) { + const result = Object.create(null); + if (!base || !target) { + return result; + } + const targetKeys = Object.keys(target); + targetKeys.forEach(k => { + const baseValue = base[k]; + const targetValue = target[k]; + if (!equals(baseValue, targetValue)) { + result[k] = targetValue; + } + }); + return result; +} +export function getCaseInsensitive(target, key) { + const lowercaseKey = key.toLowerCase(); + const equivalentKey = Object.keys(target).find(k => k.toLowerCase() === lowercaseKey); + return equivalentKey ? target[equivalentKey] : target[key]; +} +export function filter(obj, predicate) { + const result = Object.create(null); + for (const [key, value] of Object.entries(obj)) { + if (predicate(key, value)) { + result[key] = value; + } + } + return result; +} +export function getAllPropertyNames(obj) { + let res = []; + while (Object.prototype !== obj) { + res = res.concat(Object.getOwnPropertyNames(obj)); + obj = Object.getPrototypeOf(obj); + } + return res; +} +export function getAllMethodNames(obj) { + const methods = []; + for (const prop of getAllPropertyNames(obj)) { + if (typeof obj[prop] === 'function') { + methods.push(prop); + } + } + return methods; +} +export function createProxyObject(methodNames, invoke) { + const createProxyMethod = (method) => { + return function () { + const args = Array.prototype.slice.call(arguments, 0); + return invoke(method, args); + }; + }; + // eslint-disable-next-line local/code-no-dangerous-type-assertions + const result = {}; + for (const methodName of methodNames) { + result[methodName] = createProxyMethod(methodName); + } + return result; +} +export function mapValues(obj, fn) { + const result = {}; + for (const [key, value] of Object.entries(obj)) { + result[key] = fn(value, key); + } + return result; +} +//# sourceMappingURL=objects.js.map \ No newline at end of file diff --git a/packages/core/dist/objects.js.map b/packages/core/dist/objects.js.map new file mode 100644 index 00000000..f7139885 --- /dev/null +++ b/packages/core/dist/objects.js.map @@ -0,0 +1 @@ +{"version":3,"file":"objects.js","sourceRoot":"","sources":["../src/objects.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAE5E,MAAM,UAAU,SAAS,CAAI,GAAM;IAClC,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QACpC,OAAO,GAAG,CAAC;KACX;IACD,IAAI,GAAG,YAAY,MAAM,EAAE;QAC1B,OAAO,GAAG,CAAC;KACX;IACD,MAAM,MAAM,GAAQ,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACjD,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QAC5C,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC7E,CAAC,CAAC,CAAC;IACH,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,UAAU,CAAI,GAAM;IACnC,IAAI,CAAC,GAAG,IAAI,OAAO,GAAG,KA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BAAiB,CAAC,UAAU,CAAC,CAAC;KAC1D;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,SAAS,CAAkB,GAAM,EAAE,EAAyC;IAC3F,MAAM,MAAM,GAAyB,EAAE,CAAC;IACxC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;QAC/C,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAa,KAAK,EAAE,GAAG,CAAC,CAAC;KACzC;IACD,OAAO,MAA+B,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/observable.d.ts b/packages/core/dist/observable.d.ts new file mode 100644 index 00000000..ab10390c --- /dev/null +++ b/packages/core/dist/observable.d.ts @@ -0,0 +1 @@ +export * from './observableInternal/index.js'; diff --git a/packages/core/dist/observable.js b/packages/core/dist/observable.js new file mode 100644 index 00000000..d4320aff --- /dev/null +++ b/packages/core/dist/observable.js @@ -0,0 +1,7 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +// This is a facade for the observable implementation. Only import from here! +export * from './observableInternal/index.js'; +//# sourceMappingURL=observable.js.map \ No newline at end of file diff --git a/packages/core/dist/observable.js.map b/packages/core/dist/observable.js.map new file mode 100644 index 00000000..55a81aac --- /dev/null +++ b/packages/core/dist/observable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"observable.js","sourceRoot":"","sources":["../src/observable.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,6EAA6E;AAE7E,cAAc,+BAA+B,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/api.d.ts b/packages/core/dist/observableInternal/api.d.ts new file mode 100644 index 00000000..5d086cba --- /dev/null +++ b/packages/core/dist/observableInternal/api.d.ts @@ -0,0 +1,7 @@ +import { ISettableObservable } from './base.js'; +import { IDebugNameData } from './debugName.js'; +import { EqualityComparer } from './commonFacade/deps.js'; +export declare function observableValueOpts(options: IDebugNameData & { + equalsFn?: EqualityComparer; + lazy?: boolean; +}, initialValue: T): ISettableObservable; diff --git a/packages/core/dist/observableInternal/api.js b/packages/core/dist/observableInternal/api.js new file mode 100644 index 00000000..8b31e011 --- /dev/null +++ b/packages/core/dist/observableInternal/api.js @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { ObservableValue } from './base.js'; +import { DebugNameData } from './debugName.js'; +import { strictEquals } from './commonFacade/deps.js'; +import { LazyObservableValue } from './lazyObservableValue.js'; +export function observableValueOpts(options, initialValue) { + if (options.lazy) { + return new LazyObservableValue(new DebugNameData(options.owner, options.debugName, undefined), initialValue, options.equalsFn ?? strictEquals); + } + return new ObservableValue(new DebugNameData(options.owner, options.debugName, undefined), initialValue, options.equalsFn ?? strictEquals); +} +//# sourceMappingURL=api.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/api.js.map b/packages/core/dist/observableInternal/api.js.map new file mode 100644 index 00000000..b7b574ad --- /dev/null +++ b/packages/core/dist/observableInternal/api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/observableInternal/api.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAuB,eAAe,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,EAAE,aAAa,EAAkB,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAoB,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAE/D,MAAM,UAAU,mBAAmB,CAClC,OAGC,EACD,YAAe;IAEf,IAAI,OAAO,CAAC,IAAI,EAAE;QACjB,OAAO,IAAI,mBAAmB,CAC7B,IAAI,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,EAC9D,YAAY,EACZ,OAAO,CAAC,QAAQ,IAAI,YAAY,CAChC,CAAC;KACF;IACD,OAAO,IAAI,eAAe,CACzB,IAAI,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,EAC9D,YAAY,EACZ,OAAO,CAAC,QAAQ,IAAI,YAAY,CAChC,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/autorun.d.ts b/packages/core/dist/observableInternal/autorun.d.ts new file mode 100644 index 00000000..3d86e0e1 --- /dev/null +++ b/packages/core/dist/observableInternal/autorun.d.ts @@ -0,0 +1,73 @@ +import { IChangeContext, IObservable, IObservableWithChange, IObserver, IReader } from './base.js'; +import { DebugNameData, IDebugNameData } from './debugName.js'; +import { DisposableStore, IDisposable } from './commonFacade/deps.js'; +/** + * Runs immediately and whenever a transaction ends and an observed observable changed. + * {@link fn} should start with a JS Doc using `@description` to name the autorun. + */ +export declare function autorun(fn: (reader: IReader) => void): IDisposable; +/** + * Runs immediately and whenever a transaction ends and an observed observable changed. + * {@link fn} should start with a JS Doc using `@description` to name the autorun. + */ +export declare function autorunOpts(options: IDebugNameData & {}, fn: (reader: IReader) => void): IDisposable; +/** + * Runs immediately and whenever a transaction ends and an observed observable changed. + * {@link fn} should start with a JS Doc using `@description` to name the autorun. + * + * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes. + * Use `handleChange` to add a reported change to the change summary. + * The run function is given the last change summary. + * The change summary is discarded after the run function was called. + * + * @see autorun + */ +export declare function autorunHandleChanges(options: IDebugNameData & { + createEmptyChangeSummary?: () => TChangeSummary; + handleChange: (context: IChangeContext, changeSummary: TChangeSummary) => boolean; +}, fn: (reader: IReader, changeSummary: TChangeSummary) => void): IDisposable; +/** + * @see autorunHandleChanges (but with a disposable store that is cleared before the next run or on dispose) + */ +export declare function autorunWithStoreHandleChanges(options: IDebugNameData & { + createEmptyChangeSummary?: () => TChangeSummary; + handleChange: (context: IChangeContext, changeSummary: TChangeSummary) => boolean; +}, fn: (reader: IReader, changeSummary: TChangeSummary, store: DisposableStore) => void): IDisposable; +/** + * @see autorun (but with a disposable store that is cleared before the next run or on dispose) + */ +export declare function autorunWithStore(fn: (reader: IReader, store: DisposableStore) => void): IDisposable; +export declare function autorunDelta(observable: IObservable, handler: (args: { + lastValue: T | undefined; + newValue: T; +}) => void): IDisposable; +export declare function autorunIterableDelta(getValue: (reader: IReader) => Iterable, handler: (args: { + addedValues: T[]; + removedValues: T[]; +}) => void, getUniqueIdentifier?: (value: T) => unknown): IDisposable; +export declare class AutorunObserver implements IObserver, IReader, IDisposable { + readonly _debugNameData: DebugNameData; + readonly _runFn: (reader: IReader, changeSummary: TChangeSummary) => void; + private readonly createChangeSummary; + private readonly _handleChange; + private state; + private updateCount; + private disposed; + private dependencies; + private dependenciesToBeRemoved; + private changeSummary; + get debugName(): string; + constructor(_debugNameData: DebugNameData, _runFn: (reader: IReader, changeSummary: TChangeSummary) => void, createChangeSummary: (() => TChangeSummary) | undefined, _handleChange: ((context: IChangeContext, summary: TChangeSummary) => boolean) | undefined); + dispose(): void; + private _runIfNeeded; + toString(): string; + beginUpdate(): void; + endUpdate(): void; + handlePossibleChange(observable: IObservable): void; + handleChange(observable: IObservableWithChange, change: TChange): void; + private _isReaderValid; + readObservable(observable: IObservable): T; +} +export declare namespace autorun { + const Observer: typeof AutorunObserver; +} diff --git a/packages/core/dist/observableInternal/autorun.js b/packages/core/dist/observableInternal/autorun.js new file mode 100644 index 00000000..44f15071 --- /dev/null +++ b/packages/core/dist/observableInternal/autorun.js @@ -0,0 +1,264 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { DebugNameData } from './debugName.js'; +import { assertFn, BugIndicatingError, DisposableStore, markAsDisposed, onBugIndicatingError, toDisposable, trackDisposable } from './commonFacade/deps.js'; +import { getLogger } from './logging.js'; +/** + * Runs immediately and whenever a transaction ends and an observed observable changed. + * {@link fn} should start with a JS Doc using `@description` to name the autorun. + */ +export function autorun(fn) { + return new AutorunObserver(new DebugNameData(undefined, undefined, fn), fn, undefined, undefined); +} +/** + * Runs immediately and whenever a transaction ends and an observed observable changed. + * {@link fn} should start with a JS Doc using `@description` to name the autorun. + */ +export function autorunOpts(options, fn) { + return new AutorunObserver(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, undefined, undefined); +} +/** + * Runs immediately and whenever a transaction ends and an observed observable changed. + * {@link fn} should start with a JS Doc using `@description` to name the autorun. + * + * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes. + * Use `handleChange` to add a reported change to the change summary. + * The run function is given the last change summary. + * The change summary is discarded after the run function was called. + * + * @see autorun + */ +export function autorunHandleChanges(options, fn) { + return new AutorunObserver(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, options.createEmptyChangeSummary, options.handleChange); +} +/** + * @see autorunHandleChanges (but with a disposable store that is cleared before the next run or on dispose) + */ +export function autorunWithStoreHandleChanges(options, fn) { + const store = new DisposableStore(); + const disposable = autorunHandleChanges({ + owner: options.owner, + debugName: options.debugName, + debugReferenceFn: options.debugReferenceFn ?? fn, + createEmptyChangeSummary: options.createEmptyChangeSummary, + handleChange: options.handleChange, + }, (reader, changeSummary) => { + store.clear(); + fn(reader, changeSummary, store); + }); + return toDisposable(() => { + disposable.dispose(); + store.dispose(); + }); +} +/** + * @see autorun (but with a disposable store that is cleared before the next run or on dispose) + */ +export function autorunWithStore(fn) { + const store = new DisposableStore(); + const disposable = autorunOpts({ + owner: undefined, + debugName: undefined, + debugReferenceFn: fn, + }, reader => { + store.clear(); + fn(reader, store); + }); + return toDisposable(() => { + disposable.dispose(); + store.dispose(); + }); +} +export function autorunDelta(observable, handler) { + let _lastValue; + return autorunOpts({ debugReferenceFn: handler }, (reader) => { + const newValue = observable.read(reader); + const lastValue = _lastValue; + _lastValue = newValue; + handler({ lastValue, newValue }); + }); +} +export function autorunIterableDelta(getValue, handler, getUniqueIdentifier = v => v) { + const lastValues = new Map(); + return autorunOpts({ debugReferenceFn: getValue }, (reader) => { + const newValues = new Map(); + const removedValues = new Map(lastValues); + for (const value of getValue(reader)) { + const id = getUniqueIdentifier(value); + if (lastValues.has(id)) { + removedValues.delete(id); + } + else { + newValues.set(id, value); + lastValues.set(id, value); + } + } + for (const id of removedValues.keys()) { + lastValues.delete(id); + } + if (newValues.size || removedValues.size) { + handler({ addedValues: [...newValues.values()], removedValues: [...removedValues.values()] }); + } + }); +} +var AutorunState; +(function (AutorunState) { + /** + * A dependency could have changed. + * We need to explicitly ask them if at least one dependency changed. + */ + AutorunState[AutorunState["dependenciesMightHaveChanged"] = 1] = "dependenciesMightHaveChanged"; + /** + * A dependency changed and we need to recompute. + */ + AutorunState[AutorunState["stale"] = 2] = "stale"; + AutorunState[AutorunState["upToDate"] = 3] = "upToDate"; +})(AutorunState || (AutorunState = {})); +export class AutorunObserver { + _debugNameData; + _runFn; + createChangeSummary; + _handleChange; + state = 2 /* AutorunState.stale */; + updateCount = 0; + disposed = false; + dependencies = new Set(); + dependenciesToBeRemoved = new Set(); + changeSummary; + get debugName() { + return this._debugNameData.getDebugName(this) ?? '(anonymous)'; + } + constructor(_debugNameData, _runFn, createChangeSummary, _handleChange) { + this._debugNameData = _debugNameData; + this._runFn = _runFn; + this.createChangeSummary = createChangeSummary; + this._handleChange = _handleChange; + this.changeSummary = this.createChangeSummary?.(); + getLogger()?.handleAutorunCreated(this); + this._runIfNeeded(); + trackDisposable(this); + } + dispose() { + this.disposed = true; + for (const o of this.dependencies) { + o.removeObserver(this); + } + this.dependencies.clear(); + markAsDisposed(this); + } + _runIfNeeded() { + if (this.state === 3 /* AutorunState.upToDate */) { + return; + } + const emptySet = this.dependenciesToBeRemoved; + this.dependenciesToBeRemoved = this.dependencies; + this.dependencies = emptySet; + this.state = 3 /* AutorunState.upToDate */; + const isDisposed = this.disposed; + try { + if (!isDisposed) { + getLogger()?.handleAutorunTriggered(this); + const changeSummary = this.changeSummary; + try { + this.changeSummary = this.createChangeSummary?.(); + this._isReaderValid = true; + this._runFn(this, changeSummary); + } + catch (e) { + onBugIndicatingError(e); + } + finally { + this._isReaderValid = false; + } + } + } + finally { + if (!isDisposed) { + getLogger()?.handleAutorunFinished(this); + } + // We don't want our observed observables to think that they are (not even temporarily) not being observed. + // Thus, we only unsubscribe from observables that are definitely not read anymore. + for (const o of this.dependenciesToBeRemoved) { + o.removeObserver(this); + } + this.dependenciesToBeRemoved.clear(); + } + } + toString() { + return `Autorun<${this.debugName}>`; + } + // IObserver implementation + beginUpdate() { + if (this.state === 3 /* AutorunState.upToDate */) { + this.state = 1 /* AutorunState.dependenciesMightHaveChanged */; + } + this.updateCount++; + } + endUpdate() { + try { + if (this.updateCount === 1) { + do { + if (this.state === 1 /* AutorunState.dependenciesMightHaveChanged */) { + this.state = 3 /* AutorunState.upToDate */; + for (const d of this.dependencies) { + d.reportChanges(); + if (this.state === 2 /* AutorunState.stale */) { + // The other dependencies will refresh on demand + break; + } + } + } + this._runIfNeeded(); + } while (this.state !== 3 /* AutorunState.upToDate */); + } + } + finally { + this.updateCount--; + } + assertFn(() => this.updateCount >= 0); + } + handlePossibleChange(observable) { + if (this.state === 3 /* AutorunState.upToDate */ && this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) { + this.state = 1 /* AutorunState.dependenciesMightHaveChanged */; + } + } + handleChange(observable, change) { + if (this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) { + try { + const shouldReact = this._handleChange ? this._handleChange({ + changedObservable: observable, + change, + didChange: (o) => o === observable, + }, this.changeSummary) : true; + if (shouldReact) { + this.state = 2 /* AutorunState.stale */; + } + } + catch (e) { + onBugIndicatingError(e); + } + } + } + // IReader implementation + _isReaderValid = false; + readObservable(observable) { + if (!this._isReaderValid) { + throw new BugIndicatingError('The reader object cannot be used outside its compute function!'); + } + // In case the run action disposes the autorun + if (this.disposed) { + return observable.get(); + } + observable.addObserver(this); + const value = observable.get(); + this.dependencies.add(observable); + this.dependenciesToBeRemoved.delete(observable); + return value; + } +} +(function (autorun) { + autorun.Observer = AutorunObserver; +})(autorun = autorun || (autorun = {})); +//# sourceMappingURL=autorun.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/autorun.js.map b/packages/core/dist/observableInternal/autorun.js.map new file mode 100644 index 00000000..98935262 --- /dev/null +++ b/packages/core/dist/observableInternal/autorun.js.map @@ -0,0 +1 @@ +{"version":3,"file":"autorun.js","sourceRoot":"","sources":["../../src/observableInternal/autorun.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAGhG,OAAO,EAAE,aAAa,EAAkB,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,eAAe,EAAe,cAAc,EAAE,oBAAoB,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzK,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,MAAM,UAAU,OAAO,CAAC,EAA6B;IACpD,OAAO,IAAI,eAAe,CACzB,IAAI,aAAa,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE,CAAC,EAC3C,EAAE,EACF,SAAS,EACT,SAAS,CACT,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,OAA4B,EAAE,EAA6B;IACtF,OAAO,IAAI,eAAe,CACzB,IAAI,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAC,EACnF,EAAE,EACF,SAAS,EACT,SAAS,CACT,CAAC;AACH,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,oBAAoB,CACnC,OAGC,EACD,EAA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AAC;AACzC,CAAC,EAFgB,OAAO,GAAP,OAAO,KAAP,OAAO,QAEvB"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/base.d.ts b/packages/core/dist/observableInternal/base.d.ts new file mode 100644 index 00000000..726589eb --- /dev/null +++ b/packages/core/dist/observableInternal/base.d.ts @@ -0,0 +1,257 @@ +import { DebugNameData, DebugOwner } from './debugName.js'; +import { DisposableStore, EqualityComparer, IDisposable } from './commonFacade/deps.js'; +import { keepObserved, recomputeInitiallyAndOnChange } from './utils.js'; +/** + * Represents an observable value. + * + * @template T The type of the values the observable can hold. + */ +export interface IObservable extends IObservableWithChange { +} +/** + * Represents an observable value. + * + * @template T The type of the values the observable can hold. + * @template TChange The type used to describe value changes + * (usually `void` and only used in advanced scenarios). + * While observers can miss temporary values of an observable, + * they will receive all change values (as long as they are subscribed)! + */ +export interface IObservableWithChange { + /** + * Returns the current value. + * + * Calls {@link IObserver.handleChange} if the observable notices that the value changed. + * Must not be called from {@link IObserver.handleChange}! + */ + get(): T; + /** + * Forces the observable to check for changes and report them. + * + * Has the same effect as calling {@link IObservable.get}, but does not force the observable + * to actually construct the value, e.g. if change deltas are used. + * Calls {@link IObserver.handleChange} if the observable notices that the value changed. + * Must not be called from {@link IObserver.handleChange}! + */ + reportChanges(): void; + /** + * Adds the observer to the set of subscribed observers. + * This method is idempotent. + */ + addObserver(observer: IObserver): void; + /** + * Removes the observer from the set of subscribed observers. + * This method is idempotent. + */ + removeObserver(observer: IObserver): void; + /** + * Reads the current value and subscribes the reader to this observable. + * + * Calls {@link IReader.readObservable} if a reader is given, otherwise {@link IObservable.get} + * (see {@link ConvenientObservable.read} for the implementation). + */ + read(reader: IReader | undefined): T; + /** + * Creates a derived observable that depends on this observable. + * Use the reader to read other observables + * (see {@link ConvenientObservable.map} for the implementation). + */ + map(fn: (value: T, reader: IReader) => TNew): IObservable; + map(owner: object, fn: (value: T, reader: IReader) => TNew): IObservable; + flatten(this: IObservable>): IObservable; + /** + * ONLY FOR DEBUGGING! + * Logs computations of this derived. + */ + log(): IObservableWithChange; + /** + * Makes sure this value is computed eagerly. + */ + recomputeInitiallyAndOnChange(store: DisposableStore, handleValue?: (value: T) => void): IObservable; + /** + * Makes sure this value is cached. + */ + keepObserved(store: DisposableStore): IObservable; + /** + * A human-readable name for debugging purposes. + */ + readonly debugName: string; + /** + * This property captures the type of the change object. Do not use it at runtime! + */ + readonly TChange: TChange; +} +export interface IReader { + /** + * Reads the value of an observable and subscribes to it. + */ + readObservable(observable: IObservableWithChange): T; +} +/** + * Represents an observer that can be subscribed to an observable. + * + * If an observer is subscribed to an observable and that observable didn't signal + * a change through one of the observer methods, the observer can assume that the + * observable didn't change. + * If an observable reported a possible change, {@link IObservable.reportChanges} forces + * the observable to report an actual change if there was one. + */ +export interface IObserver { + /** + * Signals that the given observable might have changed and a transaction potentially modifying that observable started. + * Before the given observable can call this method again, is must call {@link IObserver.endUpdate}. + * + * Implementations must not get/read the value of other observables, as they might not have received this event yet! + * The method {@link IObservable.reportChanges} can be used to force the observable to report the changes. + */ + beginUpdate(observable: IObservable): void; + /** + * Signals that the transaction that potentially modified the given observable ended. + * This is a good place to react to (potential) changes. + */ + endUpdate(observable: IObservable): void; + /** + * Signals that the given observable might have changed. + * The method {@link IObservable.reportChanges} can be used to force the observable to report the changes. + * + * Implementations must not get/read the value of other observables, as they might not have received this event yet! + * The change should be processed lazily or in {@link IObserver.endUpdate}. + */ + handlePossibleChange(observable: IObservable): void; + /** + * Signals that the given {@link observable} changed. + * + * Implementations must not get/read the value of other observables, as they might not have received this event yet! + * The change should be processed lazily or in {@link IObserver.endUpdate}. + * + * @param change Indicates how or why the value changed. + */ + handleChange(observable: IObservableWithChange, change: TChange): void; +} +export interface ISettable { + /** + * Sets the value of the observable. + * Use a transaction to batch multiple changes (with a transaction, observers only react at the end of the transaction). + * + * @param transaction When given, value changes are handled on demand or when the transaction ends. + * @param change Describes how or why the value changed. + */ + set(value: T, transaction: ITransaction | undefined, change: TChange): void; +} +export interface ITransaction { + /** + * Calls {@link Observer.beginUpdate} immediately + * and {@link Observer.endUpdate} when the transaction ends. + */ + updateObserver(observer: IObserver, observable: IObservableWithChange): void; +} +declare let _recomputeInitiallyAndOnChange: typeof recomputeInitiallyAndOnChange; +export declare function _setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange: typeof _recomputeInitiallyAndOnChange): void; +declare let _keepObserved: typeof keepObserved; +export declare function _setKeepObserved(keepObserved: typeof _keepObserved): void; +export declare abstract class ConvenientObservable implements IObservableWithChange { + get TChange(): TChange; + abstract get(): T; + reportChanges(): void; + abstract addObserver(observer: IObserver): void; + abstract removeObserver(observer: IObserver): void; + /** @sealed */ + read(reader: IReader | undefined): T; + /** @sealed */ + map(fn: (value: T, reader: IReader) => TNew): IObservable; + map(owner: DebugOwner, fn: (value: T, reader: IReader) => TNew): IObservable; + log(): IObservableWithChange; + /** + * @sealed + * Converts an observable of an observable value into a direct observable of the value. + */ + flatten(this: IObservable>): IObservable; + recomputeInitiallyAndOnChange(store: DisposableStore, handleValue?: (value: T) => void): IObservable; + /** + * Ensures that this observable is observed. This keeps the cache alive. + * However, in case of deriveds, it does not force eager evaluation (only when the value is read/get). + * Use `recomputeInitiallyAndOnChange` for eager evaluation. + */ + keepObserved(store: DisposableStore): IObservable; + abstract get debugName(): string; + protected get debugValue(): T; +} +export declare abstract class BaseObservable extends ConvenientObservable { + protected readonly observers: Set; + addObserver(observer: IObserver): void; + removeObserver(observer: IObserver): void; + protected onFirstObserverAdded(): void; + protected onLastObserverRemoved(): void; +} +/** + * Starts a transaction in which many observables can be changed at once. + * {@link fn} should start with a JS Doc using `@description` to give the transaction a debug name. + * Reaction run on demand or when the transaction ends. + */ +export declare function transaction(fn: (tx: ITransaction) => void, getDebugName?: () => string): void; +export declare function globalTransaction(fn: (tx: ITransaction) => void): void; +export declare function asyncTransaction(fn: (tx: ITransaction) => Promise, getDebugName?: () => string): Promise; +/** + * Allows to chain transactions. + */ +export declare function subtransaction(tx: ITransaction | undefined, fn: (tx: ITransaction) => void, getDebugName?: () => string): void; +export declare class TransactionImpl implements ITransaction { + readonly _fn: Function; + private readonly _getDebugName?; + private updatingObservers; + constructor(_fn: Function, _getDebugName?: () => string); + getDebugName(): string | undefined; + updateObserver(observer: IObserver, observable: IObservable): void; + finish(): void; +} +/** + * A settable observable. + */ +export interface ISettableObservable extends IObservableWithChange, ISettable { +} +/** + * Creates an observable value. + * Observers get informed when the value changes. + * @template TChange An arbitrary type to describe how or why the value changed. Defaults to `void`. + * Observers will receive every single change value. + */ +export declare function observableValue(name: string, initialValue: T): ISettableObservable; +export declare function observableValue(owner: object, initialValue: T): ISettableObservable; +export declare class ObservableValue extends BaseObservable implements ISettableObservable { + private readonly _debugNameData; + private readonly _equalityComparator; + protected _value: T; + get debugName(): string; + constructor(_debugNameData: DebugNameData, initialValue: T, _equalityComparator: EqualityComparer); + get(): T; + set(value: T, tx: ITransaction | undefined, change: TChange): void; + toString(): string; + protected _setValue(newValue: T): void; +} +/** + * A disposable observable. When disposed, its value is also disposed. + * When a new value is set, the previous value is disposed. + */ +export declare function disposableObservableValue(nameOrOwner: string | object, initialValue: T): ISettableObservable & IDisposable; +export declare class DisposableObservableValue extends ObservableValue implements IDisposable { + protected _setValue(newValue: T): void; + dispose(): void; +} +export interface IChangeTracker { + /** + * Returns if this change should cause an invalidation. + * Implementations can record changes. + */ + handleChange(context: IChangeContext): boolean; +} +export interface IChangeContext { + readonly changedObservable: IObservableWithChange; + readonly change: unknown; + /** + * Returns if the given observable caused the change. + */ + didChange(observable: IObservableWithChange): this is { + change: TChange; + }; +} +export {}; diff --git a/packages/core/dist/observableInternal/base.js b/packages/core/dist/observableInternal/base.js new file mode 100644 index 00000000..2375a393 --- /dev/null +++ b/packages/core/dist/observableInternal/base.js @@ -0,0 +1,278 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { DebugNameData, getFunctionName } from './debugName.js'; +import { strictEquals } from './commonFacade/deps.js'; +import { getLogger, logObservable } from './logging.js'; +let _recomputeInitiallyAndOnChange; +export function _setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange) { + _recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange; +} +let _keepObserved; +export function _setKeepObserved(keepObserved) { + _keepObserved = keepObserved; +} +let _derived; +/** + * @internal + * This is to allow splitting files. +*/ +export function _setDerivedOpts(derived) { + _derived = derived; +} +export class ConvenientObservable { + get TChange() { return null; } + reportChanges() { + this.get(); + } + /** @sealed */ + read(reader) { + if (reader) { + return reader.readObservable(this); + } + else { + return this.get(); + } + } + map(fnOrOwner, fnOrUndefined) { + const owner = fnOrUndefined === undefined ? undefined : fnOrOwner; + const fn = fnOrUndefined === undefined ? fnOrOwner : fnOrUndefined; + return _derived({ + owner, + debugName: () => { + const name = getFunctionName(fn); + if (name !== undefined) { + return name; + } + // regexp to match `x => x.y` or `x => x?.y` where x and y can be arbitrary identifiers (uses backref): + const regexp = /^\s*\(?\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*\)?\s*=>\s*\1(?:\??)\.([a-zA-Z_$][a-zA-Z_$0-9]*)\s*$/; + const match = regexp.exec(fn.toString()); + if (match) { + return `${this.debugName}.${match[2]}`; + } + if (!owner) { + return `${this.debugName} (mapped)`; + } + return undefined; + }, + debugReferenceFn: fn, + }, (reader) => fn(this.read(reader), reader)); + } + log() { + logObservable(this); + return this; + } + /** + * @sealed + * Converts an observable of an observable value into a direct observable of the value. + */ + flatten() { + return _derived({ + owner: undefined, + debugName: () => `${this.debugName} (flattened)`, + }, (reader) => this.read(reader).read(reader)); + } + recomputeInitiallyAndOnChange(store, handleValue) { + store.add(_recomputeInitiallyAndOnChange(this, handleValue)); + return this; + } + /** + * Ensures that this observable is observed. This keeps the cache alive. + * However, in case of deriveds, it does not force eager evaluation (only when the value is read/get). + * Use `recomputeInitiallyAndOnChange` for eager evaluation. + */ + keepObserved(store) { + store.add(_keepObserved(this)); + return this; + } + get debugValue() { + return this.get(); + } +} +export class BaseObservable extends ConvenientObservable { + observers = new Set(); + addObserver(observer) { + const len = this.observers.size; + this.observers.add(observer); + if (len === 0) { + this.onFirstObserverAdded(); + } + } + removeObserver(observer) { + const deleted = this.observers.delete(observer); + if (deleted && this.observers.size === 0) { + this.onLastObserverRemoved(); + } + } + onFirstObserverAdded() { } + onLastObserverRemoved() { } +} +/** + * Starts a transaction in which many observables can be changed at once. + * {@link fn} should start with a JS Doc using `@description` to give the transaction a debug name. + * Reaction run on demand or when the transaction ends. + */ +export function transaction(fn, getDebugName) { + const tx = new TransactionImpl(fn, getDebugName); + try { + fn(tx); + } + finally { + tx.finish(); + } +} +let _globalTransaction = undefined; +export function globalTransaction(fn) { + if (_globalTransaction) { + fn(_globalTransaction); + } + else { + const tx = new TransactionImpl(fn, undefined); + _globalTransaction = tx; + try { + fn(tx); + } + finally { + tx.finish(); // During finish, more actions might be added to the transaction. + // Which is why we only clear the global transaction after finish. + _globalTransaction = undefined; + } + } +} +export async function asyncTransaction(fn, getDebugName) { + const tx = new TransactionImpl(fn, getDebugName); + try { + await fn(tx); + } + finally { + tx.finish(); + } +} +/** + * Allows to chain transactions. + */ +export function subtransaction(tx, fn, getDebugName) { + if (!tx) { + transaction(fn, getDebugName); + } + else { + fn(tx); + } +} +export class TransactionImpl { + _fn; + _getDebugName; + updatingObservers = []; + constructor(_fn, _getDebugName) { + this._fn = _fn; + this._getDebugName = _getDebugName; + getLogger()?.handleBeginTransaction(this); + } + getDebugName() { + if (this._getDebugName) { + return this._getDebugName(); + } + return getFunctionName(this._fn); + } + updateObserver(observer, observable) { + // When this gets called while finish is active, they will still get considered + this.updatingObservers.push({ observer, observable }); + observer.beginUpdate(observable); + } + finish() { + const updatingObservers = this.updatingObservers; + for (let i = 0; i < updatingObservers.length; i++) { + const { observer, observable } = updatingObservers[i]; + observer.endUpdate(observable); + } + // Prevent anyone from updating observers from now on. + this.updatingObservers = null; + getLogger()?.handleEndTransaction(); + } +} +export function observableValue(nameOrOwner, initialValue) { + let debugNameData; + if (typeof nameOrOwner === 'string') { + debugNameData = new DebugNameData(undefined, nameOrOwner, undefined); + } + else { + debugNameData = new DebugNameData(nameOrOwner, undefined, undefined); + } + return new ObservableValue(debugNameData, initialValue, strictEquals); +} +export class ObservableValue extends BaseObservable { + _debugNameData; + _equalityComparator; + _value; + get debugName() { + return this._debugNameData.getDebugName(this) ?? 'ObservableValue'; + } + constructor(_debugNameData, initialValue, _equalityComparator) { + super(); + this._debugNameData = _debugNameData; + this._equalityComparator = _equalityComparator; + this._value = initialValue; + } + get() { + return this._value; + } + set(value, tx, change) { + if (change === undefined && this._equalityComparator(this._value, value)) { + return; + } + let _tx; + if (!tx) { + tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`); + } + try { + const oldValue = this._value; + this._setValue(value); + getLogger()?.handleObservableChanged(this, { oldValue, newValue: value, change, didChange: true, hadValue: true }); + for (const observer of this.observers) { + tx.updateObserver(observer, this); + observer.handleChange(this, change); + } + } + finally { + if (_tx) { + _tx.finish(); + } + } + } + toString() { + return `${this.debugName}: ${this._value}`; + } + _setValue(newValue) { + this._value = newValue; + } +} +/** + * A disposable observable. When disposed, its value is also disposed. + * When a new value is set, the previous value is disposed. + */ +export function disposableObservableValue(nameOrOwner, initialValue) { + let debugNameData; + if (typeof nameOrOwner === 'string') { + debugNameData = new DebugNameData(undefined, nameOrOwner, undefined); + } + else { + debugNameData = new DebugNameData(nameOrOwner, undefined, undefined); + } + return new DisposableObservableValue(debugNameData, initialValue, strictEquals); +} +export class DisposableObservableValue extends ObservableValue { + _setValue(newValue) { + if (this._value === newValue) { + return; + } + if (this._value) { + this._value.dispose(); + } + this._value = newValue; + } + dispose() { + this._value?.dispose(); + } +} +//# sourceMappingURL=base.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/base.js.map b/packages/core/dist/observableInternal/base.js.map new file mode 100644 index 00000000..5cbd8505 --- /dev/null +++ b/packages/core/dist/observableInternal/base.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base.js","sourceRoot":"","sources":["../../src/observableInternal/base.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,aAAa,EAAc,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC5E,OAAO,EAAkD,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEtG,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAsKxD,IAAI,8BAAoE,CAAC;AACzE,MAAM,UAAU,iCAAiC,CAAC,6BAAoE;IACrH,8BAA8B,GAAG,6BAA6B,CAAC;AAChE,CAAC;AAED,IAAI,aAAkC,CAAC;AACvC,MAAM,UAAU,gBAAgB,CAAC,YAAkC;IAClE,aAAa,GAAG,YAAY,CAAC;AAC9B,CAAC;AAGD,IAAI,QAA4B,CAAC;AACjC;;;EAGE;AACF,MAAM,UAAU,eAAe,CAAC,OAAwB;IACvD,QAAQ,GAAG,OAAO,CAAC;AACpB,CAAC;AAED,MAAM,OAAgB,oBAAoB;IACzC,IAAI,OAAO,KAAc,OAAO,IAAK,CAAC,CAAC,CAAC;IAIjC,aAAa;QACnB,IAAI,CAAC,GAAG,EAAE,CAAC;IACZ,CAAC;IAKD,cAAc;IACP,IAAI,CAAC,MAA2B;QACtC,IAAI,MAAM,EAAE;YACX,OAAO,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;SACnC;aAAM;YACN,OAAO,IAAI,CAAC,GAAG,EAAE,CAAC;SAClB;IACF,CAAC;IAKM,GAAG,CAAO,SAA6D,EAAE,aAAmD;QAClI,MAAM,KAAK,GAAG,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAuB,CAAC;QAChF,MAAM,EAAE,GAAG,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,SAAgD,CAAC,CAAC,CAAC,aAAa,CAAC;QAE1G,OAA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GAGG;AACH,MAAM,UAAU,yBAAyB,CAAoD,WAA4B,EAAE,YAAe;IACzI,IAAI,aAA4B,CAAC;IACjC,IAAI,OAAO,WAAW,KAAK,QAAQ,EAAE;QACpC,aAAa,GAAG,IAAI,aAAa,CAAC,SAAS,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;KACrE;SAAM;QACN,aAAa,GAAG,IAAI,aAAa,CAAC,WAAW,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;KACrE;IACD,OAAO,IAAI,yBAAyB,CAAC,aAAa,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;AACjF,CAAC;AAED,MAAM,OAAO,yBAA6E,SAAQ,eAA2B;IACzG,SAAS,CAAC,QAAW;QACvC,IAAI,IAAI,CAAC,MAAM,KAAK,QAAQ,EAAE;YAC7B,OAAO;SACP;QACD,IAAI,IAAI,CAAC,MAAM,EAAE;YAChB,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;SACtB;QACD,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC;IACxB,CAAC;IAEM,OAAO;QACb,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;IACxB,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/commonFacade/cancellation.d.ts b/packages/core/dist/observableInternal/commonFacade/cancellation.d.ts new file mode 100644 index 00000000..b3399641 --- /dev/null +++ b/packages/core/dist/observableInternal/commonFacade/cancellation.d.ts @@ -0,0 +1,2 @@ +export { CancellationError } from '../../errors.js'; +export { CancellationToken, CancellationTokenSource } from '../../cancellation.js'; diff --git a/packages/core/dist/observableInternal/commonFacade/cancellation.js b/packages/core/dist/observableInternal/commonFacade/cancellation.js new file mode 100644 index 00000000..2a932907 --- /dev/null +++ b/packages/core/dist/observableInternal/commonFacade/cancellation.js @@ -0,0 +1,7 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +export { CancellationError } from '../../errors.js'; +export { CancellationToken, CancellationTokenSource } from '../../cancellation.js'; +//# sourceMappingURL=cancellation.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/commonFacade/cancellation.js.map b/packages/core/dist/observableInternal/commonFacade/cancellation.js.map new file mode 100644 index 00000000..f912432c --- /dev/null +++ b/packages/core/dist/observableInternal/commonFacade/cancellation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cancellation.js","sourceRoot":"","sources":["../../../src/observableInternal/commonFacade/cancellation.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/commonFacade/deps.d.ts b/packages/core/dist/observableInternal/commonFacade/deps.d.ts new file mode 100644 index 00000000..ab9f92ed --- /dev/null +++ b/packages/core/dist/observableInternal/commonFacade/deps.d.ts @@ -0,0 +1,5 @@ +export { assertFn } from '../../assert.js'; +export { type EqualityComparer, strictEquals } from '../../equals.js'; +export { BugIndicatingError, onBugIndicatingError } from '../../errors.js'; +export { Event, type IValueWithChangeEvent } from '../../event.js'; +export { DisposableStore, type IDisposable, markAsDisposed, toDisposable, trackDisposable } from '../../lifecycle.js'; diff --git a/packages/core/dist/observableInternal/commonFacade/deps.js b/packages/core/dist/observableInternal/commonFacade/deps.js new file mode 100644 index 00000000..806310a5 --- /dev/null +++ b/packages/core/dist/observableInternal/commonFacade/deps.js @@ -0,0 +1,10 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +export { assertFn } from '../../assert.js'; +export { strictEquals } from '../../equals.js'; +export { BugIndicatingError, onBugIndicatingError } from '../../errors.js'; +export { Event } from '../../event.js'; +export { DisposableStore, markAsDisposed, toDisposable, trackDisposable } from '../../lifecycle.js'; +//# sourceMappingURL=deps.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/commonFacade/deps.js.map b/packages/core/dist/observableInternal/commonFacade/deps.js.map new file mode 100644 index 00000000..105b608a --- /dev/null +++ b/packages/core/dist/observableInternal/commonFacade/deps.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deps.js","sourceRoot":"","sources":["../../../src/observableInternal/commonFacade/deps.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAyB,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EAAE,KAAK,EAA8B,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAAE,eAAe,EAAoB,cAAc,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/debugName.d.ts b/packages/core/dist/observableInternal/debugName.d.ts new file mode 100644 index 00000000..e90a1d83 --- /dev/null +++ b/packages/core/dist/observableInternal/debugName.d.ts @@ -0,0 +1,32 @@ +export interface IDebugNameData { + /** + * The owner object of an observable. + * Used for debugging only, such as computing a name for the observable by iterating over the fields of the owner. + */ + readonly owner?: DebugOwner | undefined; + /** + * A string or function that returns a string that represents the name of the observable. + * Used for debugging only. + */ + readonly debugName?: DebugNameSource | undefined; + /** + * A function that points to the defining function of the object. + * Used for debugging only. + */ + readonly debugReferenceFn?: Function | undefined; +} +export declare class DebugNameData { + readonly owner: DebugOwner | undefined; + readonly debugNameSource: DebugNameSource | undefined; + readonly referenceFn: Function | undefined; + constructor(owner: DebugOwner | undefined, debugNameSource: DebugNameSource | undefined, referenceFn: Function | undefined); + getDebugName(target: object): string | undefined; +} +/** + * The owning object of an observable. + * Is only used for debugging purposes, such as computing a name for the observable by iterating over the fields of the owner. + */ +export type DebugOwner = object | undefined; +export type DebugNameSource = string | (() => string | undefined); +export declare function getDebugName(target: object, data: DebugNameData): string | undefined; +export declare function getFunctionName(fn: Function): string | undefined; diff --git a/packages/core/dist/observableInternal/debugName.js b/packages/core/dist/observableInternal/debugName.js new file mode 100644 index 00000000..982fe91f --- /dev/null +++ b/packages/core/dist/observableInternal/debugName.js @@ -0,0 +1,108 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +export class DebugNameData { + owner; + debugNameSource; + referenceFn; + constructor(owner, debugNameSource, referenceFn) { + this.owner = owner; + this.debugNameSource = debugNameSource; + this.referenceFn = referenceFn; + } + getDebugName(target) { + return getDebugName(target, this); + } +} +const countPerName = new Map(); +const cachedDebugName = new WeakMap(); +export function getDebugName(target, data) { + const cached = cachedDebugName.get(target); + if (cached) { + return cached; + } + const dbgName = computeDebugName(target, data); + if (dbgName) { + let count = countPerName.get(dbgName) ?? 0; + count++; + countPerName.set(dbgName, count); + const result = count === 1 ? dbgName : `${dbgName}#${count}`; + cachedDebugName.set(target, result); + return result; + } + return undefined; +} +function computeDebugName(self, data) { + const cached = cachedDebugName.get(self); + if (cached) { + return cached; + } + const ownerStr = data.owner ? formatOwner(data.owner) + `.` : ''; + let result; + const debugNameSource = data.debugNameSource; + if (debugNameSource !== undefined) { + if (typeof debugNameSource === 'function') { + result = debugNameSource(); + if (result !== undefined) { + return ownerStr + result; + } + } + else { + return ownerStr + debugNameSource; + } + } + const referenceFn = data.referenceFn; + if (referenceFn !== undefined) { + result = getFunctionName(referenceFn); + if (result !== undefined) { + return ownerStr + result; + } + } + if (data.owner !== undefined) { + const key = findKey(data.owner, self); + if (key !== undefined) { + return ownerStr + key; + } + } + return undefined; +} +function findKey(obj, value) { + for (const key in obj) { + if (obj[key] === value) { + return key; + } + } + return undefined; +} +const countPerClassName = new Map(); +const ownerId = new WeakMap(); +function formatOwner(owner) { + const id = ownerId.get(owner); + if (id) { + return id; + } + const className = getClassName(owner); + let count = countPerClassName.get(className) ?? 0; + count++; + countPerClassName.set(className, count); + const result = count === 1 ? className : `${className}#${count}`; + ownerId.set(owner, result); + return result; +} +function getClassName(obj) { + const ctor = obj.constructor; + if (ctor) { + return ctor.name; + } + return 'Object'; +} +export function getFunctionName(fn) { + const fnSrc = fn.toString(); + // Pattern: /** @description ... */ + const regexp = /\/\*\*\s*@description\s*([^*]*)\*\//; + const match = regexp.exec(fnSrc); + const result = match ? match[1] : undefined; + return result?.trim(); +} +//# sourceMappingURL=debugName.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/debugName.js.map b/packages/core/dist/observableInternal/debugName.js.map new file mode 100644 index 00000000..df91dead --- /dev/null +++ b/packages/core/dist/observableInternal/debugName.js.map @@ -0,0 +1 @@ +{"version":3,"file":"debugName.js","sourceRoot":"","sources":["../../src/observableInternal/debugName.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAsBhG,MAAM,OAAO,aAAa;IAER;IACA;IACA;IAHjB,YACiB,KAA6B,EAC7B,eAA4C,EAC5C,WAAiC;QAFjC,UAAK,GAAL,KAAK,CAAwB;QAC7B,oBAAe,GAAf,eAAe,CAA6B;QAC5C,gBAAW,GAAX,WAAW,CAAsB;IAC9C,CAAC;IAEE,YAAY,CAAC,MAAc;QACjC,OAAO,YAAY,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACnC,CAAC;CACD;AASD,MAAM,YAAY,GAAG,IAAI,GAAG,EAAkB,CAAC;AAC/C,MAAM,eAAe,GAAG,IAAI,OAAO,EAAkB,CAAC;AAEtD,MAAM,UAAU,YAAY,CAAC,MAAc,EAAE,IAAmB;IAC/D,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC3C,IAAI,MAAM,EAAE;QACX,OAAO,MAAM,CAAC;KAC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AAO,MAAM,CAAC;AACf,CAAC;AAED,SAAS,YAAY,CAAC,GAAW;IAChC,MAAM,IAAI,GAAG,GAAG,CAAC,WAAW,CAAC;IAC7B,IAAI,IAAI,EAAE;QACT,OAAO,IAAI,CAAC,IAAI,CAAC;KACjB;IACD,OAAO,QAAQ,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,EAAY;IAC3C,MAAM,KAAK,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC;IAC5B,mCAAmC;IACnC,MAAM,MAAM,GAAG,qCAAqC,CAAC;IACrD,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC5C,OAAO,MAAM,EAAE,IAAI,EAAE,CAAC;AACvB,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/derived.d.ts b/packages/core/dist/observableInternal/derived.d.ts new file mode 100644 index 00000000..d77f9b3d --- /dev/null +++ b/packages/core/dist/observableInternal/derived.d.ts @@ -0,0 +1,74 @@ +import { BaseObservable, IChangeContext, IObservable, IObservableWithChange, IObserver, IReader, ISettableObservable, ITransaction } from './base.js'; +import { DebugNameData, DebugOwner, IDebugNameData } from './debugName.js'; +import { DisposableStore, EqualityComparer, IDisposable } from './commonFacade/deps.js'; +/** + * Creates an observable that is derived from other observables. + * The value is only recomputed when absolutely needed. + * + * {@link computeFn} should start with a JS Doc using `@description` to name the derived. + */ +export declare function derived(computeFn: (reader: IReader) => T): IObservable; +export declare function derived(owner: DebugOwner, computeFn: (reader: IReader) => T): IObservable; +export declare function derivedWithSetter(owner: DebugOwner | undefined, computeFn: (reader: IReader) => T, setter: (value: T, transaction: ITransaction | undefined) => void): ISettableObservable; +export declare function derivedOpts(options: IDebugNameData & { + equalsFn?: EqualityComparer; + onLastObserverRemoved?: (() => void); +}, computeFn: (reader: IReader) => T): IObservable; +/** + * Represents an observable that is derived from other observables. + * The value is only recomputed when absolutely needed. + * + * {@link computeFn} should start with a JS Doc using `@description` to name the derived. + * + * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes. + * Use `handleChange` to add a reported change to the change summary. + * The compute function is given the last change summary. + * The change summary is discarded after the compute function was called. + * + * @see derived + */ +export declare function derivedHandleChanges(options: IDebugNameData & { + createEmptyChangeSummary: () => TChangeSummary; + handleChange: (context: IChangeContext, changeSummary: TChangeSummary) => boolean; + equalityComparer?: EqualityComparer; +}, computeFn: (reader: IReader, changeSummary: TChangeSummary) => T): IObservable; +export declare function derivedWithStore(computeFn: (reader: IReader, store: DisposableStore) => T): IObservable; +export declare function derivedWithStore(owner: object, computeFn: (reader: IReader, store: DisposableStore) => T): IObservable; +export declare function derivedDisposable(computeFn: (reader: IReader) => T): IObservable; +export declare function derivedDisposable(owner: DebugOwner, computeFn: (reader: IReader) => T): IObservable; +export declare class Derived extends BaseObservable implements IReader, IObserver { + readonly _debugNameData: DebugNameData; + readonly _computeFn: (reader: IReader, changeSummary: TChangeSummary) => T; + private readonly createChangeSummary; + private readonly _handleChange; + private readonly _handleLastObserverRemoved; + private readonly _equalityComparator; + private state; + private value; + private updateCount; + private dependencies; + private dependenciesToBeRemoved; + private changeSummary; + private _isUpdating; + private _isComputing; + get debugName(): string; + constructor(_debugNameData: DebugNameData, _computeFn: (reader: IReader, changeSummary: TChangeSummary) => T, createChangeSummary: (() => TChangeSummary) | undefined, _handleChange: ((context: IChangeContext, summary: TChangeSummary) => boolean) | undefined, _handleLastObserverRemoved: (() => void) | undefined, _equalityComparator: EqualityComparer); + protected onLastObserverRemoved(): void; + get(): T; + private _recomputeIfNeeded; + toString(): string; + beginUpdate(_observable: IObservable): void; + private _removedObserverToCallEndUpdateOn; + endUpdate(_observable: IObservable): void; + handlePossibleChange(observable: IObservable): void; + handleChange(observable: IObservableWithChange, change: TChange): void; + private _isReaderValid; + readObservable(observable: IObservable): T; + addObserver(observer: IObserver): void; + removeObserver(observer: IObserver): void; + log(): IObservableWithChange; +} +export declare class DerivedWithSetter extends Derived implements ISettableObservable { + readonly set: (value: T, tx: ITransaction | undefined) => void; + constructor(debugNameData: DebugNameData, computeFn: (reader: IReader, changeSummary: TChangeSummary) => T, createChangeSummary: (() => TChangeSummary) | undefined, handleChange: ((context: IChangeContext, summary: TChangeSummary) => boolean) | undefined, handleLastObserverRemoved: (() => void) | undefined, equalityComparator: EqualityComparer, set: (value: T, tx: ITransaction | undefined) => void); +} diff --git a/packages/core/dist/observableInternal/derived.js b/packages/core/dist/observableInternal/derived.js new file mode 100644 index 00000000..e30bba08 --- /dev/null +++ b/packages/core/dist/observableInternal/derived.js @@ -0,0 +1,377 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { BaseObservable, _setDerivedOpts, } from './base.js'; +import { DebugNameData } from './debugName.js'; +import { BugIndicatingError, DisposableStore, assertFn, onBugIndicatingError, strictEquals } from './commonFacade/deps.js'; +import { getLogger } from './logging.js'; +export function derived(computeFnOrOwner, computeFn) { + if (computeFn !== undefined) { + return new Derived(new DebugNameData(computeFnOrOwner, undefined, computeFn), computeFn, undefined, undefined, undefined, strictEquals); + } + return new Derived(new DebugNameData(undefined, undefined, computeFnOrOwner), computeFnOrOwner, undefined, undefined, undefined, strictEquals); +} +export function derivedWithSetter(owner, computeFn, setter) { + return new DerivedWithSetter(new DebugNameData(owner, undefined, computeFn), computeFn, undefined, undefined, undefined, strictEquals, setter); +} +export function derivedOpts(options, computeFn) { + return new Derived(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn), computeFn, undefined, undefined, options.onLastObserverRemoved, options.equalsFn ?? strictEquals); +} +_setDerivedOpts(derivedOpts); +/** + * Represents an observable that is derived from other observables. + * The value is only recomputed when absolutely needed. + * + * {@link computeFn} should start with a JS Doc using `@description` to name the derived. + * + * Use `createEmptyChangeSummary` to create a "change summary" that can collect the changes. + * Use `handleChange` to add a reported change to the change summary. + * The compute function is given the last change summary. + * The change summary is discarded after the compute function was called. + * + * @see derived + */ +export function derivedHandleChanges(options, computeFn) { + return new Derived(new DebugNameData(options.owner, options.debugName, undefined), computeFn, options.createEmptyChangeSummary, options.handleChange, undefined, options.equalityComparer ?? strictEquals); +} +export function derivedWithStore(computeFnOrOwner, computeFnOrUndefined) { + let computeFn; + let owner; + if (computeFnOrUndefined === undefined) { + computeFn = computeFnOrOwner; + owner = undefined; + } + else { + owner = computeFnOrOwner; + computeFn = computeFnOrUndefined; + } + const store = new DisposableStore(); + return new Derived(new DebugNameData(owner, undefined, computeFn), r => { + store.clear(); + return computeFn(r, store); + }, undefined, undefined, () => store.dispose(), strictEquals); +} +export function derivedDisposable(computeFnOrOwner, computeFnOrUndefined) { + let computeFn; + let owner; + if (computeFnOrUndefined === undefined) { + computeFn = computeFnOrOwner; + owner = undefined; + } + else { + owner = computeFnOrOwner; + computeFn = computeFnOrUndefined; + } + let store = undefined; + return new Derived(new DebugNameData(owner, undefined, computeFn), r => { + if (!store) { + store = new DisposableStore(); + } + else { + store.clear(); + } + const result = computeFn(r); + if (result) { + store.add(result); + } + return result; + }, undefined, undefined, () => { + if (store) { + store.dispose(); + store = undefined; + } + }, strictEquals); +} +var DerivedState; +(function (DerivedState) { + /** Initial state, no previous value, recomputation needed */ + DerivedState[DerivedState["initial"] = 0] = "initial"; + /** + * A dependency could have changed. + * We need to explicitly ask them if at least one dependency changed. + */ + DerivedState[DerivedState["dependenciesMightHaveChanged"] = 1] = "dependenciesMightHaveChanged"; + /** + * A dependency changed and we need to recompute. + * After recomputation, we need to check the previous value to see if we changed as well. + */ + DerivedState[DerivedState["stale"] = 2] = "stale"; + /** + * No change reported, our cached value is up to date. + */ + DerivedState[DerivedState["upToDate"] = 3] = "upToDate"; +})(DerivedState || (DerivedState = {})); +export class Derived extends BaseObservable { + _debugNameData; + _computeFn; + createChangeSummary; + _handleChange; + _handleLastObserverRemoved; + _equalityComparator; + state = 0 /* DerivedState.initial */; + value = undefined; + updateCount = 0; + dependencies = new Set(); + dependenciesToBeRemoved = new Set(); + changeSummary = undefined; + _isUpdating = false; + _isComputing = false; + get debugName() { + return this._debugNameData.getDebugName(this) ?? '(anonymous)'; + } + constructor(_debugNameData, _computeFn, createChangeSummary, _handleChange, _handleLastObserverRemoved = undefined, _equalityComparator) { + super(); + this._debugNameData = _debugNameData; + this._computeFn = _computeFn; + this.createChangeSummary = createChangeSummary; + this._handleChange = _handleChange; + this._handleLastObserverRemoved = _handleLastObserverRemoved; + this._equalityComparator = _equalityComparator; + this.changeSummary = this.createChangeSummary?.(); + getLogger()?.handleDerivedCreated(this); + } + onLastObserverRemoved() { + /** + * We are not tracking changes anymore, thus we have to assume + * that our cache is invalid. + */ + this.state = 0 /* DerivedState.initial */; + this.value = undefined; + getLogger()?.handleDerivedCleared(this); + for (const d of this.dependencies) { + d.removeObserver(this); + } + this.dependencies.clear(); + this._handleLastObserverRemoved?.(); + } + get() { + if (this._isComputing) { + throw new BugIndicatingError('Cyclic deriveds are not supported yet!'); + } + if (this.observers.size === 0) { + let result; + // Without observers, we don't know when to clean up stuff. + // Thus, we don't cache anything to prevent memory leaks. + try { + this._isReaderValid = true; + result = this._computeFn(this, this.createChangeSummary?.()); + } + finally { + this._isReaderValid = false; + } + // Clear new dependencies + this.onLastObserverRemoved(); + return result; + } + else { + do { + // We might not get a notification for a dependency that changed while it is updating, + // thus we also have to ask all our depedencies if they changed in this case. + if (this.state === 1 /* DerivedState.dependenciesMightHaveChanged */) { + for (const d of this.dependencies) { + /** might call {@link handleChange} indirectly, which could make us stale */ + d.reportChanges(); + if (this.state === 2 /* DerivedState.stale */) { + // The other dependencies will refresh on demand, so early break + break; + } + } + } + // We called report changes of all dependencies. + // If we are still not stale, we can assume to be up to date again. + if (this.state === 1 /* DerivedState.dependenciesMightHaveChanged */) { + this.state = 3 /* DerivedState.upToDate */; + } + this._recomputeIfNeeded(); + // In case recomputation changed one of our dependencies, we need to recompute again. + } while (this.state !== 3 /* DerivedState.upToDate */); + return this.value; + } + } + _recomputeIfNeeded() { + if (this.state === 3 /* DerivedState.upToDate */) { + return; + } + const emptySet = this.dependenciesToBeRemoved; + this.dependenciesToBeRemoved = this.dependencies; + this.dependencies = emptySet; + const hadValue = this.state !== 0 /* DerivedState.initial */; + const oldValue = this.value; + this.state = 3 /* DerivedState.upToDate */; + let didChange = false; + this._isComputing = false; // TODO@hediet: Set to true and investigate diff editor scrolling issues! (also see test.skip('catches cyclic dependencies') + try { + const changeSummary = this.changeSummary; + this.changeSummary = this.createChangeSummary?.(); + try { + this._isReaderValid = true; + /** might call {@link handleChange} indirectly, which could invalidate us */ + this.value = this._computeFn(this, changeSummary); + } + finally { + this._isReaderValid = false; + // We don't want our observed observables to think that they are (not even temporarily) not being observed. + // Thus, we only unsubscribe from observables that are definitely not read anymore. + for (const o of this.dependenciesToBeRemoved) { + o.removeObserver(this); + } + this.dependenciesToBeRemoved.clear(); + } + didChange = hadValue && !(this._equalityComparator(oldValue, this.value)); + getLogger()?.handleDerivedRecomputed(this, { + oldValue, + newValue: this.value, + change: undefined, + didChange, + hadValue, + }); + } + catch (e) { + onBugIndicatingError(e); + } + this._isComputing = false; + if (didChange) { + for (const r of this.observers) { + r.handleChange(this, undefined); + } + } + } + toString() { + return `LazyDerived<${this.debugName}>`; + } + // IObserver Implementation + beginUpdate(_observable) { + if (this._isUpdating) { + throw new BugIndicatingError('Cyclic deriveds are not supported yet!'); + } + this.updateCount++; + this._isUpdating = true; + try { + const propagateBeginUpdate = this.updateCount === 1; + if (this.state === 3 /* DerivedState.upToDate */) { + this.state = 1 /* DerivedState.dependenciesMightHaveChanged */; + // If we propagate begin update, that will already signal a possible change. + if (!propagateBeginUpdate) { + for (const r of this.observers) { + r.handlePossibleChange(this); + } + } + } + if (propagateBeginUpdate) { + for (const r of this.observers) { + r.beginUpdate(this); // This signals a possible change + } + } + } + finally { + this._isUpdating = false; + } + } + _removedObserverToCallEndUpdateOn = null; + endUpdate(_observable) { + this.updateCount--; + if (this.updateCount === 0) { + // End update could change the observer list. + const observers = [...this.observers]; + for (const r of observers) { + r.endUpdate(this); + } + if (this._removedObserverToCallEndUpdateOn) { + const observers = [...this._removedObserverToCallEndUpdateOn]; + this._removedObserverToCallEndUpdateOn = null; + for (const r of observers) { + r.endUpdate(this); + } + } + } + assertFn(() => this.updateCount >= 0); + } + handlePossibleChange(observable) { + // In all other states, observers already know that we might have changed. + if (this.state === 3 /* DerivedState.upToDate */ && this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) { + this.state = 1 /* DerivedState.dependenciesMightHaveChanged */; + for (const r of this.observers) { + r.handlePossibleChange(this); + } + } + } + handleChange(observable, change) { + if (this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) { + let shouldReact = false; + try { + shouldReact = this._handleChange ? this._handleChange({ + changedObservable: observable, + change, + didChange: (o) => o === observable, + }, this.changeSummary) : true; + } + catch (e) { + onBugIndicatingError(e); + } + const wasUpToDate = this.state === 3 /* DerivedState.upToDate */; + if (shouldReact && (this.state === 1 /* DerivedState.dependenciesMightHaveChanged */ || wasUpToDate)) { + this.state = 2 /* DerivedState.stale */; + if (wasUpToDate) { + for (const r of this.observers) { + r.handlePossibleChange(this); + } + } + } + } + } + // IReader Implementation + _isReaderValid = false; + readObservable(observable) { + if (!this._isReaderValid) { + throw new BugIndicatingError('The reader object cannot be used outside its compute function!'); + } + // Subscribe before getting the value to enable caching + observable.addObserver(this); + /** This might call {@link handleChange} indirectly, which could invalidate us */ + const value = observable.get(); + // Which is why we only add the observable to the dependencies now. + this.dependencies.add(observable); + this.dependenciesToBeRemoved.delete(observable); + return value; + } + addObserver(observer) { + const shouldCallBeginUpdate = !this.observers.has(observer) && this.updateCount > 0; + super.addObserver(observer); + if (shouldCallBeginUpdate) { + if (this._removedObserverToCallEndUpdateOn && this._removedObserverToCallEndUpdateOn.has(observer)) { + this._removedObserverToCallEndUpdateOn.delete(observer); + } + else { + observer.beginUpdate(this); + } + } + } + removeObserver(observer) { + if (this.observers.has(observer) && this.updateCount > 0) { + if (!this._removedObserverToCallEndUpdateOn) { + this._removedObserverToCallEndUpdateOn = new Set(); + } + this._removedObserverToCallEndUpdateOn.add(observer); + } + super.removeObserver(observer); + } + log() { + if (!getLogger()) { + super.log(); + getLogger()?.handleDerivedCreated(this); + } + else { + super.log(); + } + return this; + } +} +export class DerivedWithSetter extends Derived { + set; + constructor(debugNameData, computeFn, createChangeSummary, handleChange, handleLastObserverRemoved = undefined, equalityComparator, set) { + super(debugNameData, computeFn, createChangeSummary, handleChange, handleLastObserverRemoved, equalityComparator); + this.set = set; + } +} +//# sourceMappingURL=derived.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/derived.js.map b/packages/core/dist/observableInternal/derived.js.map new file mode 100644 index 00000000..7191a3a8 --- /dev/null +++ b/packages/core/dist/observableInternal/derived.js.map @@ -0,0 +1 @@ +{"version":3,"file":"derived.js","sourceRoot":"","sources":["../../src/observableInternal/derived.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,cAAc,EAA6G,eAAe,GAAG,MAAM,WAAW,CAAC;AACxK,OAAO,EAAE,aAAa,EAA8B,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAiC,QAAQ,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAC1J,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAUzC,MAAM,UAAU,OAAO,CAAI,gBAAuD,EAAE,SAAgD;IACnI,IAAI,SAAS,KAAK,SAAS,EAAE;QAC5B,OAAO,IAAI,OAAO,CACjB,IAAI,aAAa,CAAC,gBAAgB,EAAE,SAAS,EAAE,SAAS,CAAC,EACzD,SAAS,EACT,SAAS,EACT,SAAS,EACT,SAAS,EACT,YAAY,CACZ,CAAC;KACF;IACD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CAAC,GAAG,EAAE,CAAC;SACZ;QACD,OAAO,IAAI,CAAC;IACb,CAAC;CACD;AAGD,MAAM,OAAO,iBAA2C,SAAQ,OAA0B;IAQxE;IAPjB,YACC,aAA4B,EAC5B,SAAgE,EAChE,mBAAuD,EACvD,YAAyF,EACzF,4BAAsD,SAAS,EAC/D,kBAAuC,EACvB,GAAqD;QAErE,KAAK,CACJ,aAAa,EACb,SAAS,EACT,mBAAmB,EACnB,YAAY,EACZ,yBAAyB,EACzB,kBAAkB,CAClB,CAAC;QATc,QAAG,GAAH,GAAG,CAAkD;IAUtE,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/index.d.ts b/packages/core/dist/observableInternal/index.d.ts new file mode 100644 index 00000000..91413bd0 --- /dev/null +++ b/packages/core/dist/observableInternal/index.d.ts @@ -0,0 +1,8 @@ +export { observableValueOpts } from './api.js'; +export { autorun, autorunDelta, autorunHandleChanges, autorunOpts, autorunWithStore, autorunWithStoreHandleChanges } from './autorun.js'; +export { asyncTransaction, disposableObservableValue, globalTransaction, observableValue, subtransaction, transaction, TransactionImpl, type IChangeContext, type IChangeTracker, type IObservable, type IObservableWithChange, type IObserver, type IReader, type ISettable, type ISettableObservable, type ITransaction, } from './base.js'; +export { derived, derivedDisposable, derivedHandleChanges, derivedOpts, derivedWithSetter, derivedWithStore } from './derived.js'; +export { ObservableLazy, ObservableLazyPromise, ObservablePromise, PromiseResult, } from './promise.js'; +export { derivedWithCancellationToken, waitForState } from './utilsCancellation.js'; +export { constObservable, debouncedObservable, derivedConstOnceDefined, derivedObservableWithCache, derivedObservableWithWritableCache, keepObserved, latestChangedValue, mapObservableArrayCached, observableFromEvent, observableFromEventOpts, observableFromPromise, observableFromValueWithChangeEvent, observableSignal, observableSignalFromEvent, recomputeInitiallyAndOnChange, runOnChange, runOnChangeWithStore, signalFromObservable, ValueWithChangeEventFromObservable, wasEventTriggeredRecently, type IObservableSignal, } from './utils.js'; +export { type DebugOwner } from './debugName.js'; diff --git a/packages/core/dist/observableInternal/index.js b/packages/core/dist/observableInternal/index.js new file mode 100644 index 00000000..83c22b82 --- /dev/null +++ b/packages/core/dist/observableInternal/index.js @@ -0,0 +1,19 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +// This is a facade for the observable implementation. Only import from here! +export { observableValueOpts } from './api.js'; +export { autorun, autorunDelta, autorunHandleChanges, autorunOpts, autorunWithStore, autorunWithStoreHandleChanges } from './autorun.js'; +export { asyncTransaction, disposableObservableValue, globalTransaction, observableValue, subtransaction, transaction, TransactionImpl, } from './base.js'; +export { derived, derivedDisposable, derivedHandleChanges, derivedOpts, derivedWithSetter, derivedWithStore } from './derived.js'; +export { ObservableLazy, ObservableLazyPromise, ObservablePromise, PromiseResult, } from './promise.js'; +export { derivedWithCancellationToken, waitForState } from './utilsCancellation.js'; +export { constObservable, debouncedObservable, derivedConstOnceDefined, derivedObservableWithCache, derivedObservableWithWritableCache, keepObserved, latestChangedValue, mapObservableArrayCached, observableFromEvent, observableFromEventOpts, observableFromPromise, observableFromValueWithChangeEvent, observableSignal, observableSignalFromEvent, recomputeInitiallyAndOnChange, runOnChange, runOnChangeWithStore, signalFromObservable, ValueWithChangeEventFromObservable, wasEventTriggeredRecently, } from './utils.js'; +import { ConsoleObservableLogger, setLogger } from './logging.js'; +// Remove "//" in the next line to enable logging +const enableLogging = false; +if (enableLogging) { + setLogger(new ConsoleObservableLogger()); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/index.js.map b/packages/core/dist/observableInternal/index.js.map new file mode 100644 index 00000000..887b379a --- /dev/null +++ b/packages/core/dist/observableInternal/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/observableInternal/index.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,6EAA6E;AAE7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAC/C,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,WAAW,EAAE,gBAAgB,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AACzI,OAAO,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,iBAAiB,EAAE,eAAe,EAAE,cAAc,EAAE,WAAW,EAAE,eAAe,GAAsL,MAAM,WAAW,CAAC;AAC9U,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,WAAW,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAClI,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,aAAa,GAAG,MAAM,cAAc,CAAC;AACxG,OAAO,EAAE,4BAA4B,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACpF,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,0BAA0B,EAAE,kCAAkC,EAAE,YAAY,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,kCAAkC,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,6BAA6B,EAAE,WAAW,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,kCAAkC,EAAE,yBAAyB,GAA2B,MAAM,YAAY,CAAC;AAG7hB,OAAO,EACN,uBAAuB,EACvB,SAAS,EACT,MAAM,cAAc,CAAC;AAEtB,iDAAiD;AACjD,MAAM,aAAa,GAAG,KAAK,CAEzB;AAEF,IAAI,aAAa,EAAE;IAClB,SAAS,CAAC,IAAI,uBAAuB,EAAE,CAAC,CAAC;CACzC"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/lazyObservableValue.d.ts b/packages/core/dist/observableInternal/lazyObservableValue.d.ts new file mode 100644 index 00000000..830f713c --- /dev/null +++ b/packages/core/dist/observableInternal/lazyObservableValue.d.ts @@ -0,0 +1,25 @@ +import { EqualityComparer } from './commonFacade/deps.js'; +import { BaseObservable, IObserver, ISettableObservable, ITransaction } from './base.js'; +import { DebugNameData } from './debugName.js'; +/** + * Holds off updating observers until the value is actually read. +*/ +export declare class LazyObservableValue extends BaseObservable implements ISettableObservable { + private readonly _debugNameData; + private readonly _equalityComparator; + protected _value: T; + private _isUpToDate; + private readonly _deltas; + get debugName(): string; + constructor(_debugNameData: DebugNameData, initialValue: T, _equalityComparator: EqualityComparer); + get(): T; + private _update; + private _updateCounter; + private _beginUpdate; + private _endUpdate; + addObserver(observer: IObserver): void; + removeObserver(observer: IObserver): void; + set(value: T, tx: ITransaction | undefined, change: TChange): void; + toString(): string; + protected _setValue(newValue: T): void; +} diff --git a/packages/core/dist/observableInternal/lazyObservableValue.js b/packages/core/dist/observableInternal/lazyObservableValue.js new file mode 100644 index 00000000..8a2caa2e --- /dev/null +++ b/packages/core/dist/observableInternal/lazyObservableValue.js @@ -0,0 +1,125 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { BaseObservable, TransactionImpl } from './base.js'; +import { getLogger } from './logging.js'; +/** + * Holds off updating observers until the value is actually read. +*/ +export class LazyObservableValue extends BaseObservable { + _debugNameData; + _equalityComparator; + _value; + _isUpToDate = true; + _deltas = []; + get debugName() { + return this._debugNameData.getDebugName(this) ?? 'LazyObservableValue'; + } + constructor(_debugNameData, initialValue, _equalityComparator) { + super(); + this._debugNameData = _debugNameData; + this._equalityComparator = _equalityComparator; + this._value = initialValue; + } + get() { + this._update(); + return this._value; + } + _update() { + if (this._isUpToDate) { + return; + } + this._isUpToDate = true; + if (this._deltas.length > 0) { + for (const change of this._deltas) { + getLogger()?.handleObservableChanged(this, { change, didChange: true, oldValue: '(unknown)', newValue: this._value, hadValue: true }); + for (const observer of this.observers) { + observer.handleChange(this, change); + } + } + this._deltas.length = 0; + } + else { + getLogger()?.handleObservableChanged(this, { change: undefined, didChange: true, oldValue: '(unknown)', newValue: this._value, hadValue: true }); + for (const observer of this.observers) { + observer.handleChange(this, undefined); + } + } + } + _updateCounter = 0; + _beginUpdate() { + this._updateCounter++; + if (this._updateCounter === 1) { + for (const observer of this.observers) { + observer.beginUpdate(this); + } + } + } + _endUpdate() { + this._updateCounter--; + if (this._updateCounter === 0) { + this._update(); + // End update could change the observer list. + const observers = [...this.observers]; + for (const r of observers) { + r.endUpdate(this); + } + } + } + addObserver(observer) { + const shouldCallBeginUpdate = !this.observers.has(observer) && this._updateCounter > 0; + super.addObserver(observer); + if (shouldCallBeginUpdate) { + observer.beginUpdate(this); + } + } + removeObserver(observer) { + const shouldCallEndUpdate = this.observers.has(observer) && this._updateCounter > 0; + super.removeObserver(observer); + if (shouldCallEndUpdate) { + // Calling end update after removing the observer makes sure endUpdate cannot be called twice here. + observer.endUpdate(this); + } + } + set(value, tx, change) { + if (change === undefined && this._equalityComparator(this._value, value)) { + return; + } + let _tx; + if (!tx) { + tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`); + } + try { + this._isUpToDate = false; + this._setValue(value); + if (change !== undefined) { + this._deltas.push(change); + } + tx.updateObserver({ + beginUpdate: () => this._beginUpdate(), + endUpdate: () => this._endUpdate(), + handleChange: (observable, change) => { }, + handlePossibleChange: (observable) => { }, + }, this); + if (this._updateCounter > 1) { + // We already started begin/end update, so we need to manually call handlePossibleChange + for (const observer of this.observers) { + observer.handlePossibleChange(this); + } + } + } + finally { + if (_tx) { + _tx.finish(); + } + } + } + toString() { + return `${this.debugName}: ${this._value}`; + } + _setValue(newValue) { + this._value = newValue; + } +} +//# sourceMappingURL=lazyObservableValue.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/lazyObservableValue.js.map b/packages/core/dist/observableInternal/lazyObservableValue.js.map new file mode 100644 index 00000000..29555ad4 --- /dev/null +++ b/packages/core/dist/observableInternal/lazyObservableValue.js.map @@ -0,0 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;gBACzC,oBAAoB,EAAE,CAAC,UAAU,EAAE,EAAE,GAAG,CAAC;aACzC,EAAE,IAAI,CAAC,CAAC;YAET,IAAI,IAAI,CAAC,cAAc,GAAG,CAAC,EAAE;gBAC5B,wFAAwF;gBACxF,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE;oBACtC,QAAQ,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC;iBACpC;aACD;SAED;gBAAS;YACT,IAAI,GAAG,EAAE;gBACR,GAAG,CAAC,MAAM,EAAE,CAAC;aACb;SACD;IACF,CAAC;IAEQ,QAAQ;QAChB,OAAO,GAAG,IAAI,CAAC,SAAS,KAAK,IAAI,CAAC,MAAM,EAAE,CAAC;IAC5C,CAAC;IAES,SAAS,CAAC,QAAW;QAC9B,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC;IACxB,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/logging.d.ts b/packages/core/dist/observableInternal/logging.d.ts new file mode 100644 index 00000000..4d3ec25f --- /dev/null +++ b/packages/core/dist/observableInternal/logging.d.ts @@ -0,0 +1,54 @@ +import { AutorunObserver } from './autorun.js'; +import { IObservable, TransactionImpl } from './base.js'; +import { Derived } from './derived.js'; +import { FromEventObservable } from './utils.js'; +export declare function setLogger(logger: IObservableLogger): void; +export declare function getLogger(): IObservableLogger | undefined; +export declare function logObservable(obs: IObservable): void; +interface IChangeInformation { + oldValue: unknown; + newValue: unknown; + change: unknown; + didChange: boolean; + hadValue: boolean; +} +export interface IObservableLogger { + handleObservableChanged(observable: IObservable, info: IChangeInformation): void; + handleFromEventObservableTriggered(observable: FromEventObservable, info: IChangeInformation): void; + handleAutorunCreated(autorun: AutorunObserver): void; + handleAutorunTriggered(autorun: AutorunObserver): void; + handleAutorunFinished(autorun: AutorunObserver): void; + handleDerivedCreated(observable: Derived): void; + handleDerivedRecomputed(observable: Derived, info: IChangeInformation): void; + handleDerivedCleared(observable: Derived): void; + handleBeginTransaction(transaction: TransactionImpl): void; + handleEndTransaction(): void; +} +export declare class ConsoleObservableLogger implements IObservableLogger { + private indentation; + private _filteredObjects; + addFilteredObj(obj: unknown): void; + private _isIncluded; + private textToConsoleArgs; + private formatInfo; + handleObservableChanged(observable: IObservable, info: IChangeInformation): void; + private readonly changedObservablesSets; + formatChanges(changes: Set>): ConsoleText | undefined; + handleDerivedCreated(derived: Derived): void; + handleDerivedRecomputed(derived: Derived, info: IChangeInformation): void; + handleDerivedCleared(derived: Derived): void; + handleFromEventObservableTriggered(observable: FromEventObservable, info: IChangeInformation): void; + handleAutorunCreated(autorun: AutorunObserver): void; + handleAutorunTriggered(autorun: AutorunObserver): void; + handleAutorunFinished(autorun: AutorunObserver): void; + handleBeginTransaction(transaction: TransactionImpl): void; + handleEndTransaction(): void; +} +type ConsoleText = (ConsoleText | undefined)[] | { + text: string; + style: string; + data?: unknown[]; +} | { + data: unknown[]; +}; +export {}; diff --git a/packages/core/dist/observableInternal/logging.js b/packages/core/dist/observableInternal/logging.js new file mode 100644 index 00000000..adb3825f --- /dev/null +++ b/packages/core/dist/observableInternal/logging.js @@ -0,0 +1,336 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +let globalObservableLogger; +export function setLogger(logger) { + globalObservableLogger = logger; +} +export function getLogger() { + return globalObservableLogger; +} +export function logObservable(obs) { + if (!globalObservableLogger) { + const l = new ConsoleObservableLogger(); + l.addFilteredObj(obs); + setLogger(l); + } + else { + if (globalObservableLogger instanceof ConsoleObservableLogger) { + globalObservableLogger.addFilteredObj(obs); + } + } +} +export class ConsoleObservableLogger { + indentation = 0; + _filteredObjects; + addFilteredObj(obj) { + if (!this._filteredObjects) { + this._filteredObjects = new Set(); + } + this._filteredObjects.add(obj); + } + _isIncluded(obj) { + return this._filteredObjects?.has(obj) ?? true; + } + textToConsoleArgs(text) { + return consoleTextToArgs([ + normalText(repeat('| ', this.indentation)), + text, + ]); + } + formatInfo(info) { + if (!info.hadValue) { + return [ + normalText(` `), + styled(formatValue(info.newValue, 60), { + color: 'green', + }), + normalText(` (initial)`), + ]; + } + return info.didChange + ? [ + normalText(` `), + styled(formatValue(info.oldValue, 70), { + color: 'red', + strikeThrough: true, + }), + normalText(` `), + styled(formatValue(info.newValue, 60), { + color: 'green', + }), + ] + : [normalText(` (unchanged)`)]; + } + handleObservableChanged(observable, info) { + if (!this._isIncluded(observable)) { + return; + } + console.log(...this.textToConsoleArgs([ + formatKind('observable value changed'), + styled(observable.debugName, { color: 'BlueViolet' }), + ...this.formatInfo(info), + ])); + } + changedObservablesSets = new WeakMap(); + formatChanges(changes) { + if (changes.size === 0) { + return undefined; + } + return styled(' (changed deps: ' + + [...changes].map((o) => o.debugName).join(', ') + + ')', { color: 'gray' }); + } + handleDerivedCreated(derived) { + const existingHandleChange = derived.handleChange; + this.changedObservablesSets.set(derived, new Set()); + derived.handleChange = (observable, change) => { + this.changedObservablesSets.get(derived).add(observable); + return existingHandleChange.apply(derived, [observable, change]); + }; + const debugTrackUpdating = false; + if (debugTrackUpdating) { + const updating = []; + derived.__debugUpdating = updating; + const existingBeginUpdate = derived.beginUpdate; + derived.beginUpdate = (obs) => { + updating.push(obs); + return existingBeginUpdate.apply(derived, [obs]); + }; + const existingEndUpdate = derived.endUpdate; + derived.endUpdate = (obs) => { + const idx = updating.indexOf(obs); + if (idx === -1) { + console.error('endUpdate called without beginUpdate', derived.debugName, obs.debugName); + } + updating.splice(idx, 1); + return existingEndUpdate.apply(derived, [obs]); + }; + } + } + handleDerivedRecomputed(derived, info) { + if (!this._isIncluded(derived)) { + return; + } + const changedObservables = this.changedObservablesSets.get(derived); + if (!changedObservables) { + return; + } + console.log(...this.textToConsoleArgs([ + formatKind('derived recomputed'), + styled(derived.debugName, { color: 'BlueViolet' }), + ...this.formatInfo(info), + this.formatChanges(changedObservables), + { data: [{ fn: derived._debugNameData.referenceFn ?? derived._computeFn }] } + ])); + changedObservables.clear(); + } + handleDerivedCleared(derived) { + if (!this._isIncluded(derived)) { + return; + } + console.log(...this.textToConsoleArgs([ + formatKind('derived cleared'), + styled(derived.debugName, { color: 'BlueViolet' }), + ])); + } + handleFromEventObservableTriggered(observable, info) { + if (!this._isIncluded(observable)) { + return; + } + console.log(...this.textToConsoleArgs([ + formatKind('observable from event triggered'), + styled(observable.debugName, { color: 'BlueViolet' }), + ...this.formatInfo(info), + { data: [{ fn: observable._getValue }] } + ])); + } + handleAutorunCreated(autorun) { + if (!this._isIncluded(autorun)) { + return; + } + const existingHandleChange = autorun.handleChange; + this.changedObservablesSets.set(autorun, new Set()); + autorun.handleChange = (observable, change) => { + this.changedObservablesSets.get(autorun).add(observable); + return existingHandleChange.apply(autorun, [observable, change]); + }; + } + handleAutorunTriggered(autorun) { + const changedObservables = this.changedObservablesSets.get(autorun); + if (!changedObservables) { + return; + } + if (this._isIncluded(autorun)) { + console.log(...this.textToConsoleArgs([ + formatKind('autorun'), + styled(autorun.debugName, { color: 'BlueViolet' }), + this.formatChanges(changedObservables), + { data: [{ fn: autorun._debugNameData.referenceFn ?? autorun._runFn }] } + ])); + } + changedObservables.clear(); + this.indentation++; + } + handleAutorunFinished(autorun) { + this.indentation--; + } + handleBeginTransaction(transaction) { + let transactionName = transaction.getDebugName(); + if (transactionName === undefined) { + transactionName = ''; + } + if (this._isIncluded(transaction)) { + console.log(...this.textToConsoleArgs([ + formatKind('transaction'), + styled(transactionName, { color: 'BlueViolet' }), + { data: [{ fn: transaction._fn }] } + ])); + } + this.indentation++; + } + handleEndTransaction() { + this.indentation--; + } +} +function consoleTextToArgs(text) { + const styles = new Array(); + const data = []; + let firstArg = ''; + function process(t) { + if ('length' in t) { + for (const item of t) { + if (item) { + process(item); + } + } + } + else if ('text' in t) { + firstArg += `%c${t.text}`; + styles.push(t.style); + if (t.data) { + data.push(...t.data); + } + } + else if ('data' in t) { + data.push(...t.data); + } + } + process(text); + const result = [firstArg, ...styles]; + result.push(...data); + return result; +} +function normalText(text) { + return styled(text, { color: 'black' }); +} +function formatKind(kind) { + return styled(padStr(`${kind}: `, 10), { color: 'black', bold: true }); +} +function styled(text, options = { + color: 'black', +}) { + function objToCss(styleObj) { + return Object.entries(styleObj).reduce((styleString, [propName, propValue]) => { + return `${styleString}${propName}:${propValue};`; + }, ''); + } + const style = { + color: options.color, + }; + if (options.strikeThrough) { + style['text-decoration'] = 'line-through'; + } + if (options.bold) { + style['font-weight'] = 'bold'; + } + return { + text, + style: objToCss(style), + }; +} +function formatValue(value, availableLen) { + switch (typeof value) { + case 'number': + return '' + value; + case 'string': + if (value.length + 2 <= availableLen) { + return `"${value}"`; + } + return `"${value.substr(0, availableLen - 7)}"+...`; + case 'boolean': + return value ? 'true' : 'false'; + case 'undefined': + return 'undefined'; + case 'object': + if (value === null) { + return 'null'; + } + if (Array.isArray(value)) { + return formatArray(value, availableLen); + } + return formatObject(value, availableLen); + case 'symbol': + return value.toString(); + case 'function': + return `[[Function${value.name ? ' ' + value.name : ''}]]`; + default: + return '' + value; + } +} +function formatArray(value, availableLen) { + let result = '[ '; + let first = true; + for (const val of value) { + if (!first) { + result += ', '; + } + if (result.length - 5 > availableLen) { + result += '...'; + break; + } + first = false; + result += `${formatValue(val, availableLen - result.length)}`; + } + result += ' ]'; + return result; +} +function formatObject(value, availableLen) { + if (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) { + const val = value.toString(); + if (val.length <= availableLen) { + return val; + } + return val.substring(0, availableLen - 3) + '...'; + } + let result = '{ '; + let first = true; + for (const [key, val] of Object.entries(value)) { + if (!first) { + result += ', '; + } + if (result.length - 5 > availableLen) { + result += '...'; + break; + } + first = false; + result += `${key}: ${formatValue(val, availableLen - result.length)}`; + } + result += ' }'; + return result; +} +function repeat(str, count) { + let result = ''; + for (let i = 1; i <= count; i++) { + result += str; + } + return result; +} +function padStr(str, length) { + while (str.length < length) { + str += ' '; + } + return str; +} +//# sourceMappingURL=logging.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/logging.js.map b/packages/core/dist/observableInternal/logging.js.map new file mode 100644 index 00000000..e4e04174 --- /dev/null +++ b/packages/core/dist/observableInternal/logging.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.js","sourceRoot":"","sources":["../../src/observableInternal/logging.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAOhG,IAAI,sBAAqD,CAAC;AAE1D,MAAM,UAAU,SAAS,CAAC,MAAyB;IAClD,sBAAsB,GAAG,MAAM,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,SAAS;IACxB,OAAO,sBAAsB,CAAC;AAC/B,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,GAAqB;IAClD,IAAI,CAAC,sBAAsB,EAAE;QAC5B,MAAM,CAAC,GAAG,IAAI,uBAAuB,EAAE,CAAC;QACxC,CAAC,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;QACtB,SAAS,CAAC,CAAC,CAAC,CAAC;KACb;SAAM;QACN,IAAI,sBAAsB,YAAY,uBAAuB,EAAE;YAC7D,sBAAkD,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;SACxE;KACD;AACF,CAAC;AA0BD,MAAM,OAAO,uBAAuB;IAC3B,WAAW,GAAG,CAAC,CAAC;IAEhB,gBAAgB,CAA2B;IAE5C,cAAc,CAAC,GAAY;QACjC,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE;YAC3B,IAAI,CAAC,gBAAgB,GAAG,IAAI,GAAG,EAAE,CAAC;SAClC;QACD,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAChC,CAAC;IAEO,WAAW,CAAC,GAAY;QAC/B,OAAO,IAAI,CAAC,gBAAgB,EAAE,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC;IAChD,CAAC;IAEO,iBAAiB,CAAC,IAAiB;QAC1C,OAAO,iBAAiB,CAAC;YACxB,UAAU,CAAC,MAAM,CAAC,KAAK,EA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AC,QAAQ,EAAE,CAAC;QAC7B,IAAI,GAAG,CAAC,MAAM,IAAI,YAAY,EAAE;YAC/B,OAAO,GAAG,CAAC;SACX;QACD,OAAO,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,YAAY,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;KAClD;IAED,IAAI,MAAM,GAAG,IAAI,CAAC;IAClB,IAAI,KAAK,GAAG,IAAI,CAAC;IACjB,KAAK,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;QAC/C,IAAI,CAAC,KAAK,EAAE;YACX,MAAM,IAAI,IAAI,CAAC;SACf;QACD,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,GAAG,YAAY,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC;YAChB,MAAM;SACN;QACD,KAAK,GAAG,KAAK,CAAC;QACd,MAAM,IAAI,GAAG,GAAG,KAAK,WAAW,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;KACtE;IACD,MAAM,IAAI,IAAI,CAAC;IACf,OAAO,MAAM,CAAC;AACf,CAAC;AAED,SAAS,MAAM,CAAC,GAAW,EAAE,KAAa;IACzC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC,EAAE,EAAE;QAChC,MAAM,IAAI,GAAG,CAAC;KACd;IACD,OAAO,MAAM,CAAC;AACf,CAAC;AAED,SAAS,MAAM,CAAC,GAAW,EAAE,MAAc;IAC1C,OAAO,GAAG,CAAC,MAAM,GAAG,MAAM,EAAE;QAC3B,GAAG,IAAI,GAAG,CAAC;KACX;IACD,OAAO,GAAG,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/promise.d.ts b/packages/core/dist/observableInternal/promise.d.ts new file mode 100644 index 00000000..6e08093e --- /dev/null +++ b/packages/core/dist/observableInternal/promise.d.ts @@ -0,0 +1,74 @@ +import { IObservable } from './base.js'; +export declare class ObservableLazy { + private readonly _computeValue; + private readonly _value; + /** + * The cached value. + * Does not force a computation of the value. + */ + get cachedValue(): IObservable; + constructor(_computeValue: () => T); + /** + * Returns the cached value. + * Computes the value if the value has not been cached yet. + */ + getValue(): T; +} +/** + * A promise whose state is observable. + */ +export declare class ObservablePromise { + static fromFn(fn: () => Promise): ObservablePromise; + private readonly _value; + /** + * The promise that this object wraps. + */ + readonly promise: Promise; + /** + * The current state of the promise. + * Is `undefined` if the promise didn't resolve yet. + */ + readonly promiseResult: IObservable | undefined>; + constructor(promise: Promise); +} +export declare class PromiseResult { + /** + * The value of the resolved promise. + * Undefined if the promise rejected. + */ + readonly data: T | undefined; + /** + * The error in case of a rejected promise. + * Undefined if the promise resolved. + */ + readonly error: unknown | undefined; + constructor( + /** + * The value of the resolved promise. + * Undefined if the promise rejected. + */ + data: T | undefined, + /** + * The error in case of a rejected promise. + * Undefined if the promise resolved. + */ + error: unknown | undefined); + /** + * Returns the value if the promise resolved, otherwise throws the error. + */ + getDataOrThrow(): T; +} +/** + * A lazy promise whose state is observable. + */ +export declare class ObservableLazyPromise { + private readonly _computePromise; + private readonly _lazyValue; + /** + * Does not enforce evaluation of the promise compute function. + * Is undefined if the promise has not been computed yet. + */ + readonly cachedPromiseResult: IObservable>; + constructor(_computePromise: () => Promise); + getPromise(): Promise; +} diff --git a/packages/core/dist/observableInternal/promise.js b/packages/core/dist/observableInternal/promise.js new file mode 100644 index 00000000..0d525bd9 --- /dev/null +++ b/packages/core/dist/observableInternal/promise.js @@ -0,0 +1,109 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { observableValue, transaction } from './base.js'; +import { derived } from './derived.js'; +export class ObservableLazy { + _computeValue; + _value = observableValue(this, undefined); + /** + * The cached value. + * Does not force a computation of the value. + */ + get cachedValue() { return this._value; } + constructor(_computeValue) { + this._computeValue = _computeValue; + } + /** + * Returns the cached value. + * Computes the value if the value has not been cached yet. + */ + getValue() { + let v = this._value.get(); + if (!v) { + v = this._computeValue(); + this._value.set(v, undefined); + } + return v; + } +} +/** + * A promise whose state is observable. + */ +export class ObservablePromise { + static fromFn(fn) { + return new ObservablePromise(fn()); + } + _value = observableValue(this, undefined); + /** + * The promise that this object wraps. + */ + promise; + /** + * The current state of the promise. + * Is `undefined` if the promise didn't resolve yet. + */ + promiseResult = this._value; + constructor(promise) { + this.promise = promise.then(value => { + transaction(tx => { + /** @description onPromiseResolved */ + this._value.set(new PromiseResult(value, undefined), tx); + }); + return value; + }, error => { + transaction(tx => { + /** @description onPromiseRejected */ + this._value.set(new PromiseResult(undefined, error), tx); + }); + throw error; + }); + } +} +export class PromiseResult { + data; + error; + constructor( + /** + * The value of the resolved promise. + * Undefined if the promise rejected. + */ + data, + /** + * The error in case of a rejected promise. + * Undefined if the promise resolved. + */ + error) { + this.data = data; + this.error = error; + } + /** + * Returns the value if the promise resolved, otherwise throws the error. + */ + getDataOrThrow() { + if (this.error) { + throw this.error; + } + return this.data; + } +} +/** + * A lazy promise whose state is observable. + */ +export class ObservableLazyPromise { + _computePromise; + _lazyValue = new ObservableLazy(() => new ObservablePromise(this._computePromise())); + /** + * Does not enforce evaluation of the promise compute function. + * Is undefined if the promise has not been computed yet. + */ + cachedPromiseResult = derived(this, reader => this._lazyValue.cachedValue.read(reader)?.promiseResult.read(reader)); + constructor(_computePromise) { + this._computePromise = _computePromise; + } + getPromise() { + return this._lazyValue.getValue().promise; + } +} +//# sourceMappingURL=promise.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/promise.js.map b/packages/core/dist/observableInternal/promise.js.map new file mode 100644 index 00000000..dd14f644 --- /dev/null +++ b/packages/core/dist/observableInternal/promise.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promise.js","sourceRoot":"","sources":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ages/core/dist/observableInternal/utils.d.ts new file mode 100644 index 00000000..b663e1e6 --- /dev/null +++ b/packages/core/dist/observableInternal/utils.d.ts @@ -0,0 +1,109 @@ +import { BaseObservable, IObservable, IObservableWithChange, IObserver, IReader, ITransaction } from './base.js'; +import { DebugNameData, DebugOwner, IDebugNameData } from './debugName.js'; +import { DisposableStore, EqualityComparer, Event, IDisposable, IValueWithChangeEvent } from './commonFacade/deps.js'; +/** + * Represents an efficient observable whose value never changes. + */ +export declare function constObservable(value: T): IObservable; +export declare function observableFromPromise(promise: Promise): IObservable<{ + value?: T; +}>; +export declare function observableFromEvent(owner: DebugOwner, event: Event, getValue: (args: TArgs | undefined) => T): IObservable; +export declare function observableFromEvent(event: Event, getValue: (args: TArgs | undefined) => T): IObservable; +export declare function observableFromEventOpts(options: IDebugNameData & { + equalsFn?: EqualityComparer; +}, event: Event, getValue: (args: TArgs | undefined) => T): IObservable; +export declare class FromEventObservable extends BaseObservable { + private readonly _debugNameData; + private readonly event; + readonly _getValue: (args: TArgs | undefined) => T; + private readonly _getTransaction; + private readonly _equalityComparator; + static globalTransaction: ITransaction | undefined; + private value; + private hasValue; + private subscription; + constructor(_debugNameData: DebugNameData, event: Event, _getValue: (args: TArgs | undefined) => T, _getTransaction: () => ITransaction | undefined, _equalityComparator: EqualityComparer); + private getDebugName; + get debugName(): string; + protected onFirstObserverAdded(): void; + private readonly handleEvent; + protected onLastObserverRemoved(): void; + get(): T; +} +export declare namespace observableFromEvent { + const Observer: typeof FromEventObservable; + function batchEventsGlobally(tx: ITransaction, fn: () => void): void; +} +export declare function observableSignalFromEvent(debugName: string, event: Event): IObservable; +/** + * Creates a signal that can be triggered to invalidate observers. + * Signals don't have a value - when they are triggered they indicate a change. + * However, signals can carry a delta that is passed to observers. + */ +export declare function observableSignal(debugName: string): IObservableSignal; +export declare function observableSignal(owner: object): IObservableSignal; +export interface IObservableSignal extends IObservableWithChange { + trigger(tx: ITransaction | undefined, change: TChange): void; +} +export declare function signalFromObservable(owner: DebugOwner | undefined, observable: IObservable): IObservable; +/** + * @deprecated Use `debouncedObservable2` instead. + */ +export declare function debouncedObservable(observable: IObservable, debounceMs: number, disposableStore: DisposableStore): IObservable; +/** + * Creates an observable that debounces the input observable. + */ +export declare function debouncedObservable2(observable: IObservable, debounceMs: number): IObservable; +export declare function wasEventTriggeredRecently(event: Event, timeoutMs: number, disposableStore: DisposableStore): IObservable; +/** + * This makes sure the observable is being observed and keeps its cache alive. + */ +export declare function keepObserved(observable: IObservable): IDisposable; +/** + * This converts the given observable into an autorun. + */ +export declare function recomputeInitiallyAndOnChange(observable: IObservable, handleValue?: (value: T) => void): IDisposable; +export declare class KeepAliveObserver implements IObserver { + private readonly _forceRecompute; + private readonly _handleValue; + private _counter; + constructor(_forceRecompute: boolean, _handleValue: ((value: any) => void) | undefined); + beginUpdate(observable: IObservable): void; + endUpdate(observable: IObservable): void; + handlePossibleChange(observable: IObservable): void; + handleChange(observable: IObservableWithChange, change: TChange): void; +} +export declare function derivedObservableWithCache(owner: DebugOwner, computeFn: (reader: IReader, lastValue: T | undefined) => T): IObservable; +export declare function derivedObservableWithWritableCache(owner: object, computeFn: (reader: IReader, lastValue: T | undefined) => T): IObservable & { + clearCache(transaction: ITransaction): void; + setCache(newValue: T | undefined, tx: ITransaction | undefined): void; +}; +/** + * When the items array changes, referential equal items are not mapped again. + */ +export declare function mapObservableArrayCached(owner: DebugOwner, items: IObservable, map: (input: TIn, store: DisposableStore) => TOut, keySelector?: (input: TIn) => TKey): IObservable; +export declare class ValueWithChangeEventFromObservable implements IValueWithChangeEvent { + readonly observable: IObservable; + constructor(observable: IObservable); + get onDidChange(): Event; + get value(): T; +} +export declare function observableFromValueWithChangeEvent(owner: DebugOwner, value: IValueWithChangeEvent): IObservable; +/** + * Creates an observable that has the latest changed value of the given observables. + * Initially (and when not observed), it has the value of the last observable. + * When observed and any of the observables change, it has the value of the last changed observable. + * If multiple observables change in the same transaction, the last observable wins. +*/ +export declare function latestChangedValue[]>(owner: DebugOwner, observables: T): IObservable>; +/** + * Works like a derived. + * However, if the value is not undefined, it is cached and will not be recomputed anymore. + * In that case, the derived will unsubscribe from its dependencies. +*/ +export declare function derivedConstOnceDefined(owner: DebugOwner, fn: (reader: IReader) => T): IObservable; +type RemoveUndefined = T extends undefined ? never : T; +export declare function runOnChange(observable: IObservableWithChange, cb: (value: T, previousValue: undefined | T, deltas: RemoveUndefined[]) => void): IDisposable; +export declare function runOnChangeWithStore(observable: IObservableWithChange, cb: (value: T, previousValue: undefined | T, deltas: RemoveUndefined[], store: DisposableStore) => void): IDisposable; +export {}; diff --git a/packages/core/dist/observableInternal/utils.js b/packages/core/dist/observableInternal/utils.js new file mode 100644 index 00000000..0227a434 --- /dev/null +++ b/packages/core/dist/observableInternal/utils.js @@ -0,0 +1,548 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { autorun, autorunOpts, autorunWithStoreHandleChanges } from './autorun.js'; +import { BaseObservable, ConvenientObservable, _setKeepObserved, _setRecomputeInitiallyAndOnChange, observableValue, subtransaction, transaction } from './base.js'; +import { DebugNameData, getDebugName, } from './debugName.js'; +import { BugIndicatingError, DisposableStore, Event, strictEquals, toDisposable } from './commonFacade/deps.js'; +import { derived, derivedOpts } from './derived.js'; +import { getLogger } from './logging.js'; +/** + * Represents an efficient observable whose value never changes. + */ +export function constObservable(value) { + return new ConstObservable(value); +} +class ConstObservable extends ConvenientObservable { + value; + constructor(value) { + super(); + this.value = value; + } + get debugName() { + return this.toString(); + } + get() { + return this.value; + } + addObserver(observer) { + // NO OP + } + removeObserver(observer) { + // NO OP + } + toString() { + return `Const: ${this.value}`; + } +} +export function observableFromPromise(promise) { + const observable = observableValue('promiseValue', {}); + promise.then((value) => { + observable.set({ value }, undefined); + }); + return observable; +} +export function observableFromEvent(...args) { + let owner; + let event; + let getValue; + if (args.length === 3) { + [owner, event, getValue] = args; + } + else { + [event, getValue] = args; + } + return new FromEventObservable(new DebugNameData(owner, undefined, getValue), event, getValue, () => FromEventObservable.globalTransaction, strictEquals); +} +export function observableFromEventOpts(options, event, getValue) { + return new FromEventObservable(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? getValue), event, getValue, () => FromEventObservable.globalTransaction, options.equalsFn ?? strictEquals); +} +export class FromEventObservable extends BaseObservable { + _debugNameData; + event; + _getValue; + _getTransaction; + _equalityComparator; + static globalTransaction; + value; + hasValue = false; + subscription; + constructor(_debugNameData, event, _getValue, _getTransaction, _equalityComparator) { + super(); + this._debugNameData = _debugNameData; + this.event = event; + this._getValue = _getValue; + this._getTransaction = _getTransaction; + this._equalityComparator = _equalityComparator; + } + getDebugName() { + return this._debugNameData.getDebugName(this); + } + get debugName() { + const name = this.getDebugName(); + return 'From Event' + (name ? `: ${name}` : ''); + } + onFirstObserverAdded() { + this.subscription = this.event(this.handleEvent); + } + handleEvent = (args) => { + const newValue = this._getValue(args); + const oldValue = this.value; + const didChange = !this.hasValue || !(this._equalityComparator(oldValue, newValue)); + let didRunTransaction = false; + if (didChange) { + this.value = newValue; + if (this.hasValue) { + didRunTransaction = true; + subtransaction(this._getTransaction(), (tx) => { + getLogger()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: undefined, didChange, hadValue: this.hasValue }); + for (const o of this.observers) { + tx.updateObserver(o, this); + o.handleChange(this, undefined); + } + }, () => { + const name = this.getDebugName(); + return 'Event fired' + (name ? `: ${name}` : ''); + }); + } + this.hasValue = true; + } + if (!didRunTransaction) { + getLogger()?.handleFromEventObservableTriggered(this, { oldValue, newValue, change: undefined, didChange, hadValue: this.hasValue }); + } + }; + onLastObserverRemoved() { + this.subscription.dispose(); + this.subscription = undefined; + this.hasValue = false; + this.value = undefined; + } + get() { + if (this.subscription) { + if (!this.hasValue) { + this.handleEvent(undefined); + } + return this.value; + } + else { + // no cache, as there are no subscribers to keep it updated + const value = this._getValue(undefined); + return value; + } + } +} +(function (observableFromEvent) { + observableFromEvent.Observer = FromEventObservable; + function batchEventsGlobally(tx, fn) { + let didSet = false; + if (FromEventObservable.globalTransaction === undefined) { + FromEventObservable.globalTransaction = tx; + didSet = true; + } + try { + fn(); + } + finally { + if (didSet) { + FromEventObservable.globalTransaction = undefined; + } + } + } + observableFromEvent.batchEventsGlobally = batchEventsGlobally; +})(observableFromEvent = observableFromEvent || (observableFromEvent = {})); +export function observableSignalFromEvent(debugName, event) { + return new FromEventObservableSignal(debugName, event); +} +class FromEventObservableSignal extends BaseObservable { + debugName; + event; + subscription; + constructor(debugName, event) { + super(); + this.debugName = debugName; + this.event = event; + } + onFirstObserverAdded() { + this.subscription = this.event(this.handleEvent); + } + handleEvent = () => { + transaction((tx) => { + for (const o of this.observers) { + tx.updateObserver(o, this); + o.handleChange(this, undefined); + } + }, () => this.debugName); + }; + onLastObserverRemoved() { + this.subscription.dispose(); + this.subscription = undefined; + } + get() { + // NO OP + } +} +export function observableSignal(debugNameOrOwner) { + if (typeof debugNameOrOwner === 'string') { + return new ObservableSignal(debugNameOrOwner); + } + else { + return new ObservableSignal(undefined, debugNameOrOwner); + } +} +class ObservableSignal extends BaseObservable { + _debugName; + _owner; + get debugName() { + return new DebugNameData(this._owner, this._debugName, undefined).getDebugName(this) ?? 'Observable Signal'; + } + toString() { + return this.debugName; + } + constructor(_debugName, _owner) { + super(); + this._debugName = _debugName; + this._owner = _owner; + } + trigger(tx, change) { + if (!tx) { + transaction(tx => { + this.trigger(tx, change); + }, () => `Trigger signal ${this.debugName}`); + return; + } + for (const o of this.observers) { + tx.updateObserver(o, this); + o.handleChange(this, change); + } + } + get() { + // NO OP + } +} +export function signalFromObservable(owner, observable) { + return derivedOpts({ + owner, + equalsFn: () => false, + }, reader => { + observable.read(reader); + }); +} +/** + * @deprecated Use `debouncedObservable2` instead. + */ +export function debouncedObservable(observable, debounceMs, disposableStore) { + const debouncedObservable = observableValue('debounced', undefined); + let timeout = undefined; + disposableStore.add(autorun(reader => { + /** @description debounce */ + const value = observable.read(reader); + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(() => { + transaction(tx => { + debouncedObservable.set(value, tx); + }); + }, debounceMs); + })); + return debouncedObservable; +} +/** + * Creates an observable that debounces the input observable. + */ +export function debouncedObservable2(observable, debounceMs) { + let hasValue = false; + let lastValue; + let timeout = undefined; + return observableFromEvent(cb => { + const d = autorun(reader => { + const value = observable.read(reader); + if (!hasValue) { + hasValue = true; + lastValue = value; + } + else { + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(() => { + lastValue = value; + cb(); + }, debounceMs); + } + }); + return { + dispose() { + d.dispose(); + hasValue = false; + lastValue = undefined; + }, + }; + }, () => { + if (hasValue) { + return lastValue; + } + else { + return observable.get(); + } + }); +} +export function wasEventTriggeredRecently(event, timeoutMs, disposableStore) { + const observable = observableValue('triggeredRecently', false); + let timeout = undefined; + disposableStore.add(event(() => { + observable.set(true, undefined); + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(() => { + observable.set(false, undefined); + }, timeoutMs); + })); + return observable; +} +/** + * This makes sure the observable is being observed and keeps its cache alive. + */ +export function keepObserved(observable) { + const o = new KeepAliveObserver(false, undefined); + observable.addObserver(o); + return toDisposable(() => { + observable.removeObserver(o); + }); +} +_setKeepObserved(keepObserved); +/** + * This converts the given observable into an autorun. + */ +export function recomputeInitiallyAndOnChange(observable, handleValue) { + const o = new KeepAliveObserver(true, handleValue); + observable.addObserver(o); + if (handleValue) { + handleValue(observable.get()); + } + else { + observable.reportChanges(); + } + return toDisposable(() => { + observable.removeObserver(o); + }); +} +_setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange); +export class KeepAliveObserver { + _forceRecompute; + _handleValue; + _counter = 0; + constructor(_forceRecompute, _handleValue) { + this._forceRecompute = _forceRecompute; + this._handleValue = _handleValue; + } + beginUpdate(observable) { + this._counter++; + } + endUpdate(observable) { + this._counter--; + if (this._counter === 0 && this._forceRecompute) { + if (this._handleValue) { + this._handleValue(observable.get()); + } + else { + observable.reportChanges(); + } + } + } + handlePossibleChange(observable) { + // NO OP + } + handleChange(observable, change) { + // NO OP + } +} +export function derivedObservableWithCache(owner, computeFn) { + let lastValue = undefined; + const observable = derivedOpts({ owner, debugReferenceFn: computeFn }, reader => { + lastValue = computeFn(reader, lastValue); + return lastValue; + }); + return observable; +} +export function derivedObservableWithWritableCache(owner, computeFn) { + let lastValue = undefined; + const onChange = observableSignal('derivedObservableWithWritableCache'); + const observable = derived(owner, reader => { + onChange.read(reader); + lastValue = computeFn(reader, lastValue); + return lastValue; + }); + return Object.assign(observable, { + clearCache: (tx) => { + lastValue = undefined; + onChange.trigger(tx); + }, + setCache: (newValue, tx) => { + lastValue = newValue; + onChange.trigger(tx); + } + }); +} +/** + * When the items array changes, referential equal items are not mapped again. + */ +export function mapObservableArrayCached(owner, items, map, keySelector) { + let m = new ArrayMap(map, keySelector); + const self = derivedOpts({ + debugReferenceFn: map, + owner, + onLastObserverRemoved: () => { + m.dispose(); + m = new ArrayMap(map); + } + }, (reader) => { + m.setItems(items.read(reader)); + return m.getItems(); + }); + return self; +} +class ArrayMap { + _map; + _keySelector; + _cache = new Map(); + _items = []; + constructor(_map, _keySelector) { + this._map = _map; + this._keySelector = _keySelector; + } + dispose() { + this._cache.forEach(entry => entry.store.dispose()); + this._cache.clear(); + } + setItems(items) { + const newItems = []; + const itemsToRemove = new Set(this._cache.keys()); + for (const item of items) { + const key = this._keySelector ? this._keySelector(item) : item; + let entry = this._cache.get(key); + if (!entry) { + const store = new DisposableStore(); + const out = this._map(item, store); + entry = { out, store }; + this._cache.set(key, entry); + } + else { + itemsToRemove.delete(key); + } + newItems.push(entry.out); + } + for (const item of itemsToRemove) { + const entry = this._cache.get(item); + entry.store.dispose(); + this._cache.delete(item); + } + this._items = newItems; + } + getItems() { + return this._items; + } +} +export class ValueWithChangeEventFromObservable { + observable; + constructor(observable) { + this.observable = observable; + } + get onDidChange() { + return Event.fromObservableLight(this.observable); + } + get value() { + return this.observable.get(); + } +} +export function observableFromValueWithChangeEvent(owner, value) { + if (value instanceof ValueWithChangeEventFromObservable) { + return value.observable; + } + return observableFromEvent(owner, value.onDidChange, () => value.value); +} +/** + * Creates an observable that has the latest changed value of the given observables. + * Initially (and when not observed), it has the value of the last observable. + * When observed and any of the observables change, it has the value of the last changed observable. + * If multiple observables change in the same transaction, the last observable wins. +*/ +export function latestChangedValue(owner, observables) { + if (observables.length === 0) { + throw new BugIndicatingError(); + } + let hasLastChangedValue = false; + let lastChangedValue = undefined; + const result = observableFromEvent(owner, cb => { + const store = new DisposableStore(); + for (const o of observables) { + store.add(autorunOpts({ debugName: () => getDebugName(result, new DebugNameData(owner, undefined, undefined)) + '.updateLastChangedValue' }, reader => { + hasLastChangedValue = true; + lastChangedValue = o.read(reader); + cb(); + })); + } + store.add({ + dispose() { + hasLastChangedValue = false; + lastChangedValue = undefined; + }, + }); + return store; + }, () => { + if (hasLastChangedValue) { + return lastChangedValue; + } + else { + return observables[observables.length - 1].get(); + } + }); + return result; +} +/** + * Works like a derived. + * However, if the value is not undefined, it is cached and will not be recomputed anymore. + * In that case, the derived will unsubscribe from its dependencies. +*/ +export function derivedConstOnceDefined(owner, fn) { + return derivedObservableWithCache(owner, (reader, lastValue) => lastValue ?? fn(reader)); +} +export function runOnChange(observable, cb) { + let _previousValue; + return autorunWithStoreHandleChanges({ + createEmptyChangeSummary: () => ({ deltas: [], didChange: false }), + handleChange: (context, changeSummary) => { + if (context.didChange(observable)) { + const e = context.change; + if (e !== undefined) { + changeSummary.deltas.push(e); + } + changeSummary.didChange = true; + } + return true; + }, + }, (reader, changeSummary) => { + const value = observable.read(reader); + const previousValue = _previousValue; + if (changeSummary.didChange) { + _previousValue = value; + cb(value, previousValue, changeSummary.deltas); + } + }); +} +export function runOnChangeWithStore(observable, cb) { + const store = new DisposableStore(); + const disposable = runOnChange(observable, (value, previousValue, deltas) => { + store.clear(); + cb(value, previousValue, deltas, store); + }); + return { + dispose() { + disposable.dispose(); + store.dispose(); + } + }; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/utils.js.map b/packages/core/dist/observableInternal/utils.js.map new file mode 100644 index 00000000..21cf42be --- /dev/null +++ b/packages/core/dist/observableInternal/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/observableInternal/utils.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC;AACnF,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAwE,gBAAgB,EAAE,iCAAiC,EAAE,eAAe,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAC1O,OAAO,EAAE,aAAa,EAA8B,YAAY,GAAG,MAAM,gBAAgB,CAAC;AAC1F,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAoB,KAAK,EAAsC,YAAY,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtK,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;GAEG;AACH,MAAM,UAAU,eAAe,CAAI,KAAQ;IAC1C,OAAO,IAAI,eAAe,CAAC,KAAK,CAAC,CAAC;AACnC,CAAC;AAED,MAAM,eAAmB,SAAQ,oBAA6B;IAChC;IAA7B,YAA6B,KAAQ;QACpC,KAAK,EAAE,CAAC;QADoB,UAAK,GAAL,KAAK,CAAG;IAErC,CAAC;IAED,IAAoB,SAAS;QAC5B,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC;IACxB,CAAC;IAEM,GAAG;QACT,OAAO,IAAI,CAAC,KAAK,CAAC;IACnB,CAAC;IACM,WAAW,CAAC,QAAmB;QACrC,QAAQ;IACT,CAAC;IACM,cAAc,CAAC,QAAmB;QACxC,QAAQ;IACT,CAAC;IAEQ,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AM,CAAC;gBACzB,IAAI,CAAC,KAAK,SAAS,EAAE;oBACpB,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAA6B,CAAC,CAAC;iBACzD;gBACD,aAAa,CAAC,SAAS,GAAG,IAAI,CAAC;aAC/B;YACD,OAAO,IAAI,CAAC;QACb,CAAC;KACD,EAAE,CAAC,MAAM,EAAE,aAAa,EAAE,EAAE;QAC5B,MAAM,KAAK,GAAG,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACtC,MAAM,aAAa,GAAG,cAAc,CAAC;QACrC,IAAI,aAAa,CAAC,SAAS,EAAE;YAC5B,cAAc,GAAG,KAAK,CAAC;YACvB,EAAE,CAAC,KAAK,EAAE,aAAa,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;SAC/C;IACF,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAa,UAA6C,EAAE,EAAgH;IAC/M,MAAM,KAAK,GAAG,IAAI,eAAe,EAAE,CAAC;IACpC,MAAM,UAAU,GAAG,WAAW,CAAC,UAAU,EAAE,CAAC,KAAK,EAAE,aAA4B,EAAE,MAAM,EAAE,EAAE;QAC1F,KAAK,CAAC,KAAK,EAAE,CAAC;QACd,EAAE,CAAC,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;IACzC,CAAC,CAAC,CAAC;IACH,OAAO;QACN,OAAO;YACN,UAAU,CAAC,OAAO,EAAE,CAAC;YACrB,KAAK,CAAC,OAAO,EAAE,CAAC;QACjB,CAAC;KACD,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/observableInternal/utilsCancellation.d.ts b/packages/core/dist/observableInternal/utilsCancellation.d.ts new file mode 100644 index 00000000..a3591db1 --- /dev/null +++ b/packages/core/dist/observableInternal/utilsCancellation.d.ts @@ -0,0 +1,10 @@ +import { IReader, IObservable } from './base.js'; +import { CancellationToken } from './commonFacade/cancellation.js'; +/** + * Resolves the promise when the observables state matches the predicate. + */ +export declare function waitForState(observable: IObservable): Promise; +export declare function waitForState(observable: IObservable, predicate: (state: T) => state is TState, isError?: (state: T) => boolean | unknown | undefined, cancellationToken?: CancellationToken): Promise; +export declare function waitForState(observable: IObservable, predicate: (state: T) => boolean, isError?: (state: T) => boolean | unknown | undefined, cancellationToken?: CancellationToken): Promise; +export declare function derivedWithCancellationToken(computeFn: (reader: IReader, cancellationToken: CancellationToken) => T): IObservable; +export declare function derivedWithCancellationToken(owner: object, computeFn: (reader: IReader, cancellationToken: CancellationToken) => T): IObservable; diff --git a/packages/core/dist/observableInternal/utilsCancellation.js b/packages/core/dist/observableInternal/utilsCancellation.js new file mode 100644 index 00000000..ac8debd2 --- /dev/null +++ b/packages/core/dist/observableInternal/utilsCancellation.js @@ -0,0 +1,83 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { DebugNameData } from './debugName.js'; +import { CancellationError, CancellationTokenSource } from './commonFacade/cancellation.js'; +import { Derived } from './derived.js'; +import { strictEquals } from './commonFacade/deps.js'; +import { autorun } from './autorun.js'; +export function waitForState(observable, predicate, isError, cancellationToken) { + if (!predicate) { + predicate = state => state !== null && state !== undefined; + } + return new Promise((resolve, reject) => { + let isImmediateRun = true; + let shouldDispose = false; + const stateObs = observable.map(state => { + /** @description waitForState.state */ + return { + isFinished: predicate(state), + error: isError ? isError(state) : false, + state + }; + }); + const d = autorun(reader => { + /** @description waitForState */ + const { isFinished, error, state } = stateObs.read(reader); + if (isFinished || error) { + if (isImmediateRun) { + // The variable `d` is not initialized yet + shouldDispose = true; + } + else { + d.dispose(); + } + if (error) { + reject(error === true ? state : error); + } + else { + resolve(state); + } + } + }); + if (cancellationToken) { + const dc = cancellationToken.onCancellationRequested(() => { + d.dispose(); + dc.dispose(); + reject(new CancellationError()); + }); + if (cancellationToken.isCancellationRequested) { + d.dispose(); + dc.dispose(); + reject(new CancellationError()); + return; + } + } + isImmediateRun = false; + if (shouldDispose) { + d.dispose(); + } + }); +} +export function derivedWithCancellationToken(computeFnOrOwner, computeFnOrUndefined) { + let computeFn; + let owner; + if (computeFnOrUndefined === undefined) { + computeFn = computeFnOrOwner; + owner = undefined; + } + else { + owner = computeFnOrOwner; + computeFn = computeFnOrUndefined; + } + let cancellationTokenSource = undefined; + return new Derived(new DebugNameData(owner, undefined, computeFn), r => { + if (cancellationTokenSource) { + cancellationTokenSource.dispose(true); + } + cancellationTokenSource = new CancellationTokenSource(); + return computeFn(r, cancellationTokenSource.token); + }, undefined, undefined, () => cancellationTokenSource?.dispose(), strictEquals); +} +//# sourceMappingURL=utilsCancellation.js.map \ No newline at end of file diff --git a/packages/core/dist/observableInternal/utilsCancellation.js.map b/packages/core/dist/observableInternal/utilsCancellation.js.map new file mode 100644 index 00000000..ec1631b0 --- /dev/null +++ b/packages/core/dist/observableInternal/utilsCancellation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utilsCancellation.js","sourceRoot":"","sources":["../../src/observableInternal/utilsCancellation.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAGhG,OAAO,EAAc,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAqB,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAC/G,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAQvC,MAAM,UAAU,YAAY,CAAI,UAA0B,EAAE,SAAiC,EAAE,OAAqD,EAAE,iBAAqC;IAC1L,IAAI,CAAC,SAAS,EAAE;QACf,SAAS,GAAG,KAAK,CAAC,EAAE,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC;KAC3D;IACD,OAAO,IAAI,OAAO,CAAC,CAAC,OAA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,CAAC;gBACZ,EAAE,CAAC,OAAO,EAAE,CAAC;gBACb,MAAM,CAAC,IAAI,iBAAiB,EAAE,CAAC,CAAC;gBAChC,OAAO;aACP;SACD;QACD,cAAc,GAAG,KAAK,CAAC;QACvB,IAAI,aAAa,EAAE;YAClB,CAAC,CAAC,OAAO,EAAE,CAAC;SACZ;IACF,CAAC,CAAC,CAAC;AACJ,CAAC;AAID,MAAM,UAAU,4BAA4B,CAAI,gBAAyF,EAAE,oBAAqF;IAC/N,IAAI,SAA2D,CAAC;IAChE,IAAI,KAAiB,CAAC;IACtB,IAAI,oBAAoB,KAAK,SAAS,EAAE;QACvC,SAAS,GAAG,gBAAuB,CAAC;QACpC,KAAK,GAAG,SAAS,CAAC;KAClB;SAAM;QACN,KAAK,GAAG,gBAAgB,CAAC;QACzB,SAAS,GAAG,oBAA2B,CAAC;KACxC;IAED,IAAI,uBAAuB,GAAwC,SAAS,CAAC;IAC7E,OAAO,IAAI,OAAO,CACjB,IAAI,aAAa,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,CAAC,EAC9C,CAAC,CAAC,EAAE;QACH,IAAI,uBAAuB,EAAE;YAC5B,uBAAuB,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;SACtC;QACD,uBAAuB,GAAG,IAAI,uBAAuB,EAAE,CAAC;QACxD,OAAO,SAAS,CAAC,CAAC,EAAE,uBAAuB,CAAC,KAAK,CAAC,CAAC;IACpD,CAAC,EAAE,SAAS,EACZ,SAAS,EACT,GAAG,EAAE,CAAC,uBAAuB,EAAE,OAAO,EAAE,EACxC,YAAY,CACZ,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/path.d.ts b/packages/core/dist/path.d.ts new file mode 100644 index 00000000..c7ed7908 --- /dev/null +++ b/packages/core/dist/path.d.ts @@ -0,0 +1,39 @@ +export interface ParsedPath { + root: string; + dir: string; + base: string; + ext: string; + name: string; +} +export interface IPath { + normalize(path: string): string; + isAbsolute(path: string): boolean; + join(...paths: string[]): string; + resolve(...pathSegments: string[]): string; + relative(from: string, to: string): string; + dirname(path: string): string; + basename(path: string, suffix?: string): string; + extname(path: string): string; + format(pathObject: ParsedPath): string; + parse(path: string): ParsedPath; + toNamespacedPath(path: string): string; + sep: '\\' | '/'; + delimiter: string; + win32: IPath | null; + posix: IPath | null; +} +export declare const win32: IPath; +export declare const posix: IPath; +export declare const normalize: (path: string) => string; +export declare const isAbsolute: (path: string) => boolean; +export declare const join: (...paths: string[]) => string; +export declare const resolve: (...pathSegments: string[]) => string; +export declare const relative: (from: string, to: string) => string; +export declare const dirname: (path: string) => string; +export declare const basename: (path: string, suffix?: string) => string; +export declare const extname: (path: string) => string; +export declare const format: (pathObject: ParsedPath) => string; +export declare const parse: (path: string) => ParsedPath; +export declare const toNamespacedPath: (path: string) => string; +export declare const sep: "/" | "\\"; +export declare const delimiter: string; diff --git a/packages/core/dist/path.js b/packages/core/dist/path.js new file mode 100644 index 00000000..39627430 --- /dev/null +++ b/packages/core/dist/path.js @@ -0,0 +1,1406 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +// NOTE: VSCode's copy of nodejs path library to be usable in common (non-node) namespace +// Copied from: https://github.com/nodejs/node/commits/v20.9.0/lib/path.js +// Excluding: the change that adds primordials +// (https://github.com/nodejs/node/commit/187a862d221dec42fa9a5c4214e7034d9092792f and others) +/** + * Copyright Joyent, Inc. and other Node contributors. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the + * following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + * USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +import * as process from './process.js'; +const CHAR_UPPERCASE_A = 65; /* A */ +const CHAR_LOWERCASE_A = 97; /* a */ +const CHAR_UPPERCASE_Z = 90; /* Z */ +const CHAR_LOWERCASE_Z = 122; /* z */ +const CHAR_DOT = 46; /* . */ +const CHAR_FORWARD_SLASH = 47; /* / */ +const CHAR_BACKWARD_SLASH = 92; /* \ */ +const CHAR_COLON = 58; /* : */ +const CHAR_QUESTION_MARK = 63; /* ? */ +class ErrorInvalidArgType extends Error { + code; + constructor(name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && expected.indexOf('not ') === 0) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } + else { + determiner = 'must be'; + } + const type = name.indexOf('.') !== -1 ? 'property' : 'argument'; + let msg = `The "${name}" ${type} ${determiner} of type ${expected}`; + msg += `. Received type ${typeof actual}`; + super(msg); + this.code = 'ERR_INVALID_ARG_TYPE'; + } +} +function validateObject(pathObject, name) { + if (pathObject === null || typeof pathObject !== 'object') { + throw new ErrorInvalidArgType(name, 'Object', pathObject); + } +} +function validateString(value, name) { + if (typeof value !== 'string') { + throw new ErrorInvalidArgType(name, 'string', value); + } +} +const platformIsWin32 = (process.platform === 'win32'); +function isPathSeparator(code) { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +} +function isPosixPathSeparator(code) { + return code === CHAR_FORWARD_SLASH; +} +function isWindowsDeviceRoot(code) { + return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || + (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z); +} +// Resolves . and .. elements in a path with directory names +function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { + let res = ''; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code = 0; + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } + else if (isPathSeparator(code)) { + break; + } + else { + code = CHAR_FORWARD_SLASH; + } + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) { + // NOOP + } + else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || + res.charCodeAt(res.length - 1) !== CHAR_DOT || + res.charCodeAt(res.length - 2) !== CHAR_DOT) { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf(separator); + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } + else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } + else if (res.length !== 0) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? `${separator}..` : '..'; + lastSegmentLength = 2; + } + } + else { + if (res.length > 0) { + res += `${separator}${path.slice(lastSlash + 1, i)}`; + } + else { + res = path.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } + else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } + else { + dots = -1; + } + } + return res; +} +function formatExt(ext) { + return ext ? `${ext[0] === '.' ? '' : '.'}${ext}` : ''; +} +function _format(sep, pathObject) { + validateObject(pathObject, 'pathObject'); + const dir = pathObject.dir || pathObject.root; + const base = pathObject.base || + `${pathObject.name || ''}${formatExt(pathObject.ext)}`; + if (!dir) { + return base; + } + return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`; +} +export const win32 = { + // path.resolve([from ...], to) + resolve(...pathSegments) { + let resolvedDevice = ''; + let resolvedTail = ''; + let resolvedAbsolute = false; + for (let i = pathSegments.length - 1; i >= -1; i--) { + let path; + if (i >= 0) { + path = pathSegments[i]; + validateString(path, `paths[${i}]`); + // Skip empty entries + if (path.length === 0) { + continue; + } + } + else if (resolvedDevice.length === 0) { + path = process.cwd(); + } + else { + // Windows has the concept of drive-specific current working + // directories. If we've resolved a drive letter but not yet an + // absolute path, get cwd for that drive, or the process cwd if + // the drive cwd is not available. We're sure the device is not + // a UNC path at this points, because UNC paths are always absolute. + path = process.env[`=${resolvedDevice}`] || process.cwd(); + // Verify that a cwd was found and that it actually points + // to our drive. If not, default to the drive's root. + if (path === undefined || + (path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && + path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) { + path = `${resolvedDevice}\\`; + } + } + const len = path.length; + let rootEnd = 0; + let device = ''; + let isAbsolute = false; + const code = path.charCodeAt(0); + // Try to match a root + if (len === 1) { + if (isPathSeparator(code)) { + // `path` contains just a path separator + rootEnd = 1; + isAbsolute = true; + } + } + else if (isPathSeparator(code)) { + // Possible UNC root + // If we started with a separator, we know we at least have an + // absolute path of some kind (UNC or otherwise) + isAbsolute = true; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + while (j < len && !isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + // Matched! + last = j; + // Match 1 or more path separators + while (j < len && isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + while (j < len && !isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j === len || j !== last) { + // We matched a UNC root + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } + else { + rootEnd = 1; + } + } + else if (isWindowsDeviceRoot(code) && + path.charCodeAt(1) === CHAR_COLON) { + // Possible device root + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2 && isPathSeparator(path.charCodeAt(2))) { + // Treat separator following drive name as an absolute path + // indicator + isAbsolute = true; + rootEnd = 3; + } + } + if (device.length > 0) { + if (resolvedDevice.length > 0) { + if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { + // This path points to another device so it is not applicable + continue; + } + } + else { + resolvedDevice = device; + } + } + if (resolvedAbsolute) { + if (resolvedDevice.length > 0) { + break; + } + } + else { + resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; + resolvedAbsolute = isAbsolute; + if (isAbsolute && resolvedDevice.length > 0) { + break; + } + } + } + // At this point the path should be resolved to a full absolute path, + // but handle relative paths to be safe (might happen when process.cwd() + // fails) + // Normalize the tail path + resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparator); + return resolvedAbsolute ? + `${resolvedDevice}\\${resolvedTail}` : + `${resolvedDevice}${resolvedTail}` || '.'; + }, + normalize(path) { + validateString(path, 'path'); + const len = path.length; + if (len === 0) { + return '.'; + } + let rootEnd = 0; + let device; + let isAbsolute = false; + const code = path.charCodeAt(0); + // Try to match a root + if (len === 1) { + // `path` contains just a single char, exit early to avoid + // unnecessary work + return isPosixPathSeparator(code) ? '\\' : path; + } + if (isPathSeparator(code)) { + // Possible UNC root + // If we started with a separator, we know we at least have an absolute + // path of some kind (UNC or otherwise) + isAbsolute = true; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + while (j < len && !isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + // Matched! + last = j; + // Match 1 or more path separators + while (j < len && isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + while (j < len && !isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j === len) { + // We matched a UNC root only + // Return the normalized version of the UNC root since there + // is nothing left to process + return `\\\\${firstPart}\\${path.slice(last)}\\`; + } + if (j !== last) { + // We matched a UNC root with leftovers + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } + else { + rootEnd = 1; + } + } + else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { + // Possible device root + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2 && isPathSeparator(path.charCodeAt(2))) { + // Treat separator following drive name as an absolute path + // indicator + isAbsolute = true; + rootEnd = 3; + } + } + let tail = rootEnd < len ? + normalizeString(path.slice(rootEnd), !isAbsolute, '\\', isPathSeparator) : + ''; + if (tail.length === 0 && !isAbsolute) { + tail = '.'; + } + if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) { + tail += '\\'; + } + if (device === undefined) { + return isAbsolute ? `\\${tail}` : tail; + } + return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`; + }, + isAbsolute(path) { + validateString(path, 'path'); + const len = path.length; + if (len === 0) { + return false; + } + const code = path.charCodeAt(0); + return isPathSeparator(code) || + // Possible device root + (len > 2 && + isWindowsDeviceRoot(code) && + path.charCodeAt(1) === CHAR_COLON && + isPathSeparator(path.charCodeAt(2))); + }, + join(...paths) { + if (paths.length === 0) { + return '.'; + } + let joined; + let firstPart; + for (let i = 0; i < paths.length; ++i) { + const arg = paths[i]; + validateString(arg, 'path'); + if (arg.length > 0) { + if (joined === undefined) { + joined = firstPart = arg; + } + else { + joined += `\\${arg}`; + } + } + } + if (joined === undefined) { + return '.'; + } + // Make sure that the joined path doesn't start with two slashes, because + // normalize() will mistake it for a UNC path then. + // + // This step is skipped when it is very clear that the user actually + // intended to point at a UNC path. This is assumed when the first + // non-empty string arguments starts with exactly two slashes followed by + // at least one more non-slash character. + // + // Note that for normalize() to treat a path as a UNC path it needs to + // have at least 2 components, so we don't filter for that here. + // This means that the user can use join to construct UNC paths from + // a server name and a share name; for example: + // path.join('//server', 'share') -> '\\\\server\\share\\') + let needsReplace = true; + let slashCount = 0; + if (typeof firstPart === 'string' && isPathSeparator(firstPart.charCodeAt(0))) { + ++slashCount; + const firstLen = firstPart.length; + if (firstLen > 1 && isPathSeparator(firstPart.charCodeAt(1))) { + ++slashCount; + if (firstLen > 2) { + if (isPathSeparator(firstPart.charCodeAt(2))) { + ++slashCount; + } + else { + // We matched a UNC path in the first part + needsReplace = false; + } + } + } + } + if (needsReplace) { + // Find any more consecutive slashes we need to replace + while (slashCount < joined.length && + isPathSeparator(joined.charCodeAt(slashCount))) { + slashCount++; + } + // Replace the slashes if needed + if (slashCount >= 2) { + joined = `\\${joined.slice(slashCount)}`; + } + } + return win32.normalize(joined); + }, + // It will solve the relative path from `from` to `to`, for instance: + // from = 'C:\\orandea\\test\\aaa' + // to = 'C:\\orandea\\impl\\bbb' + // The output of the function should be: '..\\..\\impl\\bbb' + relative(from, to) { + validateString(from, 'from'); + validateString(to, 'to'); + if (from === to) { + return ''; + } + const fromOrig = win32.resolve(from); + const toOrig = win32.resolve(to); + if (fromOrig === toOrig) { + return ''; + } + from = fromOrig.toLowerCase(); + to = toOrig.toLowerCase(); + if (from === to) { + return ''; + } + // Trim any leading backslashes + let fromStart = 0; + while (fromStart < from.length && + from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) { + fromStart++; + } + // Trim trailing backslashes (applicable to UNC paths only) + let fromEnd = from.length; + while (fromEnd - 1 > fromStart && + from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) { + fromEnd--; + } + const fromLen = fromEnd - fromStart; + // Trim any leading backslashes + let toStart = 0; + while (toStart < to.length && + to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { + toStart++; + } + // Trim trailing backslashes (applicable to UNC paths only) + let toEnd = to.length; + while (toEnd - 1 > toStart && + to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) { + toEnd--; + } + const toLen = toEnd - toStart; + // Compare paths to find the longest common path from root + const length = fromLen < toLen ? fromLen : toLen; + let lastCommonSep = -1; + let i = 0; + for (; i < length; i++) { + const fromCode = from.charCodeAt(fromStart + i); + if (fromCode !== to.charCodeAt(toStart + i)) { + break; + } + else if (fromCode === CHAR_BACKWARD_SLASH) { + lastCommonSep = i; + } + } + // We found a mismatch before the first common path separator was seen, so + // return the original `to`. + if (i !== length) { + if (lastCommonSep === -1) { + return toOrig; + } + } + else { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { + // We get here if `from` is the exact base path for `to`. + // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' + return toOrig.slice(toStart + i + 1); + } + if (i === 2) { + // We get here if `from` is the device root. + // For example: from='C:\\'; to='C:\\foo' + return toOrig.slice(toStart + i); + } + } + if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='C:\\foo\\bar'; to='C:\\foo' + lastCommonSep = i; + } + else if (i === 2) { + // We get here if `to` is the device root. + // For example: from='C:\\foo\\bar'; to='C:\\' + lastCommonSep = 3; + } + } + if (lastCommonSep === -1) { + lastCommonSep = 0; + } + } + let out = ''; + // Generate the relative path based on the path difference between `to` and + // `from` + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { + out += out.length === 0 ? '..' : '\\..'; + } + } + toStart += lastCommonSep; + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) { + return `${out}${toOrig.slice(toStart, toEnd)}`; + } + if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { + ++toStart; + } + return toOrig.slice(toStart, toEnd); + }, + toNamespacedPath(path) { + // Note: this will *probably* throw somewhere. + if (typeof path !== 'string' || path.length === 0) { + return path; + } + const resolvedPath = win32.resolve(path); + if (resolvedPath.length <= 2) { + return path; + } + if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { + // Possible UNC root + if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { + const code = resolvedPath.charCodeAt(2); + if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { + // Matched non-long UNC root, convert the path to a long UNC path + return `\\\\?\\UNC\\${resolvedPath.slice(2)}`; + } + } + } + else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) && + resolvedPath.charCodeAt(1) === CHAR_COLON && + resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) { + // Matched device root, convert the path to a long UNC path + return `\\\\?\\${resolvedPath}`; + } + return path; + }, + dirname(path) { + validateString(path, 'path'); + const len = path.length; + if (len === 0) { + return '.'; + } + let rootEnd = -1; + let offset = 0; + const code = path.charCodeAt(0); + if (len === 1) { + // `path` contains just a path separator, exit early to avoid + // unnecessary work or a dot. + return isPathSeparator(code) ? path : '.'; + } + // Try to match a root + if (isPathSeparator(code)) { + // Possible UNC root + rootEnd = offset = 1; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + while (j < len && !isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + while (j < len && isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + while (j < len && !isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j === len) { + // We matched a UNC root only + return path; + } + if (j !== last) { + // We matched a UNC root with leftovers + // Offset by 1 to include the separator after the UNC root to + // treat it as a "normal root" on top of a (UNC) root + rootEnd = offset = j + 1; + } + } + } + } + // Possible device root + } + else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { + rootEnd = len > 2 && isPathSeparator(path.charCodeAt(2)) ? 3 : 2; + offset = rootEnd; + } + let end = -1; + let matchedSlash = true; + for (let i = len - 1; i >= offset; --i) { + if (isPathSeparator(path.charCodeAt(i))) { + if (!matchedSlash) { + end = i; + break; + } + } + else { + // We saw the first non-path separator + matchedSlash = false; + } + } + if (end === -1) { + if (rootEnd === -1) { + return '.'; + } + end = rootEnd; + } + return path.slice(0, end); + }, + basename(path, suffix) { + if (suffix !== undefined) { + validateString(suffix, 'suffix'); + } + validateString(path, 'path'); + let start = 0; + let end = -1; + let matchedSlash = true; + let i; + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + if (path.length >= 2 && + isWindowsDeviceRoot(path.charCodeAt(0)) && + path.charCodeAt(1) === CHAR_COLON) { + start = 2; + } + if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) { + if (suffix === path) { + return ''; + } + let extIdx = suffix.length - 1; + let firstNonSlashEnd = -1; + for (i = path.length - 1; i >= start; --i) { + const code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } + else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === suffix.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } + else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + if (start === end) { + end = firstNonSlashEnd; + } + else if (end === -1) { + end = path.length; + } + return path.slice(start, end); + } + for (i = path.length - 1; i >= start; --i) { + if (isPathSeparator(path.charCodeAt(i))) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } + else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + if (end === -1) { + return ''; + } + return path.slice(start, end); + }, + extname(path) { + validateString(path, 'path'); + let start = 0; + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + // Check for a drive letter prefix so as not to mistake the following + // path separator as an extra separator at the end of the path that can be + // disregarded + if (path.length >= 2 && + path.charCodeAt(1) === CHAR_COLON && + isWindowsDeviceRoot(path.charCodeAt(0))) { + start = startPart = 2; + } + for (let i = path.length - 1; i >= start; --i) { + const code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) { + startDot = i; + } + else if (preDotState !== 1) { + preDotState = 1; + } + } + else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && + startDot === end - 1 && + startDot === startPart + 1)) { + return ''; + } + return path.slice(startDot, end); + }, + format: _format.bind(null, '\\'), + parse(path) { + validateString(path, 'path'); + const ret = { root: '', dir: '', base: '', ext: '', name: '' }; + if (path.length === 0) { + return ret; + } + const len = path.length; + let rootEnd = 0; + let code = path.charCodeAt(0); + if (len === 1) { + if (isPathSeparator(code)) { + // `path` contains just a path separator, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + ret.base = ret.name = path; + return ret; + } + // Try to match a root + if (isPathSeparator(code)) { + // Possible UNC root + rootEnd = 1; + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + // Match 1 or more non-path separators + while (j < len && !isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + while (j < len && isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + while (j < len && !isPathSeparator(path.charCodeAt(j))) { + j++; + } + if (j === len) { + // We matched a UNC root only + rootEnd = j; + } + else if (j !== last) { + // We matched a UNC root with leftovers + rootEnd = j + 1; + } + } + } + } + } + else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { + // Possible device root + if (len <= 2) { + // `path` contains just a drive root, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + rootEnd = 2; + if (isPathSeparator(path.charCodeAt(2))) { + if (len === 3) { + // `path` contains just a drive root, exit early to avoid + // unnecessary work + ret.root = ret.dir = path; + return ret; + } + rootEnd = 3; + } + } + if (rootEnd > 0) { + ret.root = path.slice(0, rootEnd); + } + let startDot = -1; + let startPart = rootEnd; + let end = -1; + let matchedSlash = true; + let i = path.length - 1; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + // Get non-dir info + for (; i >= rootEnd; --i) { + code = path.charCodeAt(i); + if (isPathSeparator(code)) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) { + startDot = i; + } + else if (preDotState !== 1) { + preDotState = 1; + } + } + else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (end !== -1) { + if (startDot === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && + startDot === end - 1 && + startDot === startPart + 1)) { + ret.base = ret.name = path.slice(startPart, end); + } + else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + ret.ext = path.slice(startDot, end); + } + } + // If the directory is the root, use the entire root as the `dir` including + // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the + // trailing slash (`C:\abc\def` -> `C:\abc`). + if (startPart > 0 && startPart !== rootEnd) { + ret.dir = path.slice(0, startPart - 1); + } + else { + ret.dir = ret.root; + } + return ret; + }, + sep: '\\', + delimiter: ';', + win32: null, + posix: null +}; +const posixCwd = (() => { + if (platformIsWin32) { + // Converts Windows' backslash path separators to POSIX forward slashes + // and truncates any drive indicator + const regexp = /\\/g; + return () => { + const cwd = process.cwd().replace(regexp, '/'); + return cwd.slice(cwd.indexOf('/')); + }; + } + // We're already on POSIX, no need for any transformations + return () => process.cwd(); +})(); +export const posix = { + // path.resolve([from ...], to) + resolve(...pathSegments) { + let resolvedPath = ''; + let resolvedAbsolute = false; + for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + const path = i >= 0 ? pathSegments[i] : posixCwd(); + validateString(path, `paths[${i}]`); + // Skip empty entries + if (path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + // Normalize the path + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator); + if (resolvedAbsolute) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : '.'; + }, + normalize(path) { + validateString(path, 'path'); + if (path.length === 0) { + return '.'; + } + const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; + // Normalize the path + path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator); + if (path.length === 0) { + if (isAbsolute) { + return '/'; + } + return trailingSeparator ? './' : '.'; + } + if (trailingSeparator) { + path += '/'; + } + return isAbsolute ? `/${path}` : path; + }, + isAbsolute(path) { + validateString(path, 'path'); + return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; + }, + join(...paths) { + if (paths.length === 0) { + return '.'; + } + let joined; + for (let i = 0; i < paths.length; ++i) { + const arg = paths[i]; + validateString(arg, 'path'); + if (arg.length > 0) { + if (joined === undefined) { + joined = arg; + } + else { + joined += `/${arg}`; + } + } + } + if (joined === undefined) { + return '.'; + } + return posix.normalize(joined); + }, + relative(from, to) { + validateString(from, 'from'); + validateString(to, 'to'); + if (from === to) { + return ''; + } + // Trim leading forward slashes. + from = posix.resolve(from); + to = posix.resolve(to); + if (from === to) { + return ''; + } + const fromStart = 1; + const fromEnd = from.length; + const fromLen = fromEnd - fromStart; + const toStart = 1; + const toLen = to.length - toStart; + // Compare paths to find the longest common path from root + const length = (fromLen < toLen ? fromLen : toLen); + let lastCommonSep = -1; + let i = 0; + for (; i < length; i++) { + const fromCode = from.charCodeAt(fromStart + i); + if (fromCode !== to.charCodeAt(toStart + i)) { + break; + } + else if (fromCode === CHAR_FORWARD_SLASH) { + lastCommonSep = i; + } + } + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1); + } + if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i); + } + } + else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } + else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo/bar'; to='/' + lastCommonSep = 0; + } + } + } + let out = ''; + // Generate the relative path based on the path difference between `to` + // and `from`. + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) { + out += out.length === 0 ? '..' : '/..'; + } + } + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts. + return `${out}${to.slice(toStart + lastCommonSep)}`; + }, + toNamespacedPath(path) { + // Non-op on posix systems + return path; + }, + dirname(path) { + validateString(path, 'path'); + if (path.length === 0) { + return '.'; + } + const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + let end = -1; + let matchedSlash = true; + for (let i = path.length - 1; i >= 1; --i) { + if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { + if (!matchedSlash) { + end = i; + break; + } + } + else { + // We saw the first non-path separator + matchedSlash = false; + } + } + if (end === -1) { + return hasRoot ? '/' : '.'; + } + if (hasRoot && end === 1) { + return '//'; + } + return path.slice(0, end); + }, + basename(path, suffix) { + if (suffix !== undefined) { + validateString(suffix, 'ext'); + } + validateString(path, 'path'); + let start = 0; + let end = -1; + let matchedSlash = true; + let i; + if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) { + if (suffix === path) { + return ''; + } + let extIdx = suffix.length - 1; + let firstNonSlashEnd = -1; + for (i = path.length - 1; i >= 0; --i) { + const code = path.charCodeAt(i); + if (code === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } + else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === suffix.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } + else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + if (start === end) { + end = firstNonSlashEnd; + } + else if (end === -1) { + end = path.length; + } + return path.slice(start, end); + } + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } + else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + if (end === -1) { + return ''; + } + return path.slice(start, end); + }, + extname(path) { + validateString(path, 'path'); + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + for (let i = path.length - 1; i >= 0; --i) { + const code = path.charCodeAt(i); + if (code === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) { + startDot = i; + } + else if (preDotState !== 1) { + preDotState = 1; + } + } + else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || + end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && + startDot === end - 1 && + startDot === startPart + 1)) { + return ''; + } + return path.slice(startDot, end); + }, + format: _format.bind(null, '/'), + parse(path) { + validateString(path, 'path'); + const ret = { root: '', dir: '', base: '', ext: '', name: '' }; + if (path.length === 0) { + return ret; + } + const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + let start; + if (isAbsolute) { + ret.root = '/'; + start = 1; + } + else { + start = 0; + } + let startDot = -1; + let startPart = 0; + let end = -1; + let matchedSlash = true; + let i = path.length - 1; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + let preDotState = 0; + // Get non-dir info + for (; i >= start; --i) { + const code = path.charCodeAt(i); + if (code === CHAR_FORWARD_SLASH) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === CHAR_DOT) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) { + startDot = i; + } + else if (preDotState !== 1) { + preDotState = 1; + } + } + else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (end !== -1) { + const start = startPart === 0 && isAbsolute ? 1 : startPart; + if (startDot === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + (preDotState === 1 && + startDot === end - 1 && + startDot === startPart + 1)) { + ret.base = ret.name = path.slice(start, end); + } + else { + ret.name = path.slice(start, startDot); + ret.base = path.slice(start, end); + ret.ext = path.slice(startDot, end); + } + } + if (startPart > 0) { + ret.dir = path.slice(0, startPart - 1); + } + else if (isAbsolute) { + ret.dir = '/'; + } + return ret; + }, + sep: '/', + delimiter: ':', + win32: null, + posix: null +}; +posix.win32 = win32.win32 = win32; +posix.posix = win32.posix = posix; +export const normalize = (platformIsWin32 ? win32.normalize : posix.normalize); +export const isAbsolute = (platformIsWin32 ? win32.isAbsolute : posix.isAbsolute); +export const join = (platformIsWin32 ? win32.join : posix.join); +export const resolve = (platformIsWin32 ? win32.resolve : posix.resolve); +export const relative = (platformIsWin32 ? win32.relative : posix.relative); +export const dirname = (platformIsWin32 ? win32.dirname : posix.dirname); +export const basename = (platformIsWin32 ? win32.basename : posix.basename); +export const extname = (platformIsWin32 ? win32.extname : posix.extname); +export const format = (platformIsWin32 ? win32.format : posix.format); +export const parse = (platformIsWin32 ? win32.parse : posix.parse); +export const toNamespacedPath = (platformIsWin32 ? win32.toNamespacedPath : posix.toNamespacedPath); +export const sep = (platformIsWin32 ? win32.sep : posix.sep); +export const delimiter = (platformIsWin32 ? win32.delimiter : posix.delimiter); +//# sourceMappingURL=path.js.map \ No newline at end of file diff --git a/packages/core/dist/path.js.map b/packages/core/dist/path.js.map new file mode 100644 index 00000000..f6f2c696 --- /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QAAQ,CAAC,CAAC;AAC5E,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACzE,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AACtE,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AACnE,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;AACpG,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC7D,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/platform.d.ts b/packages/core/dist/platform.d.ts new file mode 100644 index 00000000..1803990b --- /dev/null +++ b/packages/core/dist/platform.d.ts @@ -0,0 +1,99 @@ +export declare const LANGUAGE_DEFAULT = "en"; +export interface IProcessEnvironment { + [key: string]: string | undefined; +} +/** + * This interface is intentionally not identical to node.js + * process because it also works in sandboxed environments + * where the process object is implemented differently. We + * define the properties here that we need for `platform` + * to work and nothing else. + */ +export interface INodeProcess { + platform: string; + arch: string; + env: IProcessEnvironment; + versions?: { + node?: string; + electron?: string; + chrome?: string; + }; + type?: string; + cwd: () => string; +} +export declare const enum Platform { + Web = 0, + Mac = 1, + Linux = 2, + Windows = 3 +} +export type PlatformName = 'Web' | 'Windows' | 'Mac' | 'Linux'; +export declare function PlatformToString(platform: Platform): PlatformName; +export declare const isWindows: boolean; +export declare const isMacintosh: boolean; +export declare const isLinux: boolean; +export declare const isLinuxSnap: boolean; +export declare const isNative: boolean; +export declare const isElectron: boolean; +export declare const isWeb: boolean; +export declare const isWebWorker: boolean; +export declare const webWorkerOrigin: any; +export declare const isIOS: boolean; +export declare const isMobile: boolean; +/** + * Whether we run inside a CI environment, such as + * GH actions or Azure Pipelines. + */ +export declare const isCI: boolean; +export declare const platform: Platform; +export declare const userAgent: string; +/** + * The language used for the user interface. The format of + * the string is all lower case (e.g. zh-tw for Traditional + * Chinese or de for German) + */ +export declare const language: string; +export declare namespace Language { + function value(): string; + function isDefaultVariant(): boolean; + function isDefault(): boolean; +} +/** + * Desktop: The OS locale or the locale specified by --locale or `argv.json`. + * Web: matches `platformLocale`. + * + * The UI is not necessarily shown in the provided locale. + */ +export declare const locale: string; +/** + * This will always be set to the OS/browser's locale regardless of + * what was specified otherwise. The format of the string is all + * lower case (e.g. zh-tw for Traditional Chinese). The UI is not + * necessarily shown in the provided locale. + */ +export declare const platformLocale: string; +/** + * The translations that are available through language packs. + */ +export declare const translationsConfigFile: string; +export declare const setTimeout0IsFaster: boolean; +/** + * See https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#:~:text=than%204%2C%20then-,set%20timeout%20to%204,-. + * + * Works similarly to `setTimeout(0)` but doesn't suffer from the 4ms artificial delay + * that browsers set when the nesting level is > 5. + */ +export declare const setTimeout0: (callback: () => void) => void; +export declare const enum OperatingSystem { + Windows = 1, + Macintosh = 2, + Linux = 3 +} +export declare const OS: OperatingSystem; +export declare function isLittleEndian(): boolean; +export declare const isChrome: boolean; +export declare const isFirefox: boolean; +export declare const isSafari: boolean; +export declare const isEdge: boolean; +export declare const isAndroid: boolean; +export declare function isBigSurOrNewer(osVersion: string): boolean; diff --git a/packages/core/dist/platform.js b/packages/core/dist/platform.js new file mode 100644 index 00000000..1c4b82bb --- /dev/null +++ b/packages/core/dist/platform.js @@ -0,0 +1,227 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import * as nls from './nls.js'; +export const LANGUAGE_DEFAULT = 'en'; +let _isWindows = false; +let _isMacintosh = false; +let _isLinux = false; +let _isLinuxSnap = false; +let _isNative = false; +let _isWeb = false; +let _isElectron = false; +let _isIOS = false; +let _isCI = false; +let _isMobile = false; +let _locale = undefined; +let _language = LANGUAGE_DEFAULT; +let _platformLocale = LANGUAGE_DEFAULT; +let _translationsConfigFile = undefined; +let _userAgent = undefined; +const $globalThis = globalThis; +let nodeProcess = undefined; +if (typeof $globalThis.vscode !== 'undefined' && typeof $globalThis.vscode.process !== 'undefined') { + // Native environment (sandboxed) + nodeProcess = $globalThis.vscode.process; +} +else if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') { + // Native environment (non-sandboxed) + nodeProcess = process; +} +const isElectronProcess = typeof nodeProcess?.versions?.electron === 'string'; +const isElectronRenderer = isElectronProcess && nodeProcess?.type === 'renderer'; +// Native environment +if (typeof nodeProcess === 'object') { + _isWindows = (nodeProcess.platform === 'win32'); + _isMacintosh = (nodeProcess.platform === 'darwin'); + _isLinux = (nodeProcess.platform === 'linux'); + _isLinuxSnap = _isLinux && !!nodeProcess.env['SNAP'] && !!nodeProcess.env['SNAP_REVISION']; + _isElectron = isElectronProcess; + _isCI = !!nodeProcess.env['CI'] || !!nodeProcess.env['BUILD_ARTIFACTSTAGINGDIRECTORY']; + _locale = LANGUAGE_DEFAULT; + _language = LANGUAGE_DEFAULT; + const rawNlsConfig = nodeProcess.env['VSCODE_NLS_CONFIG']; + if (rawNlsConfig) { + try { + const nlsConfig = JSON.parse(rawNlsConfig); + _locale = nlsConfig.userLocale; + _platformLocale = nlsConfig.osLocale; + _language = nlsConfig.resolvedLanguage || LANGUAGE_DEFAULT; + _translationsConfigFile = nlsConfig.languagePack?.translationsConfigFile; + } + catch (e) { + } + } + _isNative = true; +} +// Web environment +else if (typeof navigator === 'object' && !isElectronRenderer) { + _userAgent = navigator.userAgent; + _isWindows = _userAgent.indexOf('Windows') >= 0; + _isMacintosh = _userAgent.indexOf('Macintosh') >= 0; + _isIOS = (_userAgent.indexOf('Macintosh') >= 0 || _userAgent.indexOf('iPad') >= 0 || _userAgent.indexOf('iPhone') >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0; + _isLinux = _userAgent.indexOf('Linux') >= 0; + _isMobile = _userAgent?.indexOf('Mobi') >= 0; + _isWeb = true; + _language = nls.getNLSLanguage() || LANGUAGE_DEFAULT; + _locale = navigator.language.toLowerCase(); + _platformLocale = _locale; +} +// Unknown environment +else { + console.error('Unable to resolve platform.'); +} +export var Platform; +(function (Platform) { + Platform[Platform["Web"] = 0] = "Web"; + Platform[Platform["Mac"] = 1] = "Mac"; + Platform[Platform["Linux"] = 2] = "Linux"; + Platform[Platform["Windows"] = 3] = "Windows"; +})(Platform = Platform || (Platform = {})); +export function PlatformToString(platform) { + switch (platform) { + case 0 /* Platform.Web */: return 'Web'; + case 1 /* Platform.Mac */: return 'Mac'; + case 2 /* Platform.Linux */: return 'Linux'; + case 3 /* Platform.Windows */: return 'Windows'; + } +} +let _platform = 0 /* Platform.Web */; +if (_isMacintosh) { + _platform = 1 /* Platform.Mac */; +} +else if (_isWindows) { + _platform = 3 /* Platform.Windows */; +} +else if (_isLinux) { + _platform = 2 /* Platform.Linux */; +} +export const isWindows = _isWindows; +export const isMacintosh = _isMacintosh; +export const isLinux = _isLinux; +export const isLinuxSnap = _isLinuxSnap; +export const isNative = _isNative; +export const isElectron = _isElectron; +export const isWeb = _isWeb; +export const isWebWorker = (_isWeb && typeof $globalThis.importScripts === 'function'); +export const webWorkerOrigin = isWebWorker ? $globalThis.origin : undefined; +export const isIOS = _isIOS; +export const isMobile = _isMobile; +/** + * Whether we run inside a CI environment, such as + * GH actions or Azure Pipelines. + */ +export const isCI = _isCI; +export const platform = _platform; +export const userAgent = _userAgent; +/** + * The language used for the user interface. The format of + * the string is all lower case (e.g. zh-tw for Traditional + * Chinese or de for German) + */ +export const language = _language; +export var Language; +(function (Language) { + function value() { + return language; + } + Language.value = value; + function isDefaultVariant() { + if (language.length === 2) { + return language === 'en'; + } + else if (language.length >= 3) { + return language[0] === 'e' && language[1] === 'n' && language[2] === '-'; + } + else { + return false; + } + } + Language.isDefaultVariant = isDefaultVariant; + function isDefault() { + return language === 'en'; + } + Language.isDefault = isDefault; +})(Language = Language || (Language = {})); +/** + * Desktop: The OS locale or the locale specified by --locale or `argv.json`. + * Web: matches `platformLocale`. + * + * The UI is not necessarily shown in the provided locale. + */ +export const locale = _locale; +/** + * This will always be set to the OS/browser's locale regardless of + * what was specified otherwise. The format of the string is all + * lower case (e.g. zh-tw for Traditional Chinese). The UI is not + * necessarily shown in the provided locale. + */ +export const platformLocale = _platformLocale; +/** + * The translations that are available through language packs. + */ +export const translationsConfigFile = _translationsConfigFile; +export const setTimeout0IsFaster = (typeof $globalThis.postMessage === 'function' && !$globalThis.importScripts); +/** + * See https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#:~:text=than%204%2C%20then-,set%20timeout%20to%204,-. + * + * Works similarly to `setTimeout(0)` but doesn't suffer from the 4ms artificial delay + * that browsers set when the nesting level is > 5. + */ +export const setTimeout0 = (() => { + if (setTimeout0IsFaster) { + const pending = []; + $globalThis.addEventListener('message', (e) => { + if (e.data && e.data.vscodeScheduleAsyncWork) { + for (let i = 0, len = pending.length; i < len; i++) { + const candidate = pending[i]; + if (candidate.id === e.data.vscodeScheduleAsyncWork) { + pending.splice(i, 1); + candidate.callback(); + return; + } + } + } + }); + let lastId = 0; + return (callback) => { + const myId = ++lastId; + pending.push({ + id: myId, + callback: callback + }); + $globalThis.postMessage({ vscodeScheduleAsyncWork: myId }, '*'); + }; + } + return (callback) => setTimeout(callback); +})(); +export var OperatingSystem; +(function (OperatingSystem) { + OperatingSystem[OperatingSystem["Windows"] = 1] = "Windows"; + OperatingSystem[OperatingSystem["Macintosh"] = 2] = "Macintosh"; + OperatingSystem[OperatingSystem["Linux"] = 3] = "Linux"; +})(OperatingSystem = OperatingSystem || (OperatingSystem = {})); +export const OS = (_isMacintosh || _isIOS ? 2 /* OperatingSystem.Macintosh */ : (_isWindows ? 1 /* OperatingSystem.Windows */ : 3 /* OperatingSystem.Linux */)); +let _isLittleEndian = true; +let _isLittleEndianComputed = false; +export function isLittleEndian() { + if (!_isLittleEndianComputed) { + _isLittleEndianComputed = true; + const test = new Uint8Array(2); + test[0] = 1; + test[1] = 2; + const view = new Uint16Array(test.buffer); + _isLittleEndian = (view[0] === (2 << 8) + 1); + } + return _isLittleEndian; +} +export const isChrome = !!(userAgent && userAgent.indexOf('Chrome') >= 0); +export const isFirefox = !!(userAgent && userAgent.indexOf('Firefox') >= 0); +export const isSafari = !!(!isChrome && (userAgent && userAgent.indexOf('Safari') >= 0)); +export const isEdge = !!(userAgent && userAgent.indexOf('Edg/') >= 0); +export const isAndroid = !!(userAgent && userAgent.indexOf('Android') >= 0); +export function isBigSurOrNewer(osVersion) { + return parseFloat(osVersion) >= 20; +} +//# sourceMappingURL=platform.js.map \ No newline at end of file diff --git a/packages/core/dist/platform.js.map b/packages/core/dist/platform.js.map new file mode 100644 index 00000000..56e230d9 --- /dev/null +++ b/packages/core/dist/platform.js.map @@ -0,0 +1 @@ +{"version":3,"file":"platform.js","sourceRoot":"","sources":["../src/platform.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAEhC,MAAM,CAAC,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAErC,IAAI,UAAU,GAAG,KAAK,CAAC;AACvB,IAAI,YAAY,GAAG,KAAK,CAAC;AACzB,IAAI,QAAQ,GAAG,KAAK,CAAC;AACrB,IAAI,YAAY,GA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AAG,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;KAC7C;IACD,OAAO,eAAe,CAAC;AACxB,CAAC;AAED,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,SAAS,IAAI,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,CAAC,CAAC,SAAS,IAAI,SAAS,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;AAC5E,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,IAAI,CAAC,SAAS,IAAI,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACzF,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,CAAC,CAAC,SAAS,IAAI,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AACtE,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,CAAC,CAAC,SAAS,IAAI,SAAS,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;AAE5E,MAAM,UAAU,eAAe,CAAC,SAAiB;IAChD,OAAO,UAAU,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC;AACpC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/primitives.d.ts b/packages/core/dist/primitives.d.ts new file mode 100644 index 00000000..ae0cf851 --- /dev/null +++ b/packages/core/dist/primitives.d.ts @@ -0,0 +1,87 @@ +/** + * @returns whether the provided parameter is of type `Buffer` or Uint8Array dervived type + */ +export declare function isTypedArray(obj: unknown): obj is Object; +/** + * @returns whether the provided parameter is a JavaScript Array or not. + */ +export declare function isArray(array: any): array is any[]; +/** + * @returns whether the provided parameter is a JavaScript String or not. + */ +export declare function isString(str: any): str is string; +/** + * @returns whether the provided parameter is a JavaScript Array and each element in the array is a string. + */ +export declare function isStringArray(value: any): value is string[]; +/** + * + * @returns whether the provided parameter is of type `object` but **not** + * `null`, an `array`, a `regexp`, nor a `date`. + */ +export declare function isObject(obj: any): boolean; +/** + * In **contrast** to just checking `typeof` this will return `false` for `NaN`. + * @returns whether the provided parameter is a JavaScript Number or not. + */ +export declare function isNumber(obj: any): obj is number; +/** + * @returns whether the provided parameter is a JavaScript Boolean or not. + */ +export declare function isBoolean(obj: any): obj is boolean; +/** + * @returns whether the provided parameter is undefined. + */ +export declare function isUndefined(obj: any): boolean; +/** + * @returns whether the provided parameter is undefined or null. + */ +export declare function isUndefinedOrNull(obj: any): boolean; +/** + * @returns whether the provided parameter is an empty JavaScript Object or not. + */ +export declare function isEmptyObject(obj: any): obj is any; +/** + * @returns whether the provided parameter is a JavaScript Function or not. + */ +export declare function isFunction(obj: any): obj is Function; +/** + * @returns whether the provided parameters is are JavaScript Function or not. + */ +export declare function areFunctions(...objects: any[]): boolean; +export type TypeConstraint = string | Function; +export declare function validateConstraints(args: any[], constraints: TypeConstraint[]): void; +export declare function validateConstraint(arg: any, constraint: TypeConstraint): void; +/** + * Creates a new object of the provided class and will call the constructor with + * any additional argument supplied. + */ +export declare function create(ctor: Function, ...args: any[]): any; +export type IFunction0 = () => T; +export type IFunction1 = (a1: A1) => T; +export type IFunction2 = (a1: A1, a2: A2) => T; +export type IFunction3 = (a1: A1, a2: A2, a3: A3) => T; +export type IFunction4 = (a1: A1, a2: A2, a3: A3, a4: A4) => T; +export type IFunction5 = (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => T; +export type IFunction6 = (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => T; +export type IFunction7 = (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => T; +export type IFunction8 = (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => T; +export interface IAction0 extends IFunction0 { +} +export interface IAction1 extends IFunction1 { +} +export interface IAction2 extends IFunction2 { +} +export interface IAction3 extends IFunction3 { +} +export interface IAction4 extends IFunction4 { +} +export interface IAction5 extends IFunction5 { +} +export interface IAction6 extends IFunction6 { +} +export interface IAction7 extends IFunction7 { +} +export interface IAction8 extends IFunction8 { +} +export type NumberCallback = (index: number) => void; diff --git a/packages/core/dist/primitives.js b/packages/core/dist/primitives.js new file mode 100644 index 00000000..cd3d9b06 --- /dev/null +++ b/packages/core/dist/primitives.js @@ -0,0 +1,152 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +'use strict'; +const _typeof = { + number: 'number', + string: 'string', + undefined: 'undefined', + object: 'object', + function: 'function' +}; +/** + * @returns whether the provided parameter is of type `Buffer` or Uint8Array dervived type + */ +export function isTypedArray(obj) { + const TypedArray = Object.getPrototypeOf(Uint8Array); + return typeof obj === 'object' + && obj instanceof TypedArray; +} +/** + * @returns whether the provided parameter is a JavaScript Array or not. + */ +export function isArray(array) { + if (Array.isArray) { + return Array.isArray(array); + } + if (array && typeof (array.length) === _typeof.number && array.constructor === Array) { + return true; + } + return false; +} +/** + * @returns whether the provided parameter is a JavaScript String or not. + */ +export function isString(str) { + if (typeof (str) === _typeof.string || str instanceof String) { + return true; + } + return false; +} +/** + * @returns whether the provided parameter is a JavaScript Array and each element in the array is a string. + */ +export function isStringArray(value) { + return isArray(value) && (value).every(elem => isString(elem)); +} +/** + * + * @returns whether the provided parameter is of type `object` but **not** + * `null`, an `array`, a `regexp`, nor a `date`. + */ +export function isObject(obj) { + // The method can't do a type cast since there are type (like strings) which + // are subclasses of any put not positvely matched by the function. Hence type + // narrowing results in wrong results. + return typeof obj === _typeof.object + && obj !== null + && !Array.isArray(obj) + && !(obj instanceof RegExp) + && !(obj instanceof Date); +} +/** + * In **contrast** to just checking `typeof` this will return `false` for `NaN`. + * @returns whether the provided parameter is a JavaScript Number or not. + */ +export function isNumber(obj) { + if ((typeof (obj) === _typeof.number || obj instanceof Number) && !isNaN(obj)) { + return true; + } + return false; +} +/** + * @returns whether the provided parameter is a JavaScript Boolean or not. + */ +export function isBoolean(obj) { + return obj === true || obj === false; +} +/** + * @returns whether the provided parameter is undefined. + */ +export function isUndefined(obj) { + return typeof (obj) === _typeof.undefined; +} +/** + * @returns whether the provided parameter is undefined or null. + */ +export function isUndefinedOrNull(obj) { + return isUndefined(obj) || obj === null; +} +const hasOwnProperty = Object.prototype.hasOwnProperty; +/** + * @returns whether the provided parameter is an empty JavaScript Object or not. + */ +export function isEmptyObject(obj) { + if (!isObject(obj)) { + return false; + } + for (const key in obj) { + if (hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} +/** + * @returns whether the provided parameter is a JavaScript Function or not. + */ +export function isFunction(obj) { + return typeof obj === _typeof.function; +} +/** + * @returns whether the provided parameters is are JavaScript Function or not. + */ +export function areFunctions(...objects) { + return objects && objects.length > 0 && objects.every(isFunction); +} +export function validateConstraints(args, constraints) { + const len = Math.min(args.length, constraints.length); + for (let i = 0; i < len; i++) { + validateConstraint(args[i], constraints[i]); + } +} +export function validateConstraint(arg, constraint) { + if (isString(constraint)) { + if (typeof arg !== constraint) { + throw new Error(`argument does not match constraint: typeof ${constraint}`); + } + } + else if (isFunction(constraint)) { + if (arg instanceof constraint) { + return; + } + if (arg && arg.constructor === constraint) { + return; + } + if (constraint.length === 1 && constraint.call(undefined, arg) === true) { + return; + } + throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`); + } +} +/** + * Creates a new object of the provided class and will call the constructor with + * any additional argument supplied. + */ +export function create(ctor, ...args) { + const obj = Object.create(ctor.prototype); + ctor.apply(obj, args); + return obj; +} +//# sourceMappingURL=primitives.js.map \ No newline at end of file diff --git a/packages/core/dist/primitives.js.map b/packages/core/dist/primitives.js.map new file mode 100644 index 00000000..6853c024 --- /dev/null +++ b/packages/core/dist/primitives.js.map @@ -0,0 +1 @@ +{"version":3,"file":"primitives.js","sourceRoot":"","sources":["../src/primitives.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAChG,YAAY,CAAC;AAEb,MAAM,OAAO,GAAG;IACf,MAAM,EAAE,QAAQ;IAChB,MAAM,EAAE,QAAQ;IAChB,SAAS,EAAE,WAAW;IACtB,MAAM,EAAE,QAAQ;IAChB,QAAQ,EAAE,UAAU;CACpB,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,YAAY,CAAC,GAAY;IACxC,MAAM,UAAU,GAAG,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;IACrD,OAAO,OAAO,GAAG,KAAK,QAAQ;WAC1B,GAAG,YAAY,UAAU,CAAC;AAC/B,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,OAAO,CAAC,KAAU;IACjC,IAAI,KAAK,CAAC,OAAO,EAAE;QAClB,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;KAC5B;IAED,IAAI,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,OAAO,CAAC,MAAM,IAAI,KAAK,CAAC,WAAW,KAAK,KAAK,EAAE;QACrF,OAAO,IAAI,CAAC;KACZ;IAED,OAAO,KAAK,CAAC;AACd,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,QAAQ,CAAC,GAAQ;IAChC,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,OAAO,CAAC,MAAM,IAAI,GAAG,YAAY,MAAM,EAAE;QAC7D,OAAO,IAAI,CAAC;KACZ;IAED,OAAO,KAAK,CAAC;AACd,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,KAAU;IACvC,OAAO,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;A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O;SACP;QACD,MAAM,IAAI,KAAK,CAAC,2IAA2I,CAAC,CAAC;KAC7J;AACF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,MAAM,CAAC,IAAc,EAAE,GAAG,IAAW;IACpD,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC1C,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAEtB,OAAO,GAAG,CAAC;AACZ,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/process.d.ts b/packages/core/dist/process.d.ts new file mode 100644 index 00000000..4034374a --- /dev/null +++ b/packages/core/dist/process.d.ts @@ -0,0 +1,27 @@ +/** + * Provides safe access to the `cwd` property in node.js, sandboxed or web + * environments. + * + * Note: in web, this property is hardcoded to be `/`. + * + * @skipMangle + */ +export declare const cwd: () => string; +/** + * Provides safe access to the `env` property in node.js, sandboxed or web + * environments. + * + * Note: in web, this property is hardcoded to be `{}`. + */ +export declare const env: import("./platform.js").IProcessEnvironment; +/** + * Provides safe access to the `platform` property in node.js, sandboxed or web + * environments. + */ +export declare const platform: string; +/** + * Provides safe access to the `arch` method in node.js, sandboxed or web + * environments. + * Note: `arch` is `undefined` in web + */ +export declare const arch: string; diff --git a/packages/core/dist/process.js b/packages/core/dist/process.js new file mode 100644 index 00000000..83a8a80b --- /dev/null +++ b/packages/core/dist/process.js @@ -0,0 +1,65 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { isMacintosh, isWindows } from './platform.js'; +let safeProcess; +// Native sandbox environment +const vscodeGlobal = globalThis.vscode; +if (typeof vscodeGlobal !== 'undefined' && typeof vscodeGlobal.process !== 'undefined') { + const sandboxProcess = vscodeGlobal.process; + safeProcess = { + get platform() { return sandboxProcess.platform; }, + get arch() { return sandboxProcess.arch; }, + get env() { return sandboxProcess.env; }, + cwd() { return sandboxProcess.cwd(); } + }; +} +// Native node.js environment +else if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') { + safeProcess = { + get platform() { return process.platform; }, + get arch() { return process.arch; }, + get env() { return process.env; }, + cwd() { return process.env['VSCODE_CWD'] || process.cwd(); } + }; +} +// Web environment +else { + safeProcess = { + // Supported + get platform() { return isWindows ? 'win32' : isMacintosh ? 'darwin' : 'linux'; }, + get arch() { return undefined; /* arch is undefined in web */ }, + // Unsupported + get env() { return {}; }, + cwd() { return '/'; } + }; +} +/** + * Provides safe access to the `cwd` property in node.js, sandboxed or web + * environments. + * + * Note: in web, this property is hardcoded to be `/`. + * + * @skipMangle + */ +export const cwd = safeProcess.cwd; +/** + * Provides safe access to the `env` property in node.js, sandboxed or web + * environments. + * + * Note: in web, this property is hardcoded to be `{}`. + */ +export const env = safeProcess.env; +/** + * Provides safe access to the `platform` property in node.js, sandboxed or web + * environments. + */ +export const platform = safeProcess.platform; +/** + * Provides safe access to the `arch` method in node.js, sandboxed or web + * environments. + * Note: `arch` is `undefined` in web + */ +export const arch = safeProcess.arch; +//# sourceMappingURL=process.js.map \ No newline at end of file diff --git a/packages/core/dist/process.js.map b/packages/core/dist/process.js.map new file mode 100644 index 00000000..26b9036d --- /dev/null +++ b/packages/core/dist/process.js.map @@ -0,0 +1 @@ +{"version":3,"file":"process.js","sourceRoot":"","sources":["../src/process.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,WAAW,EAAE,SAAS,EAAqB,MAAM,eAAe,CAAC;AAE1E,IAAI,WAAsE,CAAC;AAG3E,6BAA6B;AAC7B,MAAM,YAAY,GAAI,UAAkB,CAAC,MAAM,CAAC;AAChD,IAAI,OAAO,YAAY,KAAK,WAAW,IAAI,OAAO,YAAY,CAAC,OAAO,KAAK,WAAW,EAAE;IACvF,MAAM,cAAc,GAAiB,YAAY,CAAC,OAAO,CAAC;IAC1D,WAAW,GAAG;QACb,IAAI,QAAQ,K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C,MAAM,GAAG,GAAG,WAAW,CAAC,GAAG,CAAC;AAEnC;;;GAGG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC;AAE7C;;;;GAIG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/resources.d.ts b/packages/core/dist/resources.d.ts new file mode 100644 index 00000000..549bf744 --- /dev/null +++ b/packages/core/dist/resources.d.ts @@ -0,0 +1,187 @@ +import { URI } from './uri.js'; +export declare function originalFSPath(uri: URI): string; +export interface IExtUri { + /** + * Compares two uris. + * + * @param uri1 Uri + * @param uri2 Uri + * @param ignoreFragment Ignore the fragment (defaults to `false`) + */ + compare(uri1: URI, uri2: URI, ignoreFragment?: boolean): number; + /** + * Tests whether two uris are equal + * + * @param uri1 Uri + * @param uri2 Uri + * @param ignoreFragment Ignore the fragment (defaults to `false`) + */ + isEqual(uri1: URI | undefined, uri2: URI | undefined, ignoreFragment?: boolean): boolean; + /** + * Tests whether a `candidate` URI is a parent or equal of a given `base` URI. + * + * @param base A uri which is "longer" or at least same length as `parentCandidate` + * @param parentCandidate A uri which is "shorter" or up to same length as `base` + * @param ignoreFragment Ignore the fragment (defaults to `false`) + */ + isEqualOrParent(base: URI, parentCandidate: URI, ignoreFragment?: boolean): boolean; + /** + * Creates a key from a resource URI to be used to resource comparison and for resource maps. + * @see {@link ResourceMap} + * @param uri Uri + * @param ignoreFragment Ignore the fragment (defaults to `false`) + */ + getComparisonKey(uri: URI, ignoreFragment?: boolean): string; + /** + * Whether the casing of the path-component of the uri should be ignored. + */ + ignorePathCasing(uri: URI): boolean; + basenameOrAuthority(resource: URI): string; + /** + * Returns the basename of the path component of an uri. + * @param resource + */ + basename(resource: URI): string; + /** + * Returns the extension of the path component of an uri. + * @param resource + */ + extname(resource: URI): string; + /** + * Return a URI representing the directory of a URI path. + * + * @param resource The input URI. + * @returns The URI representing the directory of the input URI. + */ + dirname(resource: URI): URI; + /** + * Join a URI path with path fragments and normalizes the resulting path. + * + * @param resource The input URI. + * @param pathFragment The path fragment to add to the URI path. + * @returns The resulting URI. + */ + joinPath(resource: URI, ...pathFragment: string[]): URI; + /** + * Normalizes the path part of a URI: Resolves `.` and `..` elements with directory names. + * + * @param resource The URI to normalize the path. + * @returns The URI with the normalized path. + */ + normalizePath(resource: URI): URI; + /** + * + * @param from + * @param to + */ + relativePath(from: URI, to: URI): string | undefined; + /** + * Resolves an absolute or relative path against a base URI. + * The path can be relative or absolute posix or a Windows path + */ + resolvePath(base: URI, path: string): URI; + /** + * Returns true if the URI path is absolute. + */ + isAbsolutePath(resource: URI): boolean; + /** + * Tests whether the two authorities are the same + */ + isEqualAuthority(a1: string, a2: string): boolean; + /** + * Returns true if the URI path has a trailing path separator + */ + hasTrailingPathSeparator(resource: URI, sep?: string): boolean; + /** + * Removes a trailing path separator, if there's one. + * Important: Doesn't remove the first slash, it would make the URI invalid + */ + removeTrailingPathSeparator(resource: URI, sep?: string): URI; + /** + * Adds a trailing path separator to the URI if there isn't one already. + * For example, c:\ would be unchanged, but c:\users would become c:\users\ + */ + addTrailingPathSeparator(resource: URI, sep?: string): URI; +} +export declare class ExtUri implements IExtUri { + private _ignorePathCasing; + constructor(_ignorePathCasing: (uri: URI) => boolean); + compare(uri1: URI, uri2: URI, ignoreFragment?: boolean): number; + isEqual(uri1: URI | undefined, uri2: URI | undefined, ignoreFragment?: boolean): boolean; + getComparisonKey(uri: URI, ignoreFragment?: boolean): string; + ignorePathCasing(uri: URI): boolean; + isEqualOrParent(base: URI, parentCandidate: URI, ignoreFragment?: boolean): boolean; + joinPath(resource: URI, ...pathFragment: string[]): URI; + basenameOrAuthority(resource: URI): string; + basename(resource: URI): string; + extname(resource: URI): string; + dirname(resource: URI): URI; + normalizePath(resource: URI): URI; + relativePath(from: URI, to: URI): string | undefined; + resolvePath(base: URI, path: string): URI; + isAbsolutePath(resource: URI): boolean; + isEqualAuthority(a1: string | undefined, a2: string | undefined): boolean; + hasTrailingPathSeparator(resource: URI, sep?: string): boolean; + removeTrailingPathSeparator(resource: URI, sep?: string): URI; + addTrailingPathSeparator(resource: URI, sep?: string): URI; +} +/** + * Unbiased utility that takes uris "as they are". This means it can be interchanged with + * uri#toString() usages. The following is true + * ``` + * assertEqual(aUri.toString() === bUri.toString(), exturi.isEqual(aUri, bUri)) + * ``` + */ +export declare const extUri: ExtUri; +/** + * BIASED utility that _mostly_ ignored the case of urs paths. ONLY use this util if you + * understand what you are doing. + * + * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged. + * + * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient + * because those uris come from a "trustworthy source". When creating unknown uris it's always + * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path + * casing matters. + */ +export declare const extUriBiasedIgnorePathCase: ExtUri; +/** + * BIASED utility that always ignores the casing of uris paths. ONLY use this util if you + * understand what you are doing. + * + * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged. + * + * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient + * because those uris come from a "trustworthy source". When creating unknown uris it's always + * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path + * casing matters. + */ +export declare const extUriIgnorePathCase: ExtUri; +export declare const isEqual: any; +export declare const isEqualOrParent: any; +export declare const getComparisonKey: any; +export declare const basenameOrAuthority: any; +export declare const basename: any; +export declare const extname: any; +export declare const dirname: any; +export declare const joinPath: any; +export declare const normalizePath: any; +export declare const relativePath: any; +export declare const resolvePath: any; +export declare const isAbsolutePath: any; +export declare const isEqualAuthority: any; +export declare const hasTrailingPathSeparator: any; +export declare const removeTrailingPathSeparator: any; +export declare const addTrailingPathSeparator: any; +export declare function distinctParents(items: T[], resourceAccessor: (item: T) => URI): T[]; +/** + * Data URI related helpers. + */ +export declare namespace DataUri { + const META_DATA_LABEL = "label"; + const META_DATA_DESCRIPTION = "description"; + const META_DATA_SIZE = "size"; + const META_DATA_MIME = "mime"; + function parseMetaData(dataUri: URI): Map; +} +export declare function toLocalResource(resource: URI, authority: string | undefined, localScheme: string): URI; diff --git a/packages/core/dist/resources.js b/packages/core/dist/resources.js new file mode 100644 index 00000000..7fa1e78c --- /dev/null +++ b/packages/core/dist/resources.js @@ -0,0 +1,288 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import * as extpath from './extpath.js'; +import { Schemas } from './network.js'; +import * as paths from './path.js'; +import { isLinux, isWindows } from './platform.js'; +import { compare as strCompare, equalsIgnoreCase } from './strings.js'; +import { URI, uriToFsPath } from './uri.js'; +export function originalFSPath(uri) { + return uriToFsPath(uri, true); +} +export class ExtUri { + _ignorePathCasing; + constructor(_ignorePathCasing) { + this._ignorePathCasing = _ignorePathCasing; + } + compare(uri1, uri2, ignoreFragment = false) { + if (uri1 === uri2) { + return 0; + } + return strCompare(this.getComparisonKey(uri1, ignoreFragment), this.getComparisonKey(uri2, ignoreFragment)); + } + isEqual(uri1, uri2, ignoreFragment = false) { + if (uri1 === uri2) { + return true; + } + if (!uri1 || !uri2) { + return false; + } + return this.getComparisonKey(uri1, ignoreFragment) === this.getComparisonKey(uri2, ignoreFragment); + } + getComparisonKey(uri, ignoreFragment = false) { + return uri.with({ + path: this._ignorePathCasing(uri) ? uri.path.toLowerCase() : undefined, + fragment: ignoreFragment ? null : undefined + }).toString(); + } + ignorePathCasing(uri) { + return this._ignorePathCasing(uri); + } + isEqualOrParent(base, parentCandidate, ignoreFragment = false) { + if (base.scheme === parentCandidate.scheme) { + if (base.scheme === Schemas.file) { + return extpath.isEqualOrParent(originalFSPath(base), originalFSPath(parentCandidate), this._ignorePathCasing(base)) && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment); + } + if (isEqualAuthority(base.authority, parentCandidate.authority)) { + return extpath.isEqualOrParent(base.path, parentCandidate.path, this._ignorePathCasing(base), '/') && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment); + } + } + return false; + } + // --- path math + joinPath(resource, ...pathFragment) { + return URI.joinPath(resource, ...pathFragment); + } + basenameOrAuthority(resource) { + return basename(resource) || resource.authority; + } + basename(resource) { + return paths.posix.basename(resource.path); + } + extname(resource) { + return paths.posix.extname(resource.path); + } + dirname(resource) { + if (resource.path.length === 0) { + return resource; + } + let dirname; + if (resource.scheme === Schemas.file) { + dirname = URI.file(paths.dirname(originalFSPath(resource))).path; + } + else { + dirname = paths.posix.dirname(resource.path); + if (resource.authority && dirname.length && dirname.charCodeAt(0) !== 47 /* CharCode.Slash */) { + console.error(`dirname("${resource.toString})) resulted in a relative path`); + dirname = '/'; // If a URI contains an authority component, then the path component must either be empty or begin with a CharCode.Slash ("/") character + } + } + return resource.with({ + path: dirname + }); + } + normalizePath(resource) { + if (!resource.path.length) { + return resource; + } + let normalizedPath; + if (resource.scheme === Schemas.file) { + normalizedPath = URI.file(paths.normalize(originalFSPath(resource))).path; + } + else { + normalizedPath = paths.posix.normalize(resource.path); + } + return resource.with({ + path: normalizedPath + }); + } + relativePath(from, to) { + if (from.scheme !== to.scheme || !isEqualAuthority(from.authority, to.authority)) { + return undefined; + } + if (from.scheme === Schemas.file) { + const relativePath = paths.relative(originalFSPath(from), originalFSPath(to)); + return isWindows ? extpath.toSlashes(relativePath) : relativePath; + } + let fromPath = from.path || '/'; + const toPath = to.path || '/'; + if (this._ignorePathCasing(from)) { + // make casing of fromPath match toPath + let i = 0; + for (const len = Math.min(fromPath.length, toPath.length); i < len; i++) { + if (fromPath.charCodeAt(i) !== toPath.charCodeAt(i)) { + if (fromPath.charAt(i).toLowerCase() !== toPath.charAt(i).toLowerCase()) { + break; + } + } + } + fromPath = toPath.substr(0, i) + fromPath.substr(i); + } + return paths.posix.relative(fromPath, toPath); + } + resolvePath(base, path) { + if (base.scheme === Schemas.file) { + const newURI = URI.file(paths.resolve(originalFSPath(base), path)); + return base.with({ + authority: newURI.authority, + path: newURI.path + }); + } + path = extpath.toPosixPath(path); // we allow path to be a windows path + return base.with({ + path: paths.posix.resolve(base.path, path) + }); + } + // --- misc + isAbsolutePath(resource) { + return !!resource.path && resource.path[0] === '/'; + } + isEqualAuthority(a1, a2) { + return a1 === a2 || (a1 !== undefined && a2 !== undefined && equalsIgnoreCase(a1, a2)); + } + hasTrailingPathSeparator(resource, sep = paths.sep) { + if (resource.scheme === Schemas.file) { + const fsp = originalFSPath(resource); + return fsp.length > extpath.getRoot(fsp).length && fsp[fsp.length - 1] === sep; + } + else { + const p = resource.path; + return (p.length > 1 && p.charCodeAt(p.length - 1) === 47 /* CharCode.Slash */) && !(/^[a-zA-Z]:(\/$|\\$)/.test(resource.fsPath)); // ignore the slash at offset 0 + } + } + removeTrailingPathSeparator(resource, sep = paths.sep) { + // Make sure that the path isn't a drive letter. A trailing separator there is not removable. + if (hasTrailingPathSeparator(resource, sep)) { + return resource.with({ path: resource.path.substr(0, resource.path.length - 1) }); + } + return resource; + } + addTrailingPathSeparator(resource, sep = paths.sep) { + let isRootSep = false; + if (resource.scheme === Schemas.file) { + const fsp = originalFSPath(resource); + isRootSep = ((fsp !== undefined) && (fsp.length === extpath.getRoot(fsp).length) && (fsp[fsp.length - 1] === sep)); + } + else { + sep = '/'; + const p = resource.path; + isRootSep = p.length === 1 && p.charCodeAt(p.length - 1) === 47 /* CharCode.Slash */; + } + if (!isRootSep && !hasTrailingPathSeparator(resource, sep)) { + return resource.with({ path: resource.path + '/' }); + } + return resource; + } +} +/** + * Unbiased utility that takes uris "as they are". This means it can be interchanged with + * uri#toString() usages. The following is true + * ``` + * assertEqual(aUri.toString() === bUri.toString(), exturi.isEqual(aUri, bUri)) + * ``` + */ +export const extUri = new ExtUri(() => false); +/** + * BIASED utility that _mostly_ ignored the case of urs paths. ONLY use this util if you + * understand what you are doing. + * + * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged. + * + * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient + * because those uris come from a "trustworthy source". When creating unknown uris it's always + * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path + * casing matters. + */ +export const extUriBiasedIgnorePathCase = new ExtUri(uri => { + // A file scheme resource is in the same platform as code, so ignore case for non linux platforms + // Resource can be from another platform. Lowering the case as an hack. Should come from File system provider + return uri.scheme === Schemas.file ? !isLinux : true; +}); +/** + * BIASED utility that always ignores the casing of uris paths. ONLY use this util if you + * understand what you are doing. + * + * This utility is INCOMPATIBLE with `uri.toString()`-usages and both CANNOT be used interchanged. + * + * When dealing with uris from files or documents, `extUri` (the unbiased friend)is sufficient + * because those uris come from a "trustworthy source". When creating unknown uris it's always + * better to use `IUriIdentityService` which exposes an `IExtUri`-instance which knows when path + * casing matters. + */ +export const extUriIgnorePathCase = new ExtUri(_ => true); +export const isEqual = extUri.isEqual.bind(extUri); +export const isEqualOrParent = extUri.isEqualOrParent.bind(extUri); +export const getComparisonKey = extUri.getComparisonKey.bind(extUri); +export const basenameOrAuthority = extUri.basenameOrAuthority.bind(extUri); +export const basename = extUri.basename.bind(extUri); +export const extname = extUri.extname.bind(extUri); +export const dirname = extUri.dirname.bind(extUri); +export const joinPath = extUri.joinPath.bind(extUri); +export const normalizePath = extUri.normalizePath.bind(extUri); +export const relativePath = extUri.relativePath.bind(extUri); +export const resolvePath = extUri.resolvePath.bind(extUri); +export const isAbsolutePath = extUri.isAbsolutePath.bind(extUri); +export const isEqualAuthority = extUri.isEqualAuthority.bind(extUri); +export const hasTrailingPathSeparator = extUri.hasTrailingPathSeparator.bind(extUri); +export const removeTrailingPathSeparator = extUri.removeTrailingPathSeparator.bind(extUri); +export const addTrailingPathSeparator = extUri.addTrailingPathSeparator.bind(extUri); +//#endregion +export function distinctParents(items, resourceAccessor) { + const distinctParents = []; + for (let i = 0; i < items.length; i++) { + const candidateResource = resourceAccessor(items[i]); + if (items.some((otherItem, index) => { + if (index === i) { + return false; + } + return isEqualOrParent(candidateResource, resourceAccessor(otherItem)); + })) { + continue; + } + distinctParents.push(items[i]); + } + return distinctParents; +} +/** + * Data URI related helpers. + */ +export var DataUri; +(function (DataUri) { + DataUri.META_DATA_LABEL = 'label'; + DataUri.META_DATA_DESCRIPTION = 'description'; + DataUri.META_DATA_SIZE = 'size'; + DataUri.META_DATA_MIME = 'mime'; + function parseMetaData(dataUri) { + const metadata = new Map(); + // Given a URI of: data:image/png;size:2313;label:SomeLabel;description:SomeDescription;base64,77+9UE5... + // the metadata is: size:2313;label:SomeLabel;description:SomeDescription + const meta = dataUri.path.substring(dataUri.path.indexOf(';') + 1, dataUri.path.lastIndexOf(';')); + meta.split(';').forEach(property => { + const [key, value] = property.split(':'); + if (key && value) { + metadata.set(key, value); + } + }); + // Given a URI of: data:image/png;size:2313;label:SomeLabel;description:SomeDescription;base64,77+9UE5... + // the mime is: image/png + const mime = dataUri.path.substring(0, dataUri.path.indexOf(';')); + if (mime) { + metadata.set(DataUri.META_DATA_MIME, mime); + } + return metadata; + } + DataUri.parseMetaData = parseMetaData; +})(DataUri = DataUri || (DataUri = {})); +export function toLocalResource(resource, authority, localScheme) { + if (authority) { + let path = resource.path; + if (path && path[0] !== paths.posix.sep) { + path = paths.posix.sep + path; + } + return resource.with({ scheme: localScheme, authority, path }); + } + return resource.with({ scheme: localScheme }); +} +//# sourceMappingURL=resources.js.map \ No newline at end of file diff --git a/packages/core/dist/resources.js.map b/packages/core/dist/resources.js.map new file mode 100644 index 00000000..17d7121d --- /dev/null +++ b/packages/core/dist/resources.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resources.js","sourceRoot":"","sources":["../src/resources.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAGhG,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,KAAK,KAAK,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe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S,EAAE,IAAI,EAAE,CAAC,CAAC;KAC/D;IAED,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC/C,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/sequence.d.ts b/packages/core/dist/sequence.d.ts new file mode 100644 index 00000000..fb18d215 --- /dev/null +++ b/packages/core/dist/sequence.d.ts @@ -0,0 +1,19 @@ +import { Event } from './event.js'; +export interface ISplice { + readonly start: number; + readonly deleteCount: number; + readonly toInsert: readonly T[]; +} +export interface ISpliceable { + splice(start: number, deleteCount: number, toInsert: readonly T[]): void; +} +export interface ISequence { + readonly elements: T[]; + readonly onDidSplice: Event>; +} +export declare class Sequence implements ISequence, ISpliceable { + readonly elements: T[]; + private readonly _onDidSplice; + readonly onDidSplice: Event>; + splice(start: number, deleteCount: number, toInsert?: readonly T[]): void; +} diff --git a/packages/core/dist/sequence.js b/packages/core/dist/sequence.js new file mode 100644 index 00000000..528c33d0 --- /dev/null +++ b/packages/core/dist/sequence.js @@ -0,0 +1,15 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { Emitter } from './event.js'; +export class Sequence { + elements = []; + _onDidSplice = new Emitter(); + onDidSplice = this._onDidSplice.event; + splice(start, deleteCount, toInsert = []) { + this.elements.splice(start, deleteCount, ...toInsert); + this._onDidSplice.fire({ start, deleteCount, toInsert }); + } +} +//# sourceMappingURL=sequence.js.map \ No newline at end of file diff --git a/packages/core/dist/sequence.js.map b/packages/core/dist/sequence.js.map new file mode 100644 index 00000000..44a305bf --- /dev/null +++ b/packages/core/dist/sequence.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sequence.js","sourceRoot":"","sources":["../src/sequence.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,OAAO,EAAS,MAAM,YAAY,CAAC;AAiB5C,MAAM,OAAO,QAAQ;IAEX,QAAQ,GAAQ,EAAE,CAAC;IAEX,YAAY,GAAG,IAAI,OAAO,EAAc,CAAC;IACjD,WAAW,GAAsB,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC;IAElE,MAAM,CAAC,KAAa,EAAE,WAAmB,EAAE,WAAyB,EAAE;QACrE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,WAAW,EAAE,GAAG,QAAQ,CAAC,CAAC;QACtD,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC1D,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/set.d.ts b/packages/core/dist/set.d.ts new file mode 100644 index 00000000..d29d1269 --- /dev/null +++ b/packages/core/dist/set.d.ts @@ -0,0 +1,9 @@ +export declare class ArraySet { + private _elements; + constructor(elements?: T[]); + get size(): number; + set(element: T): void; + contains(element: T): boolean; + unset(element: T): void; + get elements(): T[]; +} diff --git a/packages/core/dist/set.js b/packages/core/dist/set.js new file mode 100644 index 00000000..a7c7afa0 --- /dev/null +++ b/packages/core/dist/set.js @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +export class ArraySet { + _elements; + constructor(elements = []) { + this._elements = elements.slice(); + } + get size() { + return this._elements.length; + } + set(element) { + this.unset(element); + this._elements.push(element); + } + contains(element) { + return this._elements.includes(element); + } + unset(element) { + const index = this._elements.indexOf(element); + if (index > -1) { + this._elements.splice(index, 1); + } + } + get elements() { + return this._elements.slice(); + } +} +//# sourceMappingURL=set.js.map \ No newline at end of file diff --git a/packages/core/dist/set.js.map b/packages/core/dist/set.js.map new file mode 100644 index 00000000..278d2a76 --- /dev/null +++ b/packages/core/dist/set.js.map @@ -0,0 +1 @@ +{"version":3,"file":"set.js","sourceRoot":"","sources":["../src/set.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,MAAM,OAAO,QAAQ;IAEZ,SAAS,CAAM;IAEvB,YAAY,WAAgB,EAAE;QAC7B,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC,KAAK,EAAE,CAAC;IACnC,CAAC;IAED,IAAI,IAAI;QACP,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;IAC9B,CAAC;IAED,GAAG,CAAC,OAAU;QACb,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACpB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC9B,CAAC;IAED,QAAQ,CAAC,OAAU;QAClB,OAAO,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,OAAU;QACf,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAE9C,IAAI,KAAK,GAAG,CAAC,CAAC,EAAE;YACf,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;SAChC;IACF,CAAC;IAED,IAAI,QAAQ;QACX,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/stopwatch.d.ts b/packages/core/dist/stopwatch.d.ts new file mode 100644 index 00000000..875ca075 --- /dev/null +++ b/packages/core/dist/stopwatch.d.ts @@ -0,0 +1,10 @@ +export declare class StopWatch { + private _startTime; + private _stopTime; + private readonly _now; + static create(highResolution?: boolean): StopWatch; + constructor(highResolution?: boolean); + stop(): void; + reset(): void; + elapsed(): number; +} diff --git a/packages/core/dist/stopwatch.js b/packages/core/dist/stopwatch.js new file mode 100644 index 00000000..9d5adf39 --- /dev/null +++ b/packages/core/dist/stopwatch.js @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +const hasPerformanceNow = (globalThis.performance && typeof globalThis.performance.now === 'function'); +export class StopWatch { + _startTime; + _stopTime; + _now; + static create(highResolution) { + return new StopWatch(highResolution); + } + constructor(highResolution) { + this._now = hasPerformanceNow && highResolution === false ? Date.now : globalThis.performance.now.bind(globalThis.performance); + this._startTime = this._now(); + this._stopTime = -1; + } + stop() { + this._stopTime = this._now(); + } + reset() { + this._startTime = this._now(); + this._stopTime = -1; + } + elapsed() { + if (this._stopTime !== -1) { + return this._stopTime - this._startTime; + } + return this._now() - this._startTime; + } +} +//# sourceMappingURL=stopwatch.js.map \ No newline at end of file diff --git a/packages/core/dist/stopwatch.js.map b/packages/core/dist/stopwatch.js.map new file mode 100644 index 00000000..cca4ff9c --- /dev/null +++ b/packages/core/dist/stopwatch.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stopwatch.js","sourceRoot":"","sources":["../src/stopwatch.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAKhG,MAAM,iBAAiB,GAAG,CAAC,UAAU,CAAC,WAAW,IAAI,OAAO,UAAU,CAAC,WAAW,CAAC,GAAG,KAAK,UAAU,CAAC,CAAC;AAEvG,MAAM,OAAO,SAAS;IAEb,UAAU,CAAS;IACnB,SAAS,CAAS;IAET,IAAI,CAAe;IAE7B,MAAM,CAAC,MAAM,CAAC,cAAwB;QAC5C,OAAO,IAAI,SAAS,CAAC,cAAc,CAAC,CAAC;IACtC,CAAC;IAED,YAAY,cAAwB;QACnC,IAAI,CAAC,IAAI,GAAG,iBAAiB,IAAI,cAAc,KAAK,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,UAAU,CAAC,WAAY,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;QAChI,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;IACrB,CAAC;IAEM,IAAI;QACV,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAC9B,CAAC;IAEM,KAAK;QACX,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC;IACrB,CAAC;IAEM,OAAO;QACb,IAAI,IAAI,CAAC,SAAS,KAAK,CAAC,CAAC,EAAE;YAC1B,OAAO,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC;SACxC;QACD,OAAO,IAAI,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,UAAU,CAAC;IACtC,CAAC;CACD"} \ No newline at end of file diff --git a/packages/core/dist/strings.d.ts b/packages/core/dist/strings.d.ts new file mode 100644 index 00000000..eac02178 --- /dev/null +++ b/packages/core/dist/strings.d.ts @@ -0,0 +1,259 @@ +export declare const empty = ""; +export declare const substitute: (template: any, map: any) => any; +export declare const substituteAlt: (template: any, map: any) => any; +export declare function isFalsyOrWhitespace(str: string | undefined): boolean; +/** + * Helper to produce a string with a variable number of arguments. Insert variable segments + * into the string using the {n} notation where N is the index of the argument following the string. + * @param value string to which formatting is applied + * @param args replacements for {n}-entries + */ +export declare function format(value: string, ...args: any[]): string; +/** + * Helper to create a string from a template and a string record. + * Similar to `format` but with objects instead of positional arguments. + */ +export declare function format2(template: string, values: Record): string; +/** + * Encodes the given value so that it can be used as literal value in html attributes. + * + * In other words, computes `$val`, such that `attr` in `
` has the runtime value `value`. + * This prevents XSS injection. + */ +export declare function htmlAttributeEncodeValue(value: string): string; +/** + * Converts HTML characters inside the string to use entities instead. Makes the string safe from + * being used e.g. in HTMLElement.innerHTML. + */ +export declare function escape(html: string): string; +/** + * Escapes regular expression characters in a given string + */ +export declare function escapeRegExpCharacters(value: string): string; +/** + * Counts how often `substr` occurs inside `value`. + */ +export declare function count(value: string, substr: string): number; +export declare function truncate(value: string, maxLength: number, suffix?: string): string; +export declare function truncateMiddle(value: string, maxLength: number, suffix?: string): string; +/** + * Removes all occurrences of needle from the beginning and end of haystack. + * @param haystack string to trim + * @param needle the thing to trim (default is a blank) + */ +export declare function trim(haystack: string, needle?: string): string; +/** + * Removes all occurrences of needle from the beginning of haystack. + * @param haystack string to trim + * @param needle the thing to trim + */ +export declare function ltrim(haystack: string, needle: string): string; +/** + * Removes all occurrences of needle from the end of haystack. + * @param haystack string to trim + * @param needle the thing to trim + */ +export declare function rtrim(haystack: string, needle: string): string; +export declare function convertSimple2RegExpPattern(pattern: string): string; +export declare function stripWildcards(pattern: string): string; +export interface RegExpOptions { + matchCase?: boolean; + wholeWord?: boolean; + multiline?: boolean; + global?: boolean; + unicode?: boolean; +} +export declare function createRegExp(searchString: string, isRegex: boolean, options?: RegExpOptions): RegExp; +export declare function regExpLeadsToEndlessLoop(regexp: RegExp): boolean; +export declare function joinStrings(items: (string | undefined | null | false)[], separator: string): string; +export declare function splitLines(str: string): string[]; +export declare function splitLinesIncludeSeparators(str: string): string[]; +/** + * Returns first index of the string that is not whitespace. + * If string is empty or contains only whitespaces, returns -1 + */ +export declare function firstNonWhitespaceIndex(str: string): number; +/** + * Returns the leading whitespace of the string. + * If the string contains only whitespaces, returns entire string + */ +export declare function getLeadingWhitespace(str: string, start?: number, end?: number): string; +/** + * Returns last index of the string that is not whitespace. + * If string is empty or contains only whitespaces, returns -1 + */ +export declare function lastNonWhitespaceIndex(str: string, startIndex?: number): number; +export declare function getIndentationLength(str: string): number; +/** + * Function that works identically to String.prototype.replace, except, the + * replace function is allowed to be async and return a Promise. + */ +export declare function replaceAsync(str: string, search: RegExp, replacer: (match: string, ...args: any[]) => Promise): Promise; +export declare function compare(a: string, b: string): number; +export declare function compareSubstring(a: string, b: string, aStart?: number, aEnd?: number, bStart?: number, bEnd?: number): number; +export declare function compareIgnoreCase(a: string, b: string): number; +export declare function compareSubstringIgnoreCase(a: string, b: string, aStart?: number, aEnd?: number, bStart?: number, bEnd?: number): number; +export declare function isAsciiDigit(code: number): boolean; +export declare function isLowerAsciiLetter(code: number): boolean; +export declare function isUpperAsciiLetter(code: number): boolean; +export declare function equalsIgnoreCase(a: string, b: string): boolean; +export declare function startsWithIgnoreCase(str: string, candidate: string): boolean; +/** + * @returns the length of the common prefix of the two strings. + */ +export declare function commonPrefixLength(a: string, b: string): number; +/** + * @returns the length of the common suffix of the two strings. + */ +export declare function commonSuffixLength(a: string, b: string): number; +/** + * See http://en.wikipedia.org/wiki/Surrogate_pair + */ +export declare function isHighSurrogate(charCode: number): boolean; +/** + * See http://en.wikipedia.org/wiki/Surrogate_pair + */ +export declare function isLowSurrogate(charCode: number): boolean; +/** + * See http://en.wikipedia.org/wiki/Surrogate_pair + */ +export declare function computeCodePoint(highSurrogate: number, lowSurrogate: number): number; +/** + * get the code point that begins at offset `offset` + */ +export declare function getNextCodePoint(str: string, len: number, offset: number): number; +export declare class CodePointIterator { + private readonly _str; + private readonly _len; + private _offset; + get offset(): number; + constructor(str: string, offset?: number); + setOffset(offset: number): void; + prevCodePoint(): number; + nextCodePoint(): number; + eol(): boolean; +} +export declare class GraphemeIterator { + private readonly _iterator; + get offset(): number; + constructor(str: string, offset?: number); + nextGraphemeLength(): number; + prevGraphemeLength(): number; + eol(): boolean; +} +export declare function nextCharLength(str: string, initialOffset: number): number; +export declare function prevCharLength(str: string, initialOffset: number): number; +export declare function getCharContainingOffset(str: string, offset: number): [number, number]; +export declare function charCount(str: string): number; +/** + * Returns true if `str` contains any Unicode character that is classified as "R" or "AL". + */ +export declare function containsRTL(str: string): boolean; +/** + * Returns true if `str` contains only basic ASCII characters in the range 32 - 126 (including 32 and 126) or \n, \r, \t + */ +export declare function isBasicASCII(str: string): boolean; +export declare const UNUSUAL_LINE_TERMINATORS: RegExp; +/** + * Returns true if `str` contains unusual line terminators, like LS or PS + */ +export declare function containsUnusualLineTerminators(str: string): boolean; +export declare function isFullWidthCharacter(charCode: number): boolean; +/** + * A fast function (therefore imprecise) to check if code points are emojis. + * Generated using https://github.com/alexdima/unicode-utils/blob/main/emoji-test.js + */ +export declare function isEmojiImprecise(x: number): boolean; +/** + * Given a string and a max length returns a shorted version. Shorting + * happens at favorable positions - such as whitespace or punctuation characters. + * The return value can be longer than the given value of `n`. Leading whitespace is always trimmed. + */ +export declare function lcut(text: string, n: number, prefix?: string): string; +/** Iterates over parts of a string with CSI sequences */ +export declare function forAnsiStringParts(str: string): Generator<{ + isCode: boolean; + str: string; +}, void, unknown>; +/** + * Strips ANSI escape sequences from a string. + * @param str The dastringa stringo strip the ANSI escape sequences from. + * + * @example + * removeAnsiEscapeCodes('\u001b[31mHello, World!\u001b[0m'); + * // 'Hello, World!' + */ +export declare function removeAnsiEscapeCodes(str: string): string; +/** + * Strips ANSI escape sequences from a UNIX-style prompt string (eg. `$PS1`). + * @param str The string to strip the ANSI escape sequences from. + * + * @example + * removeAnsiEscapeCodesFromPrompt('\n\\[\u001b[01;34m\\]\\w\\[\u001b[00m\\]\n\\[\u001b[1;32m\\]> \\[\u001b[0m\\]'); + * // '\n\\w\n> ' + */ +export declare function removeAnsiEscapeCodesFromPrompt(str: string): string; +export declare const UTF8_BOM_CHARACTER: string; +export declare function startsWithUTF8BOM(str: string): boolean; +export declare function stripUTF8BOM(str: string): string; +/** + * Checks if the characters of the provided query string are included in the + * target string. The characters do not have to be contiguous within the string. + */ +export declare function fuzzyContains(target: string, query: string): boolean; +export declare function containsUppercaseCharacter(target: string, ignoreEscapedChars?: boolean): boolean; +export declare function uppercaseFirstLetter(str: string): string; +export declare function getNLines(str: string, n?: number): string; +/** + * Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc. + */ +export declare function singleLetterHash(n: number): string; +export declare function getGraphemeBreakType(codePoint: number): GraphemeBreakType; +export declare const enum GraphemeBreakType { + Other = 0, + Prepend = 1, + CR = 2, + LF = 3, + Control = 4, + Extend = 5, + Regional_Indicator = 6, + SpacingMark = 7, + L = 8, + V = 9, + T = 10, + LV = 11, + LVT = 12, + ZWJ = 13, + Extended_Pictographic = 14 +} +/** + * Computes the offset after performing a left delete on the given string, + * while considering unicode grapheme/emoji rules. +*/ +export declare function getLeftDeleteOffset(offset: number, str: string): number; +export declare const noBreakWhitespace = "\u00A0"; +export declare class AmbiguousCharacters { + private readonly confusableDictionary; + private static readonly ambiguousCharacterData; + private static readonly cache; + static getInstance(locales: Set): AmbiguousCharacters; + private static _locales; + static getLocales(): string[]; + private constructor(); + isAmbiguous(codePoint: number): boolean; + containsAmbiguousCharacter(str: string): boolean; + /** + * Returns the non basic ASCII code point that the given code point can be confused, + * or undefined if such code point does note exist. + */ + getPrimaryConfusable(codePoint: number): number | undefined; + getConfusableCodePoints(): ReadonlySet; +} +export declare class InvisibleCharacters { + private static getRawData; + private static _data; + private static getData; + static isInvisibleCharacter(codePoint: number): boolean; + static containsInvisibleCharacter(str: string): boolean; + static get codePoints(): ReadonlySet; +} diff --git a/packages/core/dist/strings.js b/packages/core/dist/strings.js new file mode 100644 index 00000000..fc2819af --- /dev/null +++ b/packages/core/dist/strings.js @@ -0,0 +1,1100 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +'use strict'; +export const empty = ''; +import { REGEX_VAR, REGEX_VAR_ALT } from "./constants.js"; +export const substitute = (template, map) => { + const transform = (k) => k || ''; + return template.replace(REGEX_VAR, (match, key, format) => transform(map[key]).toString()); +}; +export const substituteAlt = (template, map) => { + const transform = (k) => k || ''; + return template.replace(REGEX_VAR_ALT, (match, key, format) => transform(map[key]).toString()); +}; +import { LRUCachedFunction } from './cache.js'; +import { Lazy } from './lazy.js'; +export function isFalsyOrWhitespace(str) { + if (!str || typeof str !== 'string') { + return true; + } + return str.trim().length === 0; +} +const _formatRegexp = /{(\d+)}/g; +/** + * Helper to produce a string with a variable number of arguments. Insert variable segments + * into the string using the {n} notation where N is the index of the argument following the string. + * @param value string to which formatting is applied + * @param args replacements for {n}-entries + */ +export function format(value, ...args) { + if (args.length === 0) { + return value; + } + return value.replace(_formatRegexp, function (match, group) { + const idx = parseInt(group, 10); + return isNaN(idx) || idx < 0 || idx >= args.length ? + match : + args[idx]; + }); +} +const _format2Regexp = /{([^}]+)}/g; +/** + * Helper to create a string from a template and a string record. + * Similar to `format` but with objects instead of positional arguments. + */ +export function format2(template, values) { + if (Object.keys(values).length === 0) { + return template; + } + return template.replace(_format2Regexp, (match, group) => (values[group] ?? match)); +} +/** + * Encodes the given value so that it can be used as literal value in html attributes. + * + * In other words, computes `$val`, such that `attr` in `
` has the runtime value `value`. + * This prevents XSS injection. + */ +export function htmlAttributeEncodeValue(value) { + return value.replace(/[<>"'&]/g, ch => { + switch (ch) { + case '<': return '<'; + case '>': return '>'; + case '"': return '"'; + case '\'': return '''; + case '&': return '&'; + } + return ch; + }); +} +/** + * Converts HTML characters inside the string to use entities instead. Makes the string safe from + * being used e.g. in HTMLElement.innerHTML. + */ +export function escape(html) { + return html.replace(/[<>&]/g, function (match) { + switch (match) { + case '<': return '<'; + case '>': return '>'; + case '&': return '&'; + default: return match; + } + }); +} +/** + * Escapes regular expression characters in a given string + */ +export function escapeRegExpCharacters(value) { + return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, '\\$&'); +} +/** + * Counts how often `substr` occurs inside `value`. + */ +export function count(value, substr) { + let result = 0; + let index = value.indexOf(substr); + while (index !== -1) { + result++; + index = value.indexOf(substr, index + substr.length); + } + return result; +} +export function truncate(value, maxLength, suffix = '…') { + if (value.length <= maxLength) { + return value; + } + return `${value.substr(0, maxLength)}${suffix}`; +} +export function truncateMiddle(value, maxLength, suffix = '…') { + if (value.length <= maxLength) { + return value; + } + const prefixLength = Math.ceil(maxLength / 2) - suffix.length / 2; + const suffixLength = Math.floor(maxLength / 2) - suffix.length / 2; + return `${value.substr(0, prefixLength)}${suffix}${value.substr(value.length - suffixLength)}`; +} +/** + * Removes all occurrences of needle from the beginning and end of haystack. + * @param haystack string to trim + * @param needle the thing to trim (default is a blank) + */ +export function trim(haystack, needle = ' ') { + const trimmed = ltrim(haystack, needle); + return rtrim(trimmed, needle); +} +/** + * Removes all occurrences of needle from the beginning of haystack. + * @param haystack string to trim + * @param needle the thing to trim + */ +export function ltrim(haystack, needle) { + if (!haystack || !needle) { + return haystack; + } + const needleLen = needle.length; + if (needleLen === 0 || haystack.length === 0) { + return haystack; + } + let offset = 0; + while (haystack.indexOf(needle, offset) === offset) { + offset = offset + needleLen; + } + return haystack.substring(offset); +} +/** + * Removes all occurrences of needle from the end of haystack. + * @param haystack string to trim + * @param needle the thing to trim + */ +export function rtrim(haystack, needle) { + if (!haystack || !needle) { + return haystack; + } + const needleLen = needle.length, haystackLen = haystack.length; + if (needleLen === 0 || haystackLen === 0) { + return haystack; + } + let offset = haystackLen, idx = -1; + while (true) { + idx = haystack.lastIndexOf(needle, offset - 1); + if (idx === -1 || idx + needleLen !== offset) { + break; + } + if (idx === 0) { + return ''; + } + offset = idx; + } + return haystack.substring(0, offset); +} +export function convertSimple2RegExpPattern(pattern) { + return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*'); +} +export function stripWildcards(pattern) { + return pattern.replace(/\*/g, ''); +} +export function createRegExp(searchString, isRegex, options = {}) { + if (!searchString) { + throw new Error('Cannot create regex from empty string'); + } + if (!isRegex) { + searchString = escapeRegExpCharacters(searchString); + } + if (options.wholeWord) { + if (!/\B/.test(searchString.charAt(0))) { + searchString = '\\b' + searchString; + } + if (!/\B/.test(searchString.charAt(searchString.length - 1))) { + searchString = searchString + '\\b'; + } + } + let modifiers = ''; + if (options.global) { + modifiers += 'g'; + } + if (!options.matchCase) { + modifiers += 'i'; + } + if (options.multiline) { + modifiers += 'm'; + } + if (options.unicode) { + modifiers += 'u'; + } + return new RegExp(searchString, modifiers); +} +export function regExpLeadsToEndlessLoop(regexp) { + // Exit early if it's one of these special cases which are meant to match + // against an empty string + if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\s*$') { + return false; + } + // We check against an empty string. If the regular expression doesn't advance + // (e.g. ends in an endless loop) it will match an empty string. + const match = regexp.exec(''); + return !!(match && regexp.lastIndex === 0); +} +export function joinStrings(items, separator) { + return items.filter(item => item !== undefined && item !== null && item !== false).join(separator); +} +export function splitLines(str) { + return str.split(/\r\n|\r|\n/); +} +export function splitLinesIncludeSeparators(str) { + const linesWithSeparators = []; + const splitLinesAndSeparators = str.split(/(\r\n|\r|\n)/); + for (let i = 0; i < Math.ceil(splitLinesAndSeparators.length / 2); i++) { + linesWithSeparators.push(splitLinesAndSeparators[2 * i] + (splitLinesAndSeparators[2 * i + 1] ?? '')); + } + return linesWithSeparators; +} +/** + * Returns first index of the string that is not whitespace. + * If string is empty or contains only whitespaces, returns -1 + */ +export function firstNonWhitespaceIndex(str) { + for (let i = 0, len = str.length; i < len; i++) { + const chCode = str.charCodeAt(i); + if (chCode !== 32 /* CharCode.Space */ && chCode !== 9 /* CharCode.Tab */) { + return i; + } + } + return -1; +} +/** + * Returns the leading whitespace of the string. + * If the string contains only whitespaces, returns entire string + */ +export function getLeadingWhitespace(str, start = 0, end = str.length) { + for (let i = start; i < end; i++) { + const chCode = str.charCodeAt(i); + if (chCode !== 32 /* CharCode.Space */ && chCode !== 9 /* CharCode.Tab */) { + return str.substring(start, i); + } + } + return str.substring(start, end); +} +/** + * Returns last index of the string that is not whitespace. + * If string is empty or contains only whitespaces, returns -1 + */ +export function lastNonWhitespaceIndex(str, startIndex = str.length - 1) { + for (let i = startIndex; i >= 0; i--) { + const chCode = str.charCodeAt(i); + if (chCode !== 32 /* CharCode.Space */ && chCode !== 9 /* CharCode.Tab */) { + return i; + } + } + return -1; +} +export function getIndentationLength(str) { + const idx = firstNonWhitespaceIndex(str); + if (idx === -1) { + return str.length; + } + return idx; +} +/** + * Function that works identically to String.prototype.replace, except, the + * replace function is allowed to be async and return a Promise. + */ +export function replaceAsync(str, search, replacer) { + const parts = []; + let last = 0; + for (const match of str.matchAll(search)) { + parts.push(str.slice(last, match.index)); + if (match.index === undefined) { + throw new Error('match.index should be defined'); + } + last = match.index + match[0].length; + parts.push(replacer(match[0], ...match.slice(1), match.index, str, match.groups)); + } + parts.push(str.slice(last)); + return Promise.all(parts).then(p => p.join('')); +} +export function compare(a, b) { + if (a < b) { + return -1; + } + else if (a > b) { + return 1; + } + else { + return 0; + } +} +export function compareSubstring(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) { + for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) { + const codeA = a.charCodeAt(aStart); + const codeB = b.charCodeAt(bStart); + if (codeA < codeB) { + return -1; + } + else if (codeA > codeB) { + return 1; + } + } + const aLen = aEnd - aStart; + const bLen = bEnd - bStart; + if (aLen < bLen) { + return -1; + } + else if (aLen > bLen) { + return 1; + } + return 0; +} +export function compareIgnoreCase(a, b) { + return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length); +} +export function compareSubstringIgnoreCase(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) { + for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) { + let codeA = a.charCodeAt(aStart); + let codeB = b.charCodeAt(bStart); + if (codeA === codeB) { + // equal + continue; + } + if (codeA >= 128 || codeB >= 128) { + // not ASCII letters -> fallback to lower-casing strings + return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd); + } + // mapper lower-case ascii letter onto upper-case varinats + // [97-122] (lower ascii) --> [65-90] (upper ascii) + if (isLowerAsciiLetter(codeA)) { + codeA -= 32; + } + if (isLowerAsciiLetter(codeB)) { + codeB -= 32; + } + // compare both code points + const diff = codeA - codeB; + if (diff === 0) { + continue; + } + return diff; + } + const aLen = aEnd - aStart; + const bLen = bEnd - bStart; + if (aLen < bLen) { + return -1; + } + else if (aLen > bLen) { + return 1; + } + return 0; +} +export function isAsciiDigit(code) { + return code >= 48 /* CharCode.Digit0 */ && code <= 57 /* CharCode.Digit9 */; +} +export function isLowerAsciiLetter(code) { + return code >= 97 /* CharCode.a */ && code <= 122 /* CharCode.z */; +} +export function isUpperAsciiLetter(code) { + return code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */; +} +export function equalsIgnoreCase(a, b) { + return a.length === b.length && compareSubstringIgnoreCase(a, b) === 0; +} +export function startsWithIgnoreCase(str, candidate) { + const candidateLength = candidate.length; + if (candidate.length > str.length) { + return false; + } + return compareSubstringIgnoreCase(str, candidate, 0, candidateLength) === 0; +} +/** + * @returns the length of the common prefix of the two strings. + */ +export function commonPrefixLength(a, b) { + const len = Math.min(a.length, b.length); + let i; + for (i = 0; i < len; i++) { + if (a.charCodeAt(i) !== b.charCodeAt(i)) { + return i; + } + } + return len; +} +/** + * @returns the length of the common suffix of the two strings. + */ +export function commonSuffixLength(a, b) { + const len = Math.min(a.length, b.length); + let i; + const aLastIndex = a.length - 1; + const bLastIndex = b.length - 1; + for (i = 0; i < len; i++) { + if (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) { + return i; + } + } + return len; +} +/** + * See http://en.wikipedia.org/wiki/Surrogate_pair + */ +export function isHighSurrogate(charCode) { + return (0xD800 <= charCode && charCode <= 0xDBFF); +} +/** + * See http://en.wikipedia.org/wiki/Surrogate_pair + */ +export function isLowSurrogate(charCode) { + return (0xDC00 <= charCode && charCode <= 0xDFFF); +} +/** + * See http://en.wikipedia.org/wiki/Surrogate_pair + */ +export function computeCodePoint(highSurrogate, lowSurrogate) { + return ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000; +} +/** + * get the code point that begins at offset `offset` + */ +export function getNextCodePoint(str, len, offset) { + const charCode = str.charCodeAt(offset); + if (isHighSurrogate(charCode) && offset + 1 < len) { + const nextCharCode = str.charCodeAt(offset + 1); + if (isLowSurrogate(nextCharCode)) { + return computeCodePoint(charCode, nextCharCode); + } + } + return charCode; +} +/** + * get the code point that ends right before offset `offset` + */ +function getPrevCodePoint(str, offset) { + const charCode = str.charCodeAt(offset - 1); + if (isLowSurrogate(charCode) && offset > 1) { + const prevCharCode = str.charCodeAt(offset - 2); + if (isHighSurrogate(prevCharCode)) { + return computeCodePoint(prevCharCode, charCode); + } + } + return charCode; +} +export class CodePointIterator { + _str; + _len; + _offset; + get offset() { + return this._offset; + } + constructor(str, offset = 0) { + this._str = str; + this._len = str.length; + this._offset = offset; + } + setOffset(offset) { + this._offset = offset; + } + prevCodePoint() { + const codePoint = getPrevCodePoint(this._str, this._offset); + this._offset -= (codePoint >= 65536 /* Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); + return codePoint; + } + nextCodePoint() { + const codePoint = getNextCodePoint(this._str, this._len, this._offset); + this._offset += (codePoint >= 65536 /* Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN */ ? 2 : 1); + return codePoint; + } + eol() { + return (this._offset >= this._len); + } +} +export class GraphemeIterator { + _iterator; + get offset() { + return this._iterator.offset; + } + constructor(str, offset = 0) { + this._iterator = new CodePointIterator(str, offset); + } + nextGraphemeLength() { + const graphemeBreakTree = GraphemeBreakTree.getInstance(); + const iterator = this._iterator; + const initialOffset = iterator.offset; + let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint()); + while (!iterator.eol()) { + const offset = iterator.offset; + const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint()); + if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) { + // move iterator back + iterator.setOffset(offset); + break; + } + graphemeBreakType = nextGraphemeBreakType; + } + return (iterator.offset - initialOffset); + } + prevGraphemeLength() { + const graphemeBreakTree = GraphemeBreakTree.getInstance(); + const iterator = this._iterator; + const initialOffset = iterator.offset; + let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint()); + while (iterator.offset > 0) { + const offset = iterator.offset; + const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint()); + if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) { + // move iterator back + iterator.setOffset(offset); + break; + } + graphemeBreakType = prevGraphemeBreakType; + } + return (initialOffset - iterator.offset); + } + eol() { + return this._iterator.eol(); + } +} +export function nextCharLength(str, initialOffset) { + const iterator = new GraphemeIterator(str, initialOffset); + return iterator.nextGraphemeLength(); +} +export function prevCharLength(str, initialOffset) { + const iterator = new GraphemeIterator(str, initialOffset); + return iterator.prevGraphemeLength(); +} +export function getCharContainingOffset(str, offset) { + if (offset > 0 && isLowSurrogate(str.charCodeAt(offset))) { + offset--; + } + const endOffset = offset + nextCharLength(str, offset); + const startOffset = endOffset - prevCharLength(str, endOffset); + return [startOffset, endOffset]; +} +export function charCount(str) { + const iterator = new GraphemeIterator(str); + let length = 0; + while (!iterator.eol()) { + length++; + iterator.nextGraphemeLength(); + } + return length; +} +let CONTAINS_RTL = undefined; +function makeContainsRtl() { + // Generated using https://github.com/alexdima/unicode-utils/blob/main/rtl-test.js + return /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDC7\uFDF0-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE35\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDD23\uDE80-\uDEA9\uDEAD-\uDF45\uDF51-\uDF81\uDF86-\uDFF6]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD4B-\uDFFF]|\uD83B[\uDC00-\uDEBB])/; +} +/** + * Returns true if `str` contains any Unicode character that is classified as "R" or "AL". + */ +export function containsRTL(str) { + if (!CONTAINS_RTL) { + CONTAINS_RTL = makeContainsRtl(); + } + return CONTAINS_RTL.test(str); +} +const IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/; +/** + * Returns true if `str` contains only basic ASCII characters in the range 32 - 126 (including 32 and 126) or \n, \r, \t + */ +export function isBasicASCII(str) { + return IS_BASIC_ASCII.test(str); +} +export const UNUSUAL_LINE_TERMINATORS = /[\u2028\u2029]/; // LINE SEPARATOR (LS) or PARAGRAPH SEPARATOR (PS) +/** + * Returns true if `str` contains unusual line terminators, like LS or PS + */ +export function containsUnusualLineTerminators(str) { + return UNUSUAL_LINE_TERMINATORS.test(str); +} +export function isFullWidthCharacter(charCode) { + // Do a cheap trick to better support wrapping of wide characters, treat them as 2 columns + // http://jrgraphix.net/research/unicode_blocks.php + // 2E80 - 2EFF CJK Radicals Supplement + // 2F00 - 2FDF Kangxi Radicals + // 2FF0 - 2FFF Ideographic Description Characters + // 3000 - 303F CJK Symbols and Punctuation + // 3040 - 309F Hiragana + // 30A0 - 30FF Katakana + // 3100 - 312F Bopomofo + // 3130 - 318F Hangul Compatibility Jamo + // 3190 - 319F Kanbun + // 31A0 - 31BF Bopomofo Extended + // 31F0 - 31FF Katakana Phonetic Extensions + // 3200 - 32FF Enclosed CJK Letters and Months + // 3300 - 33FF CJK Compatibility + // 3400 - 4DBF CJK Unified Ideographs Extension A + // 4DC0 - 4DFF Yijing Hexagram Symbols + // 4E00 - 9FFF CJK Unified Ideographs + // A000 - A48F Yi Syllables + // A490 - A4CF Yi Radicals + // AC00 - D7AF Hangul Syllables + // [IGNORE] D800 - DB7F High Surrogates + // [IGNORE] DB80 - DBFF High Private Use Surrogates + // [IGNORE] DC00 - DFFF Low Surrogates + // [IGNORE] E000 - F8FF Private Use Area + // F900 - FAFF CJK Compatibility Ideographs + // [IGNORE] FB00 - FB4F Alphabetic Presentation Forms + // [IGNORE] FB50 - FDFF Arabic Presentation Forms-A + // [IGNORE] FE00 - FE0F Variation Selectors + // [IGNORE] FE20 - FE2F Combining Half Marks + // [IGNORE] FE30 - FE4F CJK Compatibility Forms + // [IGNORE] FE50 - FE6F Small Form Variants + // [IGNORE] FE70 - FEFF Arabic Presentation Forms-B + // FF00 - FFEF Halfwidth and Fullwidth Forms + // [https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms] + // of which FF01 - FF5E fullwidth ASCII of 21 to 7E + // [IGNORE] and FF65 - FFDC halfwidth of Katakana and Hangul + // [IGNORE] FFF0 - FFFF Specials + return ((charCode >= 0x2E80 && charCode <= 0xD7AF) + || (charCode >= 0xF900 && charCode <= 0xFAFF) + || (charCode >= 0xFF01 && charCode <= 0xFF5E)); +} +/** + * A fast function (therefore imprecise) to check if code points are emojis. + * Generated using https://github.com/alexdima/unicode-utils/blob/main/emoji-test.js + */ +export function isEmojiImprecise(x) { + return ((x >= 0x1F1E6 && x <= 0x1F1FF) || (x === 8986) || (x === 8987) || (x === 9200) + || (x === 9203) || (x >= 9728 && x <= 10175) || (x === 11088) || (x === 11093) + || (x >= 127744 && x <= 128591) || (x >= 128640 && x <= 128764) + || (x >= 128992 && x <= 129008) || (x >= 129280 && x <= 129535) + || (x >= 129648 && x <= 129782)); +} +/** + * Given a string and a max length returns a shorted version. Shorting + * happens at favorable positions - such as whitespace or punctuation characters. + * The return value can be longer than the given value of `n`. Leading whitespace is always trimmed. + */ +export function lcut(text, n, prefix = '') { + const trimmed = text.trimStart(); + if (trimmed.length < n) { + return trimmed; + } + const re = /\b/g; + let i = 0; + while (re.test(trimmed)) { + if (trimmed.length - re.lastIndex < n) { + break; + } + i = re.lastIndex; + re.lastIndex += 1; + } + if (i === 0) { + return trimmed; + } + return prefix + trimmed.substring(i).trimStart(); +} +// Escape codes, compiled from https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_ +// Plus additional markers for custom `\x1b]...\x07` instructions. +const CSI_SEQUENCE = /(?:(?:\x1b\[|\x9B)[=?>!]?[\d;:]*["$#'* ]?[a-zA-Z@^`{}|~])|(:?\x1b\].*?\x07)/g; +/** Iterates over parts of a string with CSI sequences */ +export function* forAnsiStringParts(str) { + let last = 0; + for (const match of str.matchAll(CSI_SEQUENCE)) { + if (last !== match.index) { + yield { isCode: false, str: str.substring(last, match.index) }; + } + yield { isCode: true, str: match[0] }; + last = match.index + match[0].length; + } + if (last !== str.length) { + yield { isCode: false, str: str.substring(last) }; + } +} +/** + * Strips ANSI escape sequences from a string. + * @param str The dastringa stringo strip the ANSI escape sequences from. + * + * @example + * removeAnsiEscapeCodes('\u001b[31mHello, World!\u001b[0m'); + * // 'Hello, World!' + */ +export function removeAnsiEscapeCodes(str) { + if (str) { + str = str.replace(CSI_SEQUENCE, ''); + } + return str; +} +const PROMPT_NON_PRINTABLE = /\\\[.*?\\\]/g; +/** + * Strips ANSI escape sequences from a UNIX-style prompt string (eg. `$PS1`). + * @param str The string to strip the ANSI escape sequences from. + * + * @example + * removeAnsiEscapeCodesFromPrompt('\n\\[\u001b[01;34m\\]\\w\\[\u001b[00m\\]\n\\[\u001b[1;32m\\]> \\[\u001b[0m\\]'); + * // '\n\\w\n> ' + */ +export function removeAnsiEscapeCodesFromPrompt(str) { + return removeAnsiEscapeCodes(str).replace(PROMPT_NON_PRINTABLE, ''); +} +// -- UTF-8 BOM +export const UTF8_BOM_CHARACTER = String.fromCharCode(65279 /* CharCode.UTF8_BOM */); +export function startsWithUTF8BOM(str) { + return !!(str && str.length > 0 && str.charCodeAt(0) === 65279 /* CharCode.UTF8_BOM */); +} +export function stripUTF8BOM(str) { + return startsWithUTF8BOM(str) ? str.substr(1) : str; +} +/** + * Checks if the characters of the provided query string are included in the + * target string. The characters do not have to be contiguous within the string. + */ +export function fuzzyContains(target, query) { + if (!target || !query) { + return false; // return early if target or query are undefined + } + if (target.length < query.length) { + return false; // impossible for query to be contained in target + } + const queryLen = query.length; + const targetLower = target.toLowerCase(); + let index = 0; + let lastIndexOf = -1; + while (index < queryLen) { + const indexOf = targetLower.indexOf(query[index], lastIndexOf + 1); + if (indexOf < 0) { + return false; + } + lastIndexOf = indexOf; + index++; + } + return true; +} +export function containsUppercaseCharacter(target, ignoreEscapedChars = false) { + if (!target) { + return false; + } + if (ignoreEscapedChars) { + target = target.replace(/\\./g, ''); + } + return target.toLowerCase() !== target; +} +export function uppercaseFirstLetter(str) { + return str.charAt(0).toUpperCase() + str.slice(1); +} +export function getNLines(str, n = 1) { + if (n === 0) { + return ''; + } + let idx = -1; + do { + idx = str.indexOf('\n', idx + 1); + n--; + } while (n > 0 && idx >= 0); + if (idx === -1) { + return str; + } + if (str[idx - 1] === '\r') { + idx--; + } + return str.substr(0, idx); +} +/** + * Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc. + */ +export function singleLetterHash(n) { + const LETTERS_CNT = (90 /* CharCode.Z */ - 65 /* CharCode.A */ + 1); + n = n % (2 * LETTERS_CNT); + if (n < LETTERS_CNT) { + return String.fromCharCode(97 /* CharCode.a */ + n); + } + return String.fromCharCode(65 /* CharCode.A */ + n - LETTERS_CNT); +} +//#region Unicode Grapheme Break +export function getGraphemeBreakType(codePoint) { + const graphemeBreakTree = GraphemeBreakTree.getInstance(); + return graphemeBreakTree.getGraphemeBreakType(codePoint); +} +function breakBetweenGraphemeBreakType(breakTypeA, breakTypeB) { + // http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules + // !!! Let's make the common case a bit faster + if (breakTypeA === 0 /* GraphemeBreakType.Other */) { + // see https://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakTest-13.0.0d10.html#table + return (breakTypeB !== 5 /* GraphemeBreakType.Extend */ && breakTypeB !== 7 /* GraphemeBreakType.SpacingMark */); + } + // Do not break between a CR and LF. Otherwise, break before and after controls. + // GB3 CR × LF + // GB4 (Control | CR | LF) ÷ + // GB5 ÷ (Control | CR | LF) + if (breakTypeA === 2 /* GraphemeBreakType.CR */) { + if (breakTypeB === 3 /* GraphemeBreakType.LF */) { + return false; // GB3 + } + } + if (breakTypeA === 4 /* GraphemeBreakType.Control */ || breakTypeA === 2 /* GraphemeBreakType.CR */ || breakTypeA === 3 /* GraphemeBreakType.LF */) { + return true; // GB4 + } + if (breakTypeB === 4 /* GraphemeBreakType.Control */ || breakTypeB === 2 /* GraphemeBreakType.CR */ || breakTypeB === 3 /* GraphemeBreakType.LF */) { + return true; // GB5 + } + // Do not break Hangul syllable sequences. + // GB6 L × (L | V | LV | LVT) + // GB7 (LV | V) × (V | T) + // GB8 (LVT | T) × T + if (breakTypeA === 8 /* GraphemeBreakType.L */) { + if (breakTypeB === 8 /* GraphemeBreakType.L */ || breakTypeB === 9 /* GraphemeBreakType.V */ || breakTypeB === 11 /* GraphemeBreakType.LV */ || breakTypeB === 12 /* GraphemeBreakType.LVT */) { + return false; // GB6 + } + } + if (breakTypeA === 11 /* GraphemeBreakType.LV */ || breakTypeA === 9 /* GraphemeBreakType.V */) { + if (breakTypeB === 9 /* GraphemeBreakType.V */ || breakTypeB === 10 /* GraphemeBreakType.T */) { + return false; // GB7 + } + } + if (breakTypeA === 12 /* GraphemeBreakType.LVT */ || breakTypeA === 10 /* GraphemeBreakType.T */) { + if (breakTypeB === 10 /* GraphemeBreakType.T */) { + return false; // GB8 + } + } + // Do not break before extending characters or ZWJ. + // GB9 × (Extend | ZWJ) + if (breakTypeB === 5 /* GraphemeBreakType.Extend */ || breakTypeB === 13 /* GraphemeBreakType.ZWJ */) { + return false; // GB9 + } + // The GB9a and GB9b rules only apply to extended grapheme clusters: + // Do not break before SpacingMarks, or after Prepend characters. + // GB9a × SpacingMark + // GB9b Prepend × + if (breakTypeB === 7 /* GraphemeBreakType.SpacingMark */) { + return false; // GB9a + } + if (breakTypeA === 1 /* GraphemeBreakType.Prepend */) { + return false; // GB9b + } + // Do not break within emoji modifier sequences or emoji zwj sequences. + // GB11 \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic} + if (breakTypeA === 13 /* GraphemeBreakType.ZWJ */ && breakTypeB === 14 /* GraphemeBreakType.Extended_Pictographic */) { + // Note: we are not implementing the rule entirely here to avoid introducing states + return false; // GB11 + } + // GB12 sot (RI RI)* RI × RI + // GB13 [^RI] (RI RI)* RI × RI + if (breakTypeA === 6 /* GraphemeBreakType.Regional_Indicator */ && breakTypeB === 6 /* GraphemeBreakType.Regional_Indicator */) { + // Note: we are not implementing the rule entirely here to avoid introducing states + return false; // GB12 & GB13 + } + // GB999 Any ÷ Any + return true; +} +export var GraphemeBreakType; +(function (GraphemeBreakType) { + GraphemeBreakType[GraphemeBreakType["Other"] = 0] = "Other"; + GraphemeBreakType[GraphemeBreakType["Prepend"] = 1] = "Prepend"; + GraphemeBreakType[GraphemeBreakType["CR"] = 2] = "CR"; + GraphemeBreakType[GraphemeBreakType["LF"] = 3] = "LF"; + GraphemeBreakType[GraphemeBreakType["Control"] = 4] = "Control"; + GraphemeBreakType[GraphemeBreakType["Extend"] = 5] = "Extend"; + GraphemeBreakType[GraphemeBreakType["Regional_Indicator"] = 6] = "Regional_Indicator"; + GraphemeBreakType[GraphemeBreakType["SpacingMark"] = 7] = "SpacingMark"; + GraphemeBreakType[GraphemeBreakType["L"] = 8] = "L"; + GraphemeBreakType[GraphemeBreakType["V"] = 9] = "V"; + GraphemeBreakType[GraphemeBreakType["T"] = 10] = "T"; + GraphemeBreakType[GraphemeBreakType["LV"] = 11] = "LV"; + GraphemeBreakType[GraphemeBreakType["LVT"] = 12] = "LVT"; + GraphemeBreakType[GraphemeBreakType["ZWJ"] = 13] = "ZWJ"; + GraphemeBreakType[GraphemeBreakType["Extended_Pictographic"] = 14] = "Extended_Pictographic"; +})(GraphemeBreakType = GraphemeBreakType || (GraphemeBreakType = {})); +class GraphemeBreakTree { + static _INSTANCE = null; + static getInstance() { + if (!GraphemeBreakTree._INSTANCE) { + GraphemeBreakTree._INSTANCE = new GraphemeBreakTree(); + } + return GraphemeBreakTree._INSTANCE; + } + _data; + constructor() { + this._data = getGraphemeBreakRawData(); + } + getGraphemeBreakType(codePoint) { + // !!! Let's make 7bit ASCII a bit faster: 0..31 + if (codePoint < 32) { + if (codePoint === 10 /* CharCode.LineFeed */) { + return 3 /* GraphemeBreakType.LF */; + } + if (codePoint === 13 /* CharCode.CarriageReturn */) { + return 2 /* GraphemeBreakType.CR */; + } + return 4 /* GraphemeBreakType.Control */; + } + // !!! Let's make 7bit ASCII a bit faster: 32..126 + if (codePoint < 127) { + return 0 /* GraphemeBreakType.Other */; + } + const data = this._data; + const nodeCount = data.length / 3; + let nodeIndex = 1; + while (nodeIndex <= nodeCount) { + if (codePoint < data[3 * nodeIndex]) { + // go left + nodeIndex = 2 * nodeIndex; + } + else if (codePoint > data[3 * nodeIndex + 1]) { + // go right + nodeIndex = 2 * nodeIndex + 1; + } + else { + // hit + return data[3 * nodeIndex + 2]; + } + } + return 0 /* GraphemeBreakType.Other */; + } +} +function getGraphemeBreakRawData() { + // generated using https://github.com/alexdima/unicode-utils/blob/main/grapheme-break.js + return JSON.parse('[0,0,0,51229,51255,12,44061,44087,12,127462,127487,6,7083,7085,5,47645,47671,12,54813,54839,12,128678,128678,14,3270,3270,5,9919,9923,14,45853,45879,12,49437,49463,12,53021,53047,12,71216,71218,7,128398,128399,14,129360,129374,14,2519,2519,5,4448,4519,9,9742,9742,14,12336,12336,14,44957,44983,12,46749,46775,12,48541,48567,12,50333,50359,12,52125,52151,12,53917,53943,12,69888,69890,5,73018,73018,5,127990,127990,14,128558,128559,14,128759,128760,14,129653,129655,14,2027,2035,5,2891,2892,7,3761,3761,5,6683,6683,5,8293,8293,4,9825,9826,14,9999,9999,14,43452,43453,5,44509,44535,12,45405,45431,12,46301,46327,12,47197,47223,12,48093,48119,12,48989,49015,12,49885,49911,12,50781,50807,12,51677,51703,12,52573,52599,12,53469,53495,12,54365,54391,12,65279,65279,4,70471,70472,7,72145,72147,7,119173,119179,5,127799,127818,14,128240,128244,14,128512,128512,14,128652,128652,14,128721,128722,14,129292,129292,14,129445,129450,14,129734,129743,14,1476,1477,5,2366,2368,7,2750,2752,7,3076,3076,5,3415,3415,5,4141,4144,5,6109,6109,5,6964,6964,5,7394,7400,5,9197,9198,14,9770,9770,14,9877,9877,14,9968,9969,14,10084,10084,14,43052,43052,5,43713,43713,5,44285,44311,12,44733,44759,12,45181,45207,12,45629,45655,12,46077,46103,12,46525,46551,12,46973,46999,12,47421,47447,12,47869,47895,12,48317,48343,12,48765,48791,12,49213,49239,12,49661,49687,12,50109,50135,12,50557,50583,12,51005,51031,12,51453,51479,12,51901,51927,12,52349,52375,12,52797,52823,12,53245,53271,12,53693,53719,12,54141,54167,12,54589,54615,12,55037,55063,12,69506,69509,5,70191,70193,5,70841,70841,7,71463,71467,5,72330,72342,5,94031,94031,5,123628,123631,5,127763,127765,14,127941,127941,14,128043,128062,14,128302,128317,14,128465,128467,14,128539,128539,14,128640,128640,14,128662,128662,14,128703,128703,14,128745,128745,14,129004,129007,14,129329,129330,14,129402,129402,14,129483,129483,14,129686,129704,14,130048,131069,14,173,173,4,1757,1757,1,2200,2207,5,2434,2435,7,2631,2632,5,2817,2817,5,3008,3008,5,3201,3201,5,3387,3388,5,3542,3542,5,3902,3903,7,4190,4192,5,6002,6003,5,6439,6440,5,6765,6770,7,7019,7027,5,7154,7155,7,8205,8205,13,8505,8505,14,9654,9654,14,9757,9757,14,9792,9792,14,9852,9853,14,9890,9894,14,9937,9937,14,9981,9981,14,10035,10036,14,11035,11036,14,42654,42655,5,43346,43347,7,43587,43587,5,44006,44007,7,44173,44199,12,44397,44423,12,44621,44647,12,44845,44871,12,45069,45095,12,45293,45319,12,45517,45543,12,45741,45767,12,45965,45991,12,46189,46215,12,46413,46439,12,46637,46663,12,46861,46887,12,47085,47111,12,47309,47335,12,47533,47559,12,47757,47783,12,47981,48007,12,48205,48231,12,48429,48455,12,48653,48679,12,48877,48903,12,49101,49127,12,49325,49351,12,49549,49575,12,49773,49799,12,49997,50023,12,50221,50247,12,50445,50471,12,50669,50695,12,50893,50919,12,51117,51143,12,51341,51367,12,51565,51591,12,51789,51815,12,52013,52039,12,52237,52263,12,52461,52487,12,52685,52711,12,52909,52935,12,53133,53159,12,53357,53383,12,53581,53607,12,53805,53831,12,54029,54055,12,54253,54279,12,54477,54503,12,54701,54727,12,54925,54951,12,55149,55175,12,68101,68102,5,69762,69762,7,70067,70069,7,70371,70378,5,70720,70721,7,71087,71087,5,71341,71341,5,71995,71996,5,72249,72249,7,72850,72871,5,73109,73109,5,118576,118598,5,121505,121519,5,127245,127247,14,127568,127569,14,127777,127777,14,127872,127891,14,127956,127967,14,128015,128016,14,128110,128172,14,128259,128259,14,128367,128368,14,128424,128424,14,128488,128488,14,128530,128532,14,128550,128551,14,128566,128566,14,128647,128647,14,128656,128656,14,128667,128673,14,128691,128693,14,128715,128715,14,128728,128732,14,128752,128752,14,128765,128767,14,129096,129103,14,129311,129311,14,129344,129349,14,129394,129394,14,129413,129425,14,129466,129471,14,129511,129535,14,129664,129666,14,129719,129722,14,129760,129767,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2307,2307,7,2382,2383,7,2497,2500,5,2563,2563,7,2677,2677,5,2763,2764,7,2879,2879,5,2914,2915,5,3021,3021,5,3142,3144,5,3263,3263,5,3285,3286,5,3398,3400,7,3530,3530,5,3633,3633,5,3864,3865,5,3974,3975,5,4155,4156,7,4229,4230,5,5909,5909,7,6078,6085,7,6277,6278,5,6451,6456,7,6744,6750,5,6846,6846,5,6972,6972,5,7074,7077,5,7146,7148,7,7222,7223,5,7416,7417,5,8234,8238,4,8417,8417,5,9000,9000,14,9203,9203,14,9730,9731,14,9748,9749,14,9762,9763,14,9776,9783,14,9800,9811,14,9831,9831,14,9872,9873,14,9882,9882,14,9900,9903,14,9929,9933,14,9941,9960,14,9974,9974,14,9989,9989,14,10006,10006,14,10062,10062,14,10160,10160,14,11647,11647,5,12953,12953,14,43019,43019,5,43232,43249,5,43443,43443,5,43567,43568,7,43696,43696,5,43765,43765,7,44013,44013,5,44117,44143,12,44229,44255,12,44341,44367,12,44453,44479,12,44565,44591,12,44677,44703,12,44789,44815,12,44901,44927,12,45013,45039,12,45125,45151,12,45237,45263,12,45349,45375,12,45461,45487,12,45573,45599,12,45685,45711,12,45797,45823,12,45909,45935,12,46021,46047,12,46133,46159,12,46245,46271,12,46357,46383,12,46469,46495,12,46581,46607,12,46693,46719,12,46805,46831,12,46917,46943,12,47029,47055,12,47141,47167,12,47253,47279,12,47365,47391,12,47477,47503,12,47589,47615,12,47701,47727,12,47813,47839,12,47925,47951,12,48037,48063,12,48149,48175,12,48261,48287,12,48373,48399,12,48485,48511,12,48597,48623,12,48709,48735,12,48821,48847,12,48933,48959,12,49045,49071,12,49157,49183,12,49269,49295,12,49381,49407,12,49493,49519,12,49605,49631,12,49717,49743,12,49829,49855,12,49941,49967,12,50053,50079,12,50165,50191,12,50277,50303,12,50389,50415,12,50501,50527,12,50613,50639,12,50725,50751,12,50837,50863,12,50949,50975,12,51061,51087,12,51173,51199,12,51285,51311,12,51397,51423,12,51509,51535,12,51621,51647,12,51733,51759,12,51845,51871,12,51957,51983,12,52069,52095,12,52181,52207,12,52293,52319,12,52405,52431,12,52517,52543,12,52629,52655,12,52741,52767,12,52853,52879,12,52965,52991,12,53077,53103,12,53189,53215,12,53301,53327,12,53413,53439,12,53525,53551,12,53637,53663,12,53749,53775,12,53861,53887,12,53973,53999,12,54085,54111,12,54197,54223,12,54309,54335,12,54421,54447,12,54533,54559,12,54645,54671,12,54757,54783,12,54869,54895,12,54981,55007,12,55093,55119,12,55243,55291,10,66045,66045,5,68325,68326,5,69688,69702,5,69817,69818,5,69957,69958,7,70089,70092,5,70198,70199,5,70462,70462,5,70502,70508,5,70750,70750,5,70846,70846,7,71100,71101,5,71230,71230,7,71351,71351,5,71737,71738,5,72000,72000,7,72160,72160,5,72273,72278,5,72752,72758,5,72882,72883,5,73031,73031,5,73461,73462,7,94192,94193,7,119149,119149,7,121403,121452,5,122915,122916,5,126980,126980,14,127358,127359,14,127535,127535,14,127759,127759,14,127771,127771,14,127792,127793,14,127825,127867,14,127897,127899,14,127945,127945,14,127985,127986,14,128000,128007,14,128021,128021,14,128066,128100,14,128184,128235,14,128249,128252,14,128266,128276,14,128335,128335,14,128379,128390,14,128407,128419,14,128444,128444,14,128481,128481,14,128499,128499,14,128526,128526,14,128536,128536,14,128543,128543,14,128556,128556,14,128564,128564,14,128577,128580,14,128643,128645,14,128649,128649,14,128654,128654,14,128660,128660,14,128664,128664,14,128675,128675,14,128686,128689,14,128695,128696,14,128705,128709,14,128717,128719,14,128725,128725,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129009,129023,14,129160,129167,14,129296,129304,14,129320,129327,14,129340,129342,14,129356,129356,14,129388,129392,14,129399,129400,14,129404,129407,14,129432,129442,14,129454,129455,14,129473,129474,14,129485,129487,14,129648,129651,14,129659,129660,14,129671,129679,14,129709,129711,14,129728,129730,14,129751,129753,14,129776,129782,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2274,2274,1,2363,2363,7,2377,2380,7,2402,2403,5,2494,2494,5,2507,2508,7,2558,2558,5,2622,2624,7,2641,2641,5,2691,2691,7,2759,2760,5,2786,2787,5,2876,2876,5,2881,2884,5,2901,2902,5,3006,3006,5,3014,3016,7,3072,3072,5,3134,3136,5,3157,3158,5,3260,3260,5,3266,3266,5,3274,3275,7,3328,3329,5,3391,3392,7,3405,3405,5,3457,3457,5,3536,3537,7,3551,3551,5,3636,3642,5,3764,3772,5,3895,3895,5,3967,3967,7,3993,4028,5,4146,4151,5,4182,4183,7,4226,4226,5,4253,4253,5,4957,4959,5,5940,5940,7,6070,6070,7,6087,6088,7,6158,6158,4,6432,6434,5,6448,6449,7,6679,6680,5,6742,6742,5,6754,6754,5,6783,6783,5,6912,6915,5,6966,6970,5,6978,6978,5,7042,7042,7,7080,7081,5,7143,7143,7,7150,7150,7,7212,7219,5,7380,7392,5,7412,7412,5,8203,8203,4,8232,8232,4,8265,8265,14,8400,8412,5,8421,8432,5,8617,8618,14,9167,9167,14,9200,9200,14,9410,9410,14,9723,9726,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9774,14,9786,9786,14,9794,9794,14,9823,9823,14,9828,9828,14,9833,9850,14,9855,9855,14,9875,9875,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9935,9935,14,9939,9939,14,9962,9962,14,9972,9972,14,9978,9978,14,9986,9986,14,9997,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10133,10135,14,10548,10549,14,11093,11093,14,12330,12333,5,12441,12442,5,42608,42610,5,43010,43010,5,43045,43046,5,43188,43203,7,43302,43309,5,43392,43394,5,43446,43449,5,43493,43493,5,43571,43572,7,43597,43597,7,43703,43704,5,43756,43757,5,44003,44004,7,44009,44010,7,44033,44059,12,44089,44115,12,44145,44171,12,44201,44227,12,44257,44283,12,44313,44339,12,44369,44395,12,44425,44451,12,44481,44507,12,44537,44563,12,44593,44619,12,44649,44675,12,44705,44731,12,44761,44787,12,44817,44843,12,44873,44899,12,44929,44955,12,44985,45011,12,45041,45067,12,45097,45123,12,45153,45179,12,45209,45235,12,45265,45291,12,45321,45347,12,45377,45403,12,45433,45459,12,45489,45515,12,45545,45571,12,45601,45627,12,45657,45683,12,45713,45739,12,45769,45795,12,45825,45851,12,45881,45907,12,45937,45963,12,45993,46019,12,46049,46075,12,46105,46131,12,46161,46187,12,46217,46243,12,46273,46299,12,46329,46355,12,46385,46411,12,46441,46467,12,46497,46523,12,46553,46579,12,46609,46635,12,46665,46691,12,46721,46747,12,46777,46803,12,46833,46859,12,46889,46915,12,46945,46971,12,47001,47027,12,47057,47083,12,47113,47139,12,47169,47195,12,47225,47251,12,47281,47307,12,47337,47363,12,47393,47419,12,47449,47475,12,47505,47531,12,47561,47587,12,47617,47643,12,47673,47699,12,47729,47755,12,47785,47811,12,47841,47867,12,47897,47923,12,47953,47979,12,48009,48035,12,48065,48091,12,48121,48147,12,48177,48203,12,48233,48259,12,48289,48315,12,48345,48371,12,48401,48427,12,48457,48483,12,48513,48539,12,48569,48595,12,48625,48651,12,48681,48707,12,48737,48763,12,48793,48819,12,48849,48875,12,48905,48931,12,48961,48987,12,49017,49043,12,49073,49099,12,49129,49155,12,49185,49211,12,49241,49267,12,49297,49323,12,49353,49379,12,49409,49435,12,49465,49491,12,49521,49547,12,49577,49603,12,49633,49659,12,49689,49715,12,49745,49771,12,49801,49827,12,49857,49883,12,49913,49939,12,49969,49995,12,50025,50051,12,50081,50107,12,50137,50163,12,50193,50219,12,50249,50275,12,50305,50331,12,50361,50387,12,50417,50443,12,50473,50499,12,50529,50555,12,50585,50611,12,50641,50667,12,50697,50723,12,50753,50779,12,50809,50835,12,50865,50891,12,50921,50947,12,50977,51003,12,51033,51059,12,51089,51115,12,51145,51171,12,51201,51227,12,51257,51283,12,51313,51339,12,51369,51395,12,51425,51451,12,51481,51507,12,51537,51563,12,51593,51619,12,51649,51675,12,51705,51731,12,51761,51787,12,51817,51843,12,51873,51899,12,51929,51955,12,51985,52011,12,52041,52067,12,52097,52123,12,52153,52179,12,52209,52235,12,52265,52291,12,52321,52347,12,52377,52403,12,52433,52459,12,52489,52515,12,52545,52571,12,52601,52627,12,52657,52683,12,52713,52739,12,52769,52795,12,52825,52851,12,52881,52907,12,52937,52963,12,52993,53019,12,53049,53075,12,53105,53131,12,53161,53187,12,53217,53243,12,53273,53299,12,53329,53355,12,53385,53411,12,53441,53467,12,53497,53523,12,53553,53579,12,53609,53635,12,53665,53691,12,53721,53747,12,53777,53803,12,53833,53859,12,53889,53915,12,53945,53971,12,54001,54027,12,54057,54083,12,54113,54139,12,54169,54195,12,54225,54251,12,54281,54307,12,54337,54363,12,54393,54419,12,54449,54475,12,54505,54531,12,54561,54587,12,54617,54643,12,54673,54699,12,54729,54755,12,54785,54811,12,54841,54867,12,54897,54923,12,54953,54979,12,55009,55035,12,55065,55091,12,55121,55147,12,55177,55203,12,65024,65039,5,65520,65528,4,66422,66426,5,68152,68154,5,69291,69292,5,69633,69633,5,69747,69748,5,69811,69814,5,69826,69826,5,69932,69932,7,70016,70017,5,70079,70080,7,70095,70095,5,70196,70196,5,70367,70367,5,70402,70403,7,70464,70464,5,70487,70487,5,70709,70711,7,70725,70725,7,70833,70834,7,70843,70844,7,70849,70849,7,71090,71093,5,71103,71104,5,71227,71228,7,71339,71339,5,71344,71349,5,71458,71461,5,71727,71735,5,71985,71989,7,71998,71998,5,72002,72002,7,72154,72155,5,72193,72202,5,72251,72254,5,72281,72283,5,72344,72345,5,72766,72766,7,72874,72880,5,72885,72886,5,73023,73029,5,73104,73105,5,73111,73111,5,92912,92916,5,94095,94098,5,113824,113827,4,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,125252,125258,5,127183,127183,14,127340,127343,14,127377,127386,14,127491,127503,14,127548,127551,14,127744,127756,14,127761,127761,14,127769,127769,14,127773,127774,14,127780,127788,14,127796,127797,14,127820,127823,14,127869,127869,14,127894,127895,14,127902,127903,14,127943,127943,14,127947,127950,14,127972,127972,14,127988,127988,14,127992,127994,14,128009,128011,14,128019,128019,14,128023,128041,14,128064,128064,14,128102,128107,14,128174,128181,14,128238,128238,14,128246,128247,14,128254,128254,14,128264,128264,14,128278,128299,14,128329,128330,14,128348,128359,14,128371,128377,14,128392,128393,14,128401,128404,14,128421,128421,14,128433,128434,14,128450,128452,14,128476,128478,14,128483,128483,14,128495,128495,14,128506,128506,14,128519,128520,14,128528,128528,14,128534,128534,14,128538,128538,14,128540,128542,14,128544,128549,14,128552,128555,14,128557,128557,14,128560,128563,14,128565,128565,14,128567,128576,14,128581,128591,14,128641,128642,14,128646,128646,14,128648,128648,14,128650,128651,14,128653,128653,14,128655,128655,14,128657,128659,14,128661,128661,14,128663,128663,14,128665,128666,14,128674,128674,14,128676,128677,14,128679,128685,14,128690,128690,14,128694,128694,14,128697,128702,14,128704,128704,14,128710,128714,14,128716,128716,14,128720,128720,14,128723,128724,14,128726,128727,14,128733,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129008,129008,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129661,129663,14,129667,129670,14,129680,129685,14,129705,129708,14,129712,129718,14,129723,129727,14,129731,129733,14,129744,129750,14,129754,129759,14,129768,129775,14,129783,129791,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2192,2193,1,2250,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3132,3132,5,3137,3140,7,3146,3149,5,3170,3171,5,3202,3203,7,3262,3262,7,3264,3265,7,3267,3268,7,3271,3272,7,3276,3277,5,3298,3299,5,3330,3331,7,3390,3390,5,3393,3396,5,3402,3404,7,3406,3406,1,3426,3427,5,3458,3459,7,3535,3535,5,3538,3540,5,3544,3550,7,3570,3571,7,3635,3635,7,3655,3662,5,3763,3763,7,3784,3789,5,3893,3893,5,3897,3897,5,3953,3966,5,3968,3972,5,3981,3991,5,4038,4038,5,4145,4145,7,4153,4154,5,4157,4158,5,4184,4185,5,4209,4212,5,4228,4228,7,4237,4237,5,4352,4447,8,4520,4607,10,5906,5908,5,5938,5939,5,5970,5971,5,6068,6069,5,6071,6077,5,6086,6086,5,6089,6099,5,6155,6157,5,6159,6159,5,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6862,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7679,5,8204,8204,5,8206,8207,4,8233,8233,4,8252,8252,14,8288,8292,4,8294,8303,4,8413,8416,5,8418,8420,5,8482,8482,14,8596,8601,14,8986,8987,14,9096,9096,14,9193,9196,14,9199,9199,14,9201,9202,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9729,14,9732,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9775,9775,14,9784,9785,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9874,14,9876,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9934,14,9936,9936,14,9938,9938,14,9940,9940,14,9961,9961,14,9963,9967,14,9970,9971,14,9973,9973,14,9975,9977,14,9979,9980,14,9982,9985,14,9987,9988,14,9992,9996,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10083,14,10085,10087,14,10145,10145,14,10175,10175,14,11013,11015,14,11088,11088,14,11503,11505,5,11744,11775,5,12334,12335,5,12349,12349,14,12951,12951,14,42607,42607,5,42612,42621,5,42736,42737,5,43014,43014,5,43043,43044,7,43047,43047,7,43136,43137,7,43204,43205,5,43263,43263,5,43335,43345,5,43360,43388,8,43395,43395,7,43444,43445,7,43450,43451,7,43454,43456,7,43561,43566,5,43569,43570,5,43573,43574,5,43596,43596,5,43644,43644,5,43698,43700,5,43710,43711,5,43755,43755,7,43758,43759,7,43766,43766,5,44005,44005,5,44008,44008,5,44012,44012,7,44032,44032,11,44060,44060,11,44088,44088,11,44116,44116,11,44144,44144,11,44172,44172,11,44200,44200,11,44228,44228,11,44256,44256,11,44284,44284,11,44312,44312,11,44340,44340,11,44368,44368,11,44396,44396,11,44424,44424,11,44452,44452,11,44480,44480,11,44508,44508,11,44536,44536,11,44564,44564,11,44592,44592,11,44620,44620,11,44648,44648,11,44676,44676,11,44704,44704,11,44732,44732,11,44760,44760,11,44788,44788,11,44816,44816,11,44844,44844,11,44872,44872,11,44900,44900,11,44928,44928,11,44956,44956,11,44984,44984,11,45012,45012,11,45040,45040,11,45068,45068,11,45096,45096,11,45124,45124,11,45152,45152,11,45180,45180,11,45208,45208,11,45236,45236,11,45264,45264,11,45292,45292,11,45320,45320,11,45348,45348,11,45376,45376,11,45404,45404,11,45432,45432,11,45460,45460,11,45488,45488,11,45516,45516,11,45544,45544,11,45572,45572,11,45600,45600,11,45628,45628,11,45656,45656,11,45684,45684,11,45712,45712,11,45740,45740,11,45768,45768,11,45796,45796,11,45824,45824,11,45852,45852,11,45880,45880,11,45908,45908,11,45936,45936,11,45964,45964,11,45992,45992,11,46020,46020,11,46048,46048,11,46076,46076,11,46104,46104,11,46132,46132,11,46160,46160,11,46188,46188,11,46216,46216,11,46244,46244,11,46272,46272,11,46300,46300,11,46328,46328,11,46356,46356,11,46384,46384,11,46412,46412,11,46440,46440,11,46468,46468,11,46496,46496,11,46524,46524,11,46552,46552,11,46580,46580,11,46608,46608,11,46636,46636,11,46664,46664,11,46692,46692,11,46720,46720,11,46748,46748,11,46776,46776,11,46804,46804,11,46832,46832,11,46860,46860,11,46888,46888,11,46916,46916,11,46944,46944,11,46972,46972,11,47000,47000,11,47028,47028,11,47056,47056,11,47084,47084,11,47112,47112,11,47140,47140,11,47168,47168,11,47196,47196,11,47224,47224,11,47252,47252,11,47280,47280,11,47308,47308,11,47336,47336,11,47364,47364,11,47392,47392,11,47420,47420,11,47448,47448,11,47476,47476,11,47504,47504,11,47532,47532,11,47560,47560,11,47588,47588,11,47616,47616,11,47644,47644,11,47672,47672,11,47700,47700,11,47728,47728,11,47756,47756,11,47784,47784,11,47812,47812,11,47840,47840,11,47868,47868,11,47896,47896,11,47924,47924,11,47952,47952,11,47980,47980,11,48008,48008,11,48036,48036,11,48064,48064,11,48092,48092,11,48120,48120,11,48148,48148,11,48176,48176,11,48204,48204,11,48232,48232,11,48260,48260,11,48288,48288,11,48316,48316,11,48344,48344,11,48372,48372,11,48400,48400,11,48428,48428,11,48456,48456,11,48484,48484,11,48512,48512,11,48540,48540,11,48568,48568,11,48596,48596,11,48624,48624,11,48652,48652,11,48680,48680,11,48708,48708,11,48736,48736,11,48764,48764,11,48792,48792,11,48820,48820,11,48848,48848,11,48876,48876,11,48904,48904,11,48932,48932,11,48960,48960,11,48988,48988,11,49016,49016,11,49044,49044,11,49072,49072,11,49100,49100,11,49128,49128,11,49156,49156,11,49184,49184,11,49212,49212,11,49240,49240,11,49268,49268,11,49296,49296,11,49324,49324,11,49352,49352,11,49380,49380,11,49408,49408,11,49436,49436,11,49464,49464,11,49492,49492,11,49520,49520,11,49548,49548,11,49576,49576,11,49604,49604,11,49632,49632,11,49660,49660,11,49688,49688,11,49716,49716,11,49744,49744,11,49772,49772,11,49800,49800,11,49828,49828,11,49856,49856,11,49884,49884,11,49912,49912,11,49940,49940,11,49968,49968,11,49996,49996,11,50024,50024,11,50052,50052,11,50080,50080,11,50108,50108,11,50136,50136,11,50164,50164,11,50192,50192,11,50220,50220,11,50248,50248,11,50276,50276,11,50304,50304,11,50332,50332,11,50360,50360,11,50388,50388,11,50416,50416,11,50444,50444,11,50472,50472,11,50500,50500,11,50528,50528,11,50556,50556,11,50584,50584,11,50612,50612,11,50640,50640,11,50668,50668,11,50696,50696,11,50724,50724,11,50752,50752,11,50780,50780,11,50808,50808,11,50836,50836,11,50864,50864,11,50892,50892,11,50920,50920,11,50948,50948,11,50976,50976,11,51004,51004,11,51032,51032,11,51060,51060,11,51088,51088,11,51116,51116,11,51144,51144,11,51172,51172,11,51200,51200,11,51228,51228,11,51256,51256,11,51284,51284,11,51312,51312,11,51340,51340,11,51368,51368,11,51396,51396,11,51424,51424,11,51452,51452,11,51480,51480,11,51508,51508,11,51536,51536,11,51564,51564,11,51592,51592,11,51620,51620,11,51648,51648,11,51676,51676,11,51704,51704,11,51732,51732,11,51760,51760,11,51788,51788,11,51816,51816,11,51844,51844,11,51872,51872,11,51900,51900,11,51928,51928,11,51956,51956,11,51984,51984,11,52012,52012,11,52040,52040,11,52068,52068,11,52096,52096,11,52124,52124,11,52152,52152,11,52180,52180,11,52208,52208,11,52236,52236,11,52264,52264,11,52292,52292,11,52320,52320,11,52348,52348,11,52376,52376,11,52404,52404,11,52432,52432,11,52460,52460,11,52488,52488,11,52516,52516,11,52544,52544,11,52572,52572,11,52600,52600,11,52628,52628,11,52656,52656,11,52684,52684,11,52712,52712,11,52740,52740,11,52768,52768,11,52796,52796,11,52824,52824,11,52852,52852,11,52880,52880,11,52908,52908,11,52936,52936,11,52964,52964,11,52992,52992,11,53020,53020,11,53048,53048,11,53076,53076,11,53104,53104,11,53132,53132,11,53160,53160,11,53188,53188,11,53216,53216,11,53244,53244,11,53272,53272,11,53300,53300,11,53328,53328,11,53356,53356,11,53384,53384,11,53412,53412,11,53440,53440,11,53468,53468,11,53496,53496,11,53524,53524,11,53552,53552,11,53580,53580,11,53608,53608,11,53636,53636,11,53664,53664,11,53692,53692,11,53720,53720,11,53748,53748,11,53776,53776,11,53804,53804,11,53832,53832,11,53860,53860,11,53888,53888,11,53916,53916,11,53944,53944,11,53972,53972,11,54000,54000,11,54028,54028,11,54056,54056,11,54084,54084,11,54112,54112,11,54140,54140,11,54168,54168,11,54196,54196,11,54224,54224,11,54252,54252,11,54280,54280,11,54308,54308,11,54336,54336,11,54364,54364,11,54392,54392,11,54420,54420,11,54448,54448,11,54476,54476,11,54504,54504,11,54532,54532,11,54560,54560,11,54588,54588,11,54616,54616,11,54644,54644,11,54672,54672,11,54700,54700,11,54728,54728,11,54756,54756,11,54784,54784,11,54812,54812,11,54840,54840,11,54868,54868,11,54896,54896,11,54924,54924,11,54952,54952,11,54980,54980,11,55008,55008,11,55036,55036,11,55064,55064,11,55092,55092,11,55120,55120,11,55148,55148,11,55176,55176,11,55216,55238,9,64286,64286,5,65056,65071,5,65438,65439,5,65529,65531,4,66272,66272,5,68097,68099,5,68108,68111,5,68159,68159,5,68900,68903,5,69446,69456,5,69632,69632,7,69634,69634,7,69744,69744,5,69759,69761,5,69808,69810,7,69815,69816,7,69821,69821,1,69837,69837,1,69927,69931,5,69933,69940,5,70003,70003,5,70018,70018,7,70070,70078,5,70082,70083,1,70094,70094,7,70188,70190,7,70194,70195,7,70197,70197,7,70206,70206,5,70368,70370,7,70400,70401,5,70459,70460,5,70463,70463,7,70465,70468,7,70475,70477,7,70498,70499,7,70512,70516,5,70712,70719,5,70722,70724,5,70726,70726,5,70832,70832,5,70835,70840,5,70842,70842,5,70845,70845,5,70847,70848,5,70850,70851,5,71088,71089,7,71096,71099,7,71102,71102,7,71132,71133,5,71219,71226,5,71229,71229,5,71231,71232,5,71340,71340,7,71342,71343,7,71350,71350,7,71453,71455,5,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,118528,118573,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123566,123566,5,125136,125142,5,126976,126979,14,126981,127182,14,127184,127231,14,127279,127279,14,127344,127345,14,127374,127374,14,127405,127461,14,127489,127490,14,127514,127514,14,127538,127546,14,127561,127567,14,127570,127743,14,127757,127758,14,127760,127760,14,127762,127762,14,127766,127768,14,127770,127770,14,127772,127772,14,127775,127776,14,127778,127779,14,127789,127791,14,127794,127795,14,127798,127798,14,127819,127819,14,127824,127824,14,127868,127868,14,127870,127871,14,127892,127893,14,127896,127896,14,127900,127901,14,127904,127940,14,127942,127942,14,127944,127944,14,127946,127946,14,127951,127955,14,127968,127971,14,127973,127984,14,127987,127987,14,127989,127989,14,127991,127991,14,127995,127999,5,128008,128008,14,128012,128014,14,128017,128018,14,128020,128020,14,128022,128022,14,128042,128042,14,128063,128063,14,128065,128065,14,128101,128101,14,128108,128109,14,128173,128173,14,128182,128183,14,128236,128237,14,128239,128239,14,128245,128245,14,128248,128248,14,128253,128253,14,128255,128258,14,128260,128263,14,128265,128265,14,128277,128277,14,128300,128301,14,128326,128328,14,128331,128334,14,128336,128347,14,128360,128366,14,128369,128370,14,128378,128378,14,128391,128391,14,128394,128397,14,128400,128400,14,128405,128406,14,128420,128420,14,128422,128423,14,128425,128432,14,128435,128443,14,128445,128449,14,128453,128464,14,128468,128475,14,128479,128480,14,128482,128482,14,128484,128487,14,128489,128494,14,128496,128498,14,128500,128505,14,128507,128511,14,128513,128518,14,128521,128525,14,128527,128527,14,128529,128529,14,128533,128533,14,128535,128535,14,128537,128537,14]'); +} +//#endregion +/** + * Computes the offset after performing a left delete on the given string, + * while considering unicode grapheme/emoji rules. +*/ +export function getLeftDeleteOffset(offset, str) { + if (offset === 0) { + return 0; + } + // Try to delete emoji part. + const emojiOffset = getOffsetBeforeLastEmojiComponent(offset, str); + if (emojiOffset !== undefined) { + return emojiOffset; + } + // Otherwise, just skip a single code point. + const iterator = new CodePointIterator(str, offset); + iterator.prevCodePoint(); + return iterator.offset; +} +function getOffsetBeforeLastEmojiComponent(initialOffset, str) { + // See https://www.unicode.org/reports/tr51/tr51-14.html#EBNF_and_Regex for the + // structure of emojis. + const iterator = new CodePointIterator(str, initialOffset); + let codePoint = iterator.prevCodePoint(); + // Skip modifiers + while ((isEmojiModifier(codePoint) || codePoint === 65039 /* CodePoint.emojiVariantSelector */ || codePoint === 8419 /* CodePoint.enclosingKeyCap */)) { + if (iterator.offset === 0) { + // Cannot skip modifier, no preceding emoji base. + return undefined; + } + codePoint = iterator.prevCodePoint(); + } + // Expect base emoji + if (!isEmojiImprecise(codePoint)) { + // Unexpected code point, not a valid emoji. + return undefined; + } + let resultOffset = iterator.offset; + if (resultOffset > 0) { + // Skip optional ZWJ code points that combine multiple emojis. + // In theory, we should check if that ZWJ actually combines multiple emojis + // to prevent deleting ZWJs in situations we didn't account for. + const optionalZwjCodePoint = iterator.prevCodePoint(); + if (optionalZwjCodePoint === 8205 /* CodePoint.zwj */) { + resultOffset = iterator.offset; + } + } + return resultOffset; +} +function isEmojiModifier(codePoint) { + return 0x1F3FB <= codePoint && codePoint <= 0x1F3FF; +} +var CodePoint; +(function (CodePoint) { + CodePoint[CodePoint["zwj"] = 8205] = "zwj"; + /** + * Variation Selector-16 (VS16) + */ + CodePoint[CodePoint["emojiVariantSelector"] = 65039] = "emojiVariantSelector"; + /** + * Combining Enclosing Keycap + */ + CodePoint[CodePoint["enclosingKeyCap"] = 8419] = "enclosingKeyCap"; +})(CodePoint || (CodePoint = {})); +export const noBreakWhitespace = '\xa0'; +export class AmbiguousCharacters { + confusableDictionary; + static ambiguousCharacterData = new Lazy(() => { + // Generated using https://github.com/hediet/vscode-unicode-data + // Stored as key1, value1, key2, value2, ... + return JSON.parse('{\"_common\":[8232,32,8233,32,5760,32,8192,32,8193,32,8194,32,8195,32,8196,32,8197,32,8198,32,8200,32,8201,32,8202,32,8287,32,8199,32,8239,32,2042,95,65101,95,65102,95,65103,95,8208,45,8209,45,8210,45,65112,45,1748,45,8259,45,727,45,8722,45,10134,45,11450,45,1549,44,1643,44,8218,44,184,44,42233,44,894,59,2307,58,2691,58,1417,58,1795,58,1796,58,5868,58,65072,58,6147,58,6153,58,8282,58,1475,58,760,58,42889,58,8758,58,720,58,42237,58,451,33,11601,33,660,63,577,63,2429,63,5038,63,42731,63,119149,46,8228,46,1793,46,1794,46,42510,46,68176,46,1632,46,1776,46,42232,46,1373,96,65287,96,8219,96,8242,96,1370,96,1523,96,8175,96,65344,96,900,96,8189,96,8125,96,8127,96,8190,96,697,96,884,96,712,96,714,96,715,96,756,96,699,96,701,96,700,96,702,96,42892,96,1497,96,2036,96,2037,96,5194,96,5836,96,94033,96,94034,96,65339,91,10088,40,10098,40,12308,40,64830,40,65341,93,10089,41,10099,41,12309,41,64831,41,10100,123,119060,123,10101,125,65342,94,8270,42,1645,42,8727,42,66335,42,5941,47,8257,47,8725,47,8260,47,9585,47,10187,47,10744,47,119354,47,12755,47,12339,47,11462,47,20031,47,12035,47,65340,92,65128,92,8726,92,10189,92,10741,92,10745,92,119311,92,119355,92,12756,92,20022,92,12034,92,42872,38,708,94,710,94,5869,43,10133,43,66203,43,8249,60,10094,60,706,60,119350,60,5176,60,5810,60,5120,61,11840,61,12448,61,42239,61,8250,62,10095,62,707,62,119351,62,5171,62,94015,62,8275,126,732,126,8128,126,8764,126,65372,124,65293,45,120784,50,120794,50,120804,50,120814,50,120824,50,130034,50,42842,50,423,50,1000,50,42564,50,5311,50,42735,50,119302,51,120785,51,120795,51,120805,51,120815,51,120825,51,130035,51,42923,51,540,51,439,51,42858,51,11468,51,1248,51,94011,51,71882,51,120786,52,120796,52,120806,52,120816,52,120826,52,130036,52,5070,52,71855,52,120787,53,120797,53,120807,53,120817,53,120827,53,130037,53,444,53,71867,53,120788,54,120798,54,120808,54,120818,54,120828,54,130038,54,11474,54,5102,54,71893,54,119314,55,120789,55,120799,55,120809,55,120819,55,120829,55,130039,55,66770,55,71878,55,2819,56,2538,56,2666,56,125131,56,120790,56,120800,56,120810,56,120820,56,120830,56,130040,56,547,56,546,56,66330,56,2663,57,2920,57,2541,57,3437,57,120791,57,120801,57,120811,57,120821,57,120831,57,130041,57,42862,57,11466,57,71884,57,71852,57,71894,57,9082,97,65345,97,119834,97,119886,97,119938,97,119990,97,120042,97,120094,97,120146,97,120198,97,120250,97,120302,97,120354,97,120406,97,120458,97,593,97,945,97,120514,97,120572,97,120630,97,120688,97,120746,97,65313,65,119808,65,119860,65,119912,65,119964,65,120016,65,120068,65,120120,65,120172,65,120224,65,120276,65,120328,65,120380,65,120432,65,913,65,120488,65,120546,65,120604,65,120662,65,120720,65,5034,65,5573,65,42222,65,94016,65,66208,65,119835,98,119887,98,119939,98,119991,98,120043,98,120095,98,120147,98,120199,98,120251,98,120303,98,120355,98,120407,98,120459,98,388,98,5071,98,5234,98,5551,98,65314,66,8492,66,119809,66,119861,66,119913,66,120017,66,120069,66,120121,66,120173,66,120225,66,120277,66,120329,66,120381,66,120433,66,42932,66,914,66,120489,66,120547,66,120605,66,120663,66,120721,66,5108,66,5623,66,42192,66,66178,66,66209,66,66305,66,65347,99,8573,99,119836,99,119888,99,119940,99,119992,99,120044,99,120096,99,120148,99,120200,99,120252,99,120304,99,120356,99,120408,99,120460,99,7428,99,1010,99,11429,99,43951,99,66621,99,128844,67,71922,67,71913,67,65315,67,8557,67,8450,67,8493,67,119810,67,119862,67,119914,67,119966,67,120018,67,120174,67,120226,67,120278,67,120330,67,120382,67,120434,67,1017,67,11428,67,5087,67,42202,67,66210,67,66306,67,66581,67,66844,67,8574,100,8518,100,119837,100,119889,100,119941,100,119993,100,120045,100,120097,100,120149,100,120201,100,120253,100,120305,100,120357,100,120409,100,120461,100,1281,100,5095,100,5231,100,42194,100,8558,68,8517,68,119811,68,119863,68,119915,68,119967,68,120019,68,120071,68,120123,68,120175,68,120227,68,120279,68,120331,68,120383,68,120435,68,5024,68,5598,68,5610,68,42195,68,8494,101,65349,101,8495,101,8519,101,119838,101,119890,101,119942,101,120046,101,120098,101,120150,101,120202,101,120254,101,120306,101,120358,101,120410,101,120462,101,43826,101,1213,101,8959,69,65317,69,8496,69,119812,69,119864,69,119916,69,120020,69,120072,69,120124,69,120176,69,120228,69,120280,69,120332,69,120384,69,120436,69,917,69,120492,69,120550,69,120608,69,120666,69,120724,69,11577,69,5036,69,42224,69,71846,69,71854,69,66182,69,119839,102,119891,102,119943,102,119995,102,120047,102,120099,102,120151,102,120203,102,120255,102,120307,102,120359,102,120411,102,120463,102,43829,102,42905,102,383,102,7837,102,1412,102,119315,70,8497,70,119813,70,119865,70,119917,70,120021,70,120073,70,120125,70,120177,70,120229,70,120281,70,120333,70,120385,70,120437,70,42904,70,988,70,120778,70,5556,70,42205,70,71874,70,71842,70,66183,70,66213,70,66853,70,65351,103,8458,103,119840,103,119892,103,119944,103,120048,103,120100,103,120152,103,120204,103,120256,103,120308,103,120360,103,120412,103,120464,103,609,103,7555,103,397,103,1409,103,119814,71,119866,71,119918,71,119970,71,120022,71,120074,71,120126,71,120178,71,120230,71,120282,71,120334,71,120386,71,120438,71,1292,71,5056,71,5107,71,42198,71,65352,104,8462,104,119841,104,119945,104,119997,104,120049,104,120101,104,120153,104,120205,104,120257,104,120309,104,120361,104,120413,104,120465,104,1211,104,1392,104,5058,104,65320,72,8459,72,8460,72,8461,72,119815,72,119867,72,119919,72,120023,72,120179,72,120231,72,120283,72,120335,72,120387,72,120439,72,919,72,120494,72,120552,72,120610,72,120668,72,120726,72,11406,72,5051,72,5500,72,42215,72,66255,72,731,105,9075,105,65353,105,8560,105,8505,105,8520,105,119842,105,119894,105,119946,105,119998,105,120050,105,120102,105,120154,105,120206,105,120258,105,120310,105,120362,105,120414,105,120466,105,120484,105,618,105,617,105,953,105,8126,105,890,105,120522,105,120580,105,120638,105,120696,105,120754,105,1110,105,42567,105,1231,105,43893,105,5029,105,71875,105,65354,106,8521,106,119843,106,119895,106,119947,106,119999,106,120051,106,120103,106,120155,106,120207,106,120259,106,120311,106,120363,106,120415,106,120467,106,1011,106,1112,106,65322,74,119817,74,119869,74,119921,74,119973,74,120025,74,120077,74,120129,74,120181,74,120233,74,120285,74,120337,74,120389,74,120441,74,42930,74,895,74,1032,74,5035,74,5261,74,42201,74,119844,107,119896,107,119948,107,120000,107,120052,107,120104,107,120156,107,120208,107,120260,107,120312,107,120364,107,120416,107,120468,107,8490,75,65323,75,119818,75,119870,75,119922,75,119974,75,120026,75,120078,75,120130,75,120182,75,120234,75,120286,75,120338,75,120390,75,120442,75,922,75,120497,75,120555,75,120613,75,120671,75,120729,75,11412,75,5094,75,5845,75,42199,75,66840,75,1472,108,8739,73,9213,73,65512,73,1633,108,1777,73,66336,108,125127,108,120783,73,120793,73,120803,73,120813,73,120823,73,130033,73,65321,73,8544,73,8464,73,8465,73,119816,73,119868,73,119920,73,120024,73,120128,73,120180,73,120232,73,120284,73,120336,73,120388,73,120440,73,65356,108,8572,73,8467,108,119845,108,119897,108,119949,108,120001,108,120053,108,120105,73,120157,73,120209,73,120261,73,120313,73,120365,73,120417,73,120469,73,448,73,120496,73,120554,73,120612,73,120670,73,120728,73,11410,73,1030,73,1216,73,1493,108,1503,108,1575,108,126464,108,126592,108,65166,108,65165,108,1994,108,11599,73,5825,73,42226,73,93992,73,66186,124,66313,124,119338,76,8556,76,8466,76,119819,76,119871,76,119923,76,120027,76,120079,76,120131,76,120183,76,120235,76,120287,76,120339,76,120391,76,120443,76,11472,76,5086,76,5290,76,42209,76,93974,76,71843,76,71858,76,66587,76,66854,76,65325,77,8559,77,8499,77,119820,77,119872,77,119924,77,120028,77,120080,77,120132,77,120184,77,120236,77,120288,77,120340,77,120392,77,120444,77,924,77,120499,77,120557,77,120615,77,120673,77,120731,77,1018,77,11416,77,5047,77,5616,77,5846,77,42207,77,66224,77,66321,77,119847,110,119899,110,119951,110,120003,110,120055,110,120107,110,120159,110,120211,110,120263,110,120315,110,120367,110,120419,110,120471,110,1400,110,1404,110,65326,78,8469,78,119821,78,119873,78,119925,78,119977,78,120029,78,120081,78,120185,78,120237,78,120289,78,120341,78,120393,78,120445,78,925,78,120500,78,120558,78,120616,78,120674,78,120732,78,11418,78,42208,78,66835,78,3074,111,3202,111,3330,111,3458,111,2406,111,2662,111,2790,111,3046,111,3174,111,3302,111,3430,111,3664,111,3792,111,4160,111,1637,111,1781,111,65359,111,8500,111,119848,111,119900,111,119952,111,120056,111,120108,111,120160,111,120212,111,120264,111,120316,111,120368,111,120420,111,120472,111,7439,111,7441,111,43837,111,959,111,120528,111,120586,111,120644,111,120702,111,120760,111,963,111,120532,111,120590,111,120648,111,120706,111,120764,111,11423,111,4351,111,1413,111,1505,111,1607,111,126500,111,126564,111,126596,111,65259,111,65260,111,65258,111,65257,111,1726,111,64428,111,64429,111,64427,111,64426,111,1729,111,64424,111,64425,111,64423,111,64422,111,1749,111,3360,111,4125,111,66794,111,71880,111,71895,111,66604,111,1984,79,2534,79,2918,79,12295,79,70864,79,71904,79,120782,79,120792,79,120802,79,120812,79,120822,79,130032,79,65327,79,119822,79,119874,79,119926,79,119978,79,120030,79,120082,79,120134,79,120186,79,120238,79,120290,79,120342,79,120394,79,120446,79,927,79,120502,79,120560,79,120618,79,120676,79,120734,79,11422,79,1365,79,11604,79,4816,79,2848,79,66754,79,42227,79,71861,79,66194,79,66219,79,66564,79,66838,79,9076,112,65360,112,119849,112,119901,112,119953,112,120005,112,120057,112,120109,112,120161,112,120213,112,120265,112,120317,112,120369,112,120421,112,120473,112,961,112,120530,112,120544,112,120588,112,120602,112,120646,112,120660,112,120704,112,120718,112,120762,112,120776,112,11427,112,65328,80,8473,80,119823,80,119875,80,119927,80,119979,80,120031,80,120083,80,120187,80,120239,80,120291,80,120343,80,120395,80,120447,80,929,80,120504,80,120562,80,120620,80,120678,80,120736,80,11426,80,5090,80,5229,80,42193,80,66197,80,119850,113,119902,113,119954,113,120006,113,120058,113,120110,113,120162,113,120214,113,120266,113,120318,113,120370,113,120422,113,120474,113,1307,113,1379,113,1382,113,8474,81,119824,81,119876,81,119928,81,119980,81,120032,81,120084,81,120188,81,120240,81,120292,81,120344,81,120396,81,120448,81,11605,81,119851,114,119903,114,119955,114,120007,114,120059,114,120111,114,120163,114,120215,114,120267,114,120319,114,120371,114,120423,114,120475,114,43847,114,43848,114,7462,114,11397,114,43905,114,119318,82,8475,82,8476,82,8477,82,119825,82,119877,82,119929,82,120033,82,120189,82,120241,82,120293,82,120345,82,120397,82,120449,82,422,82,5025,82,5074,82,66740,82,5511,82,42211,82,94005,82,65363,115,119852,115,119904,115,119956,115,120008,115,120060,115,120112,115,120164,115,120216,115,120268,115,120320,115,120372,115,120424,115,120476,115,42801,115,445,115,1109,115,43946,115,71873,115,66632,115,65331,83,119826,83,119878,83,119930,83,119982,83,120034,83,120086,83,120138,83,120190,83,120242,83,120294,83,120346,83,120398,83,120450,83,1029,83,1359,83,5077,83,5082,83,42210,83,94010,83,66198,83,66592,83,119853,116,119905,116,119957,116,120009,116,120061,116,120113,116,120165,116,120217,116,120269,116,120321,116,120373,116,120425,116,120477,116,8868,84,10201,84,128872,84,65332,84,119827,84,119879,84,119931,84,119983,84,120035,84,120087,84,120139,84,120191,84,120243,84,120295,84,120347,84,120399,84,120451,84,932,84,120507,84,120565,84,120623,84,120681,84,120739,84,11430,84,5026,84,42196,84,93962,84,71868,84,66199,84,66225,84,66325,84,119854,117,119906,117,119958,117,120010,117,120062,117,120114,117,120166,117,120218,117,120270,117,120322,117,120374,117,120426,117,120478,117,42911,117,7452,117,43854,117,43858,117,651,117,965,117,120534,117,120592,117,120650,117,120708,117,120766,117,1405,117,66806,117,71896,117,8746,85,8899,85,119828,85,119880,85,119932,85,119984,85,120036,85,120088,85,120140,85,120192,85,120244,85,120296,85,120348,85,120400,85,120452,85,1357,85,4608,85,66766,85,5196,85,42228,85,94018,85,71864,85,8744,118,8897,118,65366,118,8564,118,119855,118,119907,118,119959,118,120011,118,120063,118,120115,118,120167,118,120219,118,120271,118,120323,118,120375,118,120427,118,120479,118,7456,118,957,118,120526,118,120584,118,120642,118,120700,118,120758,118,1141,118,1496,118,71430,118,43945,118,71872,118,119309,86,1639,86,1783,86,8548,86,119829,86,119881,86,119933,86,119985,86,120037,86,120089,86,120141,86,120193,86,120245,86,120297,86,120349,86,120401,86,120453,86,1140,86,11576,86,5081,86,5167,86,42719,86,42214,86,93960,86,71840,86,66845,86,623,119,119856,119,119908,119,119960,119,120012,119,120064,119,120116,119,120168,119,120220,119,120272,119,120324,119,120376,119,120428,119,120480,119,7457,119,1121,119,1309,119,1377,119,71434,119,71438,119,71439,119,43907,119,71919,87,71910,87,119830,87,119882,87,119934,87,119986,87,120038,87,120090,87,120142,87,120194,87,120246,87,120298,87,120350,87,120402,87,120454,87,1308,87,5043,87,5076,87,42218,87,5742,120,10539,120,10540,120,10799,120,65368,120,8569,120,119857,120,119909,120,119961,120,120013,120,120065,120,120117,120,120169,120,120221,120,120273,120,120325,120,120377,120,120429,120,120481,120,5441,120,5501,120,5741,88,9587,88,66338,88,71916,88,65336,88,8553,88,119831,88,119883,88,119935,88,119987,88,120039,88,120091,88,120143,88,120195,88,120247,88,120299,88,120351,88,120403,88,120455,88,42931,88,935,88,120510,88,120568,88,120626,88,120684,88,120742,88,11436,88,11613,88,5815,88,42219,88,66192,88,66228,88,66327,88,66855,88,611,121,7564,121,65369,121,119858,121,119910,121,119962,121,120014,121,120066,121,120118,121,120170,121,120222,121,120274,121,120326,121,120378,121,120430,121,120482,121,655,121,7935,121,43866,121,947,121,8509,121,120516,121,120574,121,120632,121,120690,121,120748,121,1199,121,4327,121,71900,121,65337,89,119832,89,119884,89,119936,89,119988,89,120040,89,120092,89,120144,89,120196,89,120248,89,120300,89,120352,89,120404,89,120456,89,933,89,978,89,120508,89,120566,89,120624,89,120682,89,120740,89,11432,89,1198,89,5033,89,5053,89,42220,89,94019,89,71844,89,66226,89,119859,122,119911,122,119963,122,120015,122,120067,122,120119,122,120171,122,120223,122,120275,122,120327,122,120379,122,120431,122,120483,122,7458,122,43923,122,71876,122,66293,90,71909,90,65338,90,8484,90,8488,90,119833,90,119885,90,119937,90,119989,90,120041,90,120197,90,120249,90,120301,90,120353,90,120405,90,120457,90,918,90,120493,90,120551,90,120609,90,120667,90,120725,90,5059,90,42204,90,71849,90,65282,34,65284,36,65285,37,65286,38,65290,42,65291,43,65294,46,65295,47,65296,48,65297,49,65298,50,65299,51,65300,52,65301,53,65302,54,65303,55,65304,56,65305,57,65308,60,65309,61,65310,62,65312,64,65316,68,65318,70,65319,71,65324,76,65329,81,65330,82,65333,85,65334,86,65335,87,65343,95,65346,98,65348,100,65350,102,65355,107,65357,109,65358,110,65361,113,65362,114,65364,116,65365,117,65367,119,65370,122,65371,123,65373,125,119846,109],\"_default\":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"cs\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"de\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"es\":[8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"fr\":[65374,126,65306,58,65281,33,8216,96,8245,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"it\":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"ja\":[8211,45,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65292,44,65307,59],\"ko\":[8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"pl\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"pt-BR\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"qps-ploc\":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"ru\":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,305,105,921,73,1009,112,215,120,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"tr\":[160,32,8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],\"zh-hans\":[65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41],\"zh-hant\":[8211,45,65374,126,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65307,59]}'); + }); + static cache = new LRUCachedFunction({ getCacheKey: JSON.stringify }, (locales) => { + function arrayToMap(arr) { + const result = new Map(); + for (let i = 0; i < arr.length; i += 2) { + result.set(arr[i], arr[i + 1]); + } + return result; + } + function mergeMaps(map1, map2) { + const result = new Map(map1); + for (const [key, value] of map2) { + result.set(key, value); + } + return result; + } + function intersectMaps(map1, map2) { + if (!map1) { + return map2; + } + const result = new Map(); + for (const [key, value] of map1) { + if (map2.has(key)) { + result.set(key, value); + } + } + return result; + } + const data = this.ambiguousCharacterData.value; + let filteredLocales = locales.filter((l) => !l.startsWith('_') && l in data); + if (filteredLocales.length === 0) { + filteredLocales = ['_default']; + } + let languageSpecificMap = undefined; + for (const locale of filteredLocales) { + const map = arrayToMap(data[locale]); + languageSpecificMap = intersectMaps(languageSpecificMap, map); + } + const commonMap = arrayToMap(data['_common']); + const map = mergeMaps(commonMap, languageSpecificMap); + return new AmbiguousCharacters(map); + }); + static getInstance(locales) { + return AmbiguousCharacters.cache.get(Array.from(locales)); + } + static _locales = new Lazy(() => Object.keys(AmbiguousCharacters.ambiguousCharacterData.value).filter((k) => !k.startsWith('_'))); + static getLocales() { + return AmbiguousCharacters._locales.value; + } + constructor(confusableDictionary) { + this.confusableDictionary = confusableDictionary; + } + isAmbiguous(codePoint) { + return this.confusableDictionary.has(codePoint); + } + containsAmbiguousCharacter(str) { + for (let i = 0; i < str.length; i++) { + const codePoint = str.codePointAt(i); + if (typeof codePoint === 'number' && this.isAmbiguous(codePoint)) { + return true; + } + } + return false; + } + /** + * Returns the non basic ASCII code point that the given code point can be confused, + * or undefined if such code point does note exist. + */ + getPrimaryConfusable(codePoint) { + return this.confusableDictionary.get(codePoint); + } + getConfusableCodePoints() { + return new Set(this.confusableDictionary.keys()); + } +} +export class InvisibleCharacters { + static getRawData() { + // Generated using https://github.com/hediet/vscode-unicode-data + return JSON.parse('[9,10,11,12,13,32,127,160,173,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207,8234,8235,8236,8237,8238,8239,8287,8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,10240,12288,12644,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65279,65440,65520,65521,65522,65523,65524,65525,65526,65527,65528,65532,78844,119155,119156,119157,119158,119159,119160,119161,119162,917504,917505,917506,917507,917508,917509,917510,917511,917512,917513,917514,917515,917516,917517,917518,917519,917520,917521,917522,917523,917524,917525,917526,917527,917528,917529,917530,917531,917532,917533,917534,917535,917536,917537,917538,917539,917540,917541,917542,917543,917544,917545,917546,917547,917548,917549,917550,917551,917552,917553,917554,917555,917556,917557,917558,917559,917560,917561,917562,917563,917564,917565,917566,917567,917568,917569,917570,917571,917572,917573,917574,917575,917576,917577,917578,917579,917580,917581,917582,917583,917584,917585,917586,917587,917588,917589,917590,917591,917592,917593,917594,917595,917596,917597,917598,917599,917600,917601,917602,917603,917604,917605,917606,917607,917608,917609,917610,917611,917612,917613,917614,917615,917616,917617,917618,917619,917620,917621,917622,917623,917624,917625,917626,917627,917628,917629,917630,917631,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999]'); + } + static _data = undefined; + static getData() { + if (!this._data) { + this._data = new Set(InvisibleCharacters.getRawData()); + } + return this._data; + } + static isInvisibleCharacter(codePoint) { + return InvisibleCharacters.getData().has(codePoint); + } + static containsInvisibleCharacter(str) { + for (let i = 0; i < str.length; i++) { + const codePoint = str.codePointAt(i); + if (typeof codePoint === 'number' && InvisibleCharacters.isInvisibleCharacter(codePoint)) { + return true; + } + } + return false; + } + static get codePoints() { + return InvisibleCharacters.getData(); + } +} +//# sourceMappingURL=strings.js.map \ No newline at end of file diff --git a/packages/core/dist/strings.js.map b/packages/core/dist/strings.js.map new file mode 100644 index 00000000..3eb36641 --- /dev/null +++ b/packages/core/dist/strings.js.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.js","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAChG,YAAY,CAAC;AAIb,MAAM,CAAC,MAAM,KAAK,GAAG,EAAE,CAAA;AAEvB,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAEzD,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE;IAC1C,MAAM,SAAS,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACjC,OAAO,QAAQ,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAA;AAC5F,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE;IAC7C,MAAM,SAAS,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACjC,OAAO,QAAQ,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC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;IAClD,CAAC;;AAGF,MAAM,OAAO,mBAAmB;IACvB,MAAM,CAAC,UAAU;QACxB,gEAAgE;QAChE,OAAO,IAAI,CAAC,KAAK,CAAC,siGAAsiG,CAAC,CAAC;IAC3jG,CAAC;IAEO,MAAM,CAAC,KAAK,GAA4B,SAAS,CAAC;IAElD,MAAM,CAAC,OAAO;QACrB,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE;YAChB,IAAI,CAAC,KAAK,GAAG,IAAI,GAAG,CAAC,mBAAmB,CAAC,UAAU,EAAE,CAAC,CAAC;SACvD;QACD,OAAO,IAAI,CAAC,KAAK,CAAC;IACnB,CAAC;IAEM,MAAM,CAAC,oBAAoB,CAAC,SAAiB;QACnD,OAAO,mBAAmB,CAAC,OAAO,EAAE,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACrD,CAAC;IAEM,MAAM,CAAC,0BAA0B,CAAC,GAAW;QACnD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACpC,MAAM,SAAS,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;YACrC,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,mBAAmB,CAAC,oBAAoB,CAAC,SAAS,CAAC,EAAE;gBACzF,OAAO,IAAI,CAAC;aACZ;SACD;QACD,OAAO,KAAK,CAAC;IAEd,CAAC;IAEM,MAAM,KAAK,UAAU;QAC3B,OAAO,mBAAmB,CAAC,OAAO,EAAE,CAAC;IACtC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/symbols.d.ts b/packages/core/dist/symbols.d.ts new file mode 100644 index 00000000..aeeaea8a --- /dev/null +++ b/packages/core/dist/symbols.d.ts @@ -0,0 +1,4 @@ +/** + * Can be passed into the Delayed to defer using a microtask + * */ +export declare const MicrotaskDelay: unique symbol; diff --git a/packages/core/dist/symbols.js b/packages/core/dist/symbols.js new file mode 100644 index 00000000..de38e21b --- /dev/null +++ b/packages/core/dist/symbols.js @@ -0,0 +1,9 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +/** + * Can be passed into the Delayed to defer using a microtask + * */ +export const MicrotaskDelay = Symbol('MicrotaskDelay'); +//# sourceMappingURL=symbols.js.map \ No newline at end of file diff --git a/packages/core/dist/symbols.js.map b/packages/core/dist/symbols.js.map new file mode 100644 index 00000000..52ce703b --- /dev/null +++ b/packages/core/dist/symbols.js.map @@ -0,0 +1 @@ +{"version":3,"file":"symbols.js","sourceRoot":"","sources":["../src/symbols.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG;;KAEK;AACL,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/types.d.ts b/packages/core/dist/types.d.ts new file mode 100644 index 00000000..f0616449 --- /dev/null +++ b/packages/core/dist/types.d.ts @@ -0,0 +1,151 @@ +/** + * @returns whether the provided parameter is a JavaScript String or not. + */ +export declare function isString(str: unknown): str is string; +/** + * @returns whether the provided parameter is a JavaScript Array and each element in the array is a string. + */ +export declare function isStringArray(value: unknown): value is string[]; +/** + * @returns whether the provided parameter is of type `object` but **not** + * `null`, an `array`, a `regexp`, nor a `date`. + */ +export declare function isObject(obj: unknown): obj is Object; +/** + * @returns whether the provided parameter is of type `Buffer` or Uint8Array dervived type + */ +export declare function isTypedArray(obj: unknown): obj is Object; +/** + * In **contrast** to just checking `typeof` this will return `false` for `NaN`. + * @returns whether the provided parameter is a JavaScript Number or not. + */ +export declare function isNumber(obj: unknown): obj is number; +/** + * @returns whether the provided parameter is an Iterable, casting to the given generic + */ +export declare function isIterable(obj: unknown): obj is Iterable; +/** + * @returns whether the provided parameter is a JavaScript Boolean or not. + */ +export declare function isBoolean(obj: unknown): obj is boolean; +/** + * @returns whether the provided parameter is undefined. + */ +export declare function isUndefined(obj: unknown): obj is undefined; +/** + * @returns whether the provided parameter is defined. + */ +export declare function isDefined(arg: T | null | undefined): arg is T; +/** + * @returns whether the provided parameter is undefined or null. + */ +export declare function isUndefinedOrNull(obj: unknown): obj is undefined | null; +export declare function assertType(condition: unknown, type?: string): asserts condition; +/** + * Asserts that the argument passed in is neither undefined nor null. + * + * @see {@link assertDefined} for a similar utility that leverages TS assertion functions to narrow down the type of `arg` to be non-nullable. + */ +export declare function assertIsDefined(arg: T | null | undefined): NonNullable; +/** + * Asserts that a provided `value` is `defined` - not `null` or `undefined`, + * throwing an error with the provided error or error message, while also + * narrowing down the type of the `value` to be `NonNullable` using TS + * assertion functions. + * + * @throws if the provided `value` is `null` or `undefined`. + * + * ## Examples + * + * ```typescript + * // an assert with an error message + * assertDefined('some value', 'String constant is not defined o_O.'); + * + * // `throws!` the provided error + * assertDefined(null, new Error('Should throw this error.')); + * + * // narrows down the type of `someValue` to be non-nullable + * const someValue: string | undefined | null = blackbox(); + * assertDefined(someValue, 'Some value must be defined.'); + * console.log(someValue.length); // now type of `someValue` is `string` + * ``` + * + * @see {@link assertIsDefined} for a similar utility but without assertion. + * @see {@link https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions typescript-3-7.html#assertion-functions} + */ +export declare function assertDefined(value: T, error: string | NonNullable): asserts value is NonNullable; +/** + * Asserts that each argument passed in is neither undefined nor null. + */ +export declare function assertAllDefined(t1: T1 | null | undefined, t2: T2 | null | undefined): [T1, T2]; +export declare function assertAllDefined(t1: T1 | null | undefined, t2: T2 | null | undefined, t3: T3 | null | undefined): [T1, T2, T3]; +export declare function assertAllDefined(t1: T1 | null | undefined, t2: T2 | null | undefined, t3: T3 | null | undefined, t4: T4 | null | undefined): [T1, T2, T3, T4]; +/** + * @returns whether the provided parameter is an empty JavaScript Object or not. + */ +export declare function isEmptyObject(obj: unknown): obj is object; +/** + * @returns whether the provided parameter is a JavaScript Function or not. + */ +export declare function isFunction(obj: unknown): obj is Function; +/** + * @returns whether the provided parameters is are JavaScript Function or not. + */ +export declare function areFunctions(...objects: unknown[]): boolean; +export type TypeConstraint = string | Function; +export declare function validateConstraints(args: unknown[], constraints: Array): void; +export declare function validateConstraint(arg: unknown, constraint: TypeConstraint | undefined): void; +/** + * Helper type assertion that safely upcasts a type to a supertype. + * + * This can be used to make sure the argument correctly conforms to the subtype while still being able to pass it + * to contexts that expects the supertype. + */ +export declare function upcast(x: Sub): Base; +type AddFirstParameterToFunction = T extends (...args: any[]) => TargetFunctionsReturnType ? (firstArg: FirstParameter, ...args: Parameters) => ReturnType : T; +/** + * Allows to add a first parameter to functions of a type. + */ +export type AddFirstParameterToFunctions = { + [K in keyof Target]: AddFirstParameterToFunction; +}; +/** + * Given an object with all optional properties, requires at least one to be defined. + * i.e. AtLeastOne; + */ +export type AtLeastOne; +}> = Partial & U[keyof U]; +/** + * Only picks the non-optional properties of a type. + */ +export type OmitOptional = { + [K in keyof T as T[K] extends Required[K] ? K : never]: T[K]; +}; +/** + * A type that removed readonly-less from all properties of `T` + */ +export type Mutable = { + -readonly [P in keyof T]: T[P]; +}; +/** + * A single object or an array of the objects. + */ +export type SingleOrMany = T | T[]; +/** + * A type that recursively makes all properties of `T` required + */ +export type DeepRequiredNonNullable = { + [P in keyof T]-?: T[P] extends object ? DeepRequiredNonNullable : Required>; +}; +/** + * Represents a type that is a partial version of a given type `T`, where all properties are optional and can be deeply nested. + */ +export type DeepPartial = { + [P in keyof T]?: T[P] extends object ? DeepPartial : Partial; +}; +/** + * Represents a type that is a partial version of a given type `T`, except a subset. + */ +export type PartialExcept = Partial> & Pick; +export {}; diff --git a/packages/core/dist/types.js b/packages/core/dist/types.js new file mode 100644 index 00000000..0d16edfd --- /dev/null +++ b/packages/core/dist/types.js @@ -0,0 +1,200 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import { assert } from './assert.js'; +/** + * @returns whether the provided parameter is a JavaScript String or not. + */ +export function isString(str) { + return (typeof str === 'string'); +} +/** + * @returns whether the provided parameter is a JavaScript Array and each element in the array is a string. + */ +export function isStringArray(value) { + return Array.isArray(value) && value.every(elem => isString(elem)); +} +/** + * @returns whether the provided parameter is of type `object` but **not** + * `null`, an `array`, a `regexp`, nor a `date`. + */ +export function isObject(obj) { + // The method can't do a type cast since there are type (like strings) which + // are subclasses of any put not positvely matched by the function. Hence type + // narrowing results in wrong results. + return typeof obj === 'object' + && obj !== null + && !Array.isArray(obj) + && !(obj instanceof RegExp) + && !(obj instanceof Date); +} +/** + * @returns whether the provided parameter is of type `Buffer` or Uint8Array dervived type + */ +export function isTypedArray(obj) { + const TypedArray = Object.getPrototypeOf(Uint8Array); + return typeof obj === 'object' + && obj instanceof TypedArray; +} +/** + * In **contrast** to just checking `typeof` this will return `false` for `NaN`. + * @returns whether the provided parameter is a JavaScript Number or not. + */ +export function isNumber(obj) { + return (typeof obj === 'number' && !isNaN(obj)); +} +/** + * @returns whether the provided parameter is an Iterable, casting to the given generic + */ +export function isIterable(obj) { + return !!obj && typeof obj[Symbol.iterator] === 'function'; +} +/** + * @returns whether the provided parameter is a JavaScript Boolean or not. + */ +export function isBoolean(obj) { + return (obj === true || obj === false); +} +/** + * @returns whether the provided parameter is undefined. + */ +export function isUndefined(obj) { + return (typeof obj === 'undefined'); +} +/** + * @returns whether the provided parameter is defined. + */ +export function isDefined(arg) { + return !isUndefinedOrNull(arg); +} +/** + * @returns whether the provided parameter is undefined or null. + */ +export function isUndefinedOrNull(obj) { + return (isUndefined(obj) || obj === null); +} +export function assertType(condition, type) { + if (!condition) { + throw new Error(type ? `Unexpected type, expected '${type}'` : 'Unexpected type'); + } +} +/** + * Asserts that the argument passed in is neither undefined nor null. + * + * @see {@link assertDefined} for a similar utility that leverages TS assertion functions to narrow down the type of `arg` to be non-nullable. + */ +export function assertIsDefined(arg) { + assert(arg !== null && arg !== undefined, 'Argument is `undefined` or `null`.'); + return arg; +} +/** + * Asserts that a provided `value` is `defined` - not `null` or `undefined`, + * throwing an error with the provided error or error message, while also + * narrowing down the type of the `value` to be `NonNullable` using TS + * assertion functions. + * + * @throws if the provided `value` is `null` or `undefined`. + * + * ## Examples + * + * ```typescript + * // an assert with an error message + * assertDefined('some value', 'String constant is not defined o_O.'); + * + * // `throws!` the provided error + * assertDefined(null, new Error('Should throw this error.')); + * + * // narrows down the type of `someValue` to be non-nullable + * const someValue: string | undefined | null = blackbox(); + * assertDefined(someValue, 'Some value must be defined.'); + * console.log(someValue.length); // now type of `someValue` is `string` + * ``` + * + * @see {@link assertIsDefined} for a similar utility but without assertion. + * @see {@link https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions typescript-3-7.html#assertion-functions} + */ +export function assertDefined(value, error) { + if (value === null || value === undefined) { + const errorToThrow = typeof error === 'string' ? new Error(error) : error; + throw errorToThrow; + } +} +export function assertAllDefined(...args) { + const result = []; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (isUndefinedOrNull(arg)) { + throw new Error(`Assertion Failed: argument at index ${i} is undefined or null`); + } + result.push(arg); + } + return result; +} +const hasOwnProperty = Object.prototype.hasOwnProperty; +/** + * @returns whether the provided parameter is an empty JavaScript Object or not. + */ +export function isEmptyObject(obj) { + if (!isObject(obj)) { + return false; + } + for (const key in obj) { + if (hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} +/** + * @returns whether the provided parameter is a JavaScript Function or not. + */ +export function isFunction(obj) { + return (typeof obj === 'function'); +} +/** + * @returns whether the provided parameters is are JavaScript Function or not. + */ +export function areFunctions(...objects) { + return objects.length > 0 && objects.every(isFunction); +} +export function validateConstraints(args, constraints) { + const len = Math.min(args.length, constraints.length); + for (let i = 0; i < len; i++) { + validateConstraint(args[i], constraints[i]); + } +} +export function validateConstraint(arg, constraint) { + if (isString(constraint)) { + if (typeof arg !== constraint) { + throw new Error(`argument does not match constraint: typeof ${constraint}`); + } + } + else if (isFunction(constraint)) { + try { + if (arg instanceof constraint) { + return; + } + } + catch { + // ignore + } + if (!isUndefinedOrNull(arg) && arg.constructor === constraint) { + return; + } + if (constraint.length === 1 && constraint.call(undefined, arg) === true) { + return; + } + throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`); + } +} +/** + * Helper type assertion that safely upcasts a type to a supertype. + * + * This can be used to make sure the argument correctly conforms to the subtype while still being able to pass it + * to contexts that expects the supertype. + */ +export function upcast(x) { + return x; +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/packages/core/dist/types.js.map b/packages/core/dist/types.js.map new file mode 100644 index 00000000..46c2be48 --- /dev/null +++ b/packages/core/dist/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC;;GAEG;AACH,MAAM,UAAU,QAAQ,CAAC,GAAY;IACpC,OAAO,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC;AAClC,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,KAAc;IAC3C,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAgB,KAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AACjF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,QAAQ,CAAC,GAAY;IACpC,4EAA4E;IAC5E,8EAA8E;IAC9E,sCAAsC;IACtC,OAAO,OAAO,GAAG,KAAK,QAAQ;WAC1B,GAAG,KAAK,IAAI;WACZ,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;WACnB,CAAC,CAAC,GAAG,YAAY,MAAM,CAAC;WACxB,CAAC,CAAC,GAAG,YAAY,IAAI,CAAC,CAAC;AAC5B,C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E,OAAO;SACP;QACD,MAAM,IAAI,KAAK,CAAC,2IAA2I,CAAC,CAAC;KAC7J;AACF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAgC,CAAM;IAC3D,OAAO,CAAC,CAAC;AACV,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/uint.d.ts b/packages/core/dist/uint.d.ts new file mode 100644 index 00000000..f7c03e2d --- /dev/null +++ b/packages/core/dist/uint.d.ts @@ -0,0 +1,31 @@ +export declare const enum Constants { + /** + * MAX SMI (SMall Integer) as defined in v8. + * one bit is lost for boxing/unboxing flag. + * one bit is lost for sign flag. + * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values + */ + MAX_SAFE_SMALL_INTEGER = 1073741824, + /** + * MIN SMI (SMall Integer) as defined in v8. + * one bit is lost for boxing/unboxing flag. + * one bit is lost for sign flag. + * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values + */ + MIN_SAFE_SMALL_INTEGER = -1073741824, + /** + * Max unsigned integer that fits on 8 bits. + */ + MAX_UINT_8 = 255, + /** + * Max unsigned integer that fits on 16 bits. + */ + MAX_UINT_16 = 65535, + /** + * Max unsigned integer that fits on 32 bits. + */ + MAX_UINT_32 = 4294967295, + UNICODE_SUPPLEMENTARY_PLANE_BEGIN = 65536 +} +export declare function toUint8(v: number): number; +export declare function toUint32(v: number): number; diff --git a/packages/core/dist/uint.js b/packages/core/dist/uint.js new file mode 100644 index 00000000..66040bce --- /dev/null +++ b/packages/core/dist/uint.js @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +export var Constants; +(function (Constants) { + /** + * MAX SMI (SMall Integer) as defined in v8. + * one bit is lost for boxing/unboxing flag. + * one bit is lost for sign flag. + * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values + */ + Constants[Constants["MAX_SAFE_SMALL_INTEGER"] = 1073741824] = "MAX_SAFE_SMALL_INTEGER"; + /** + * MIN SMI (SMall Integer) as defined in v8. + * one bit is lost for boxing/unboxing flag. + * one bit is lost for sign flag. + * See https://thibaultlaurens.github.io/javascript/2013/04/29/how-the-v8-engine-works/#tagged-values + */ + Constants[Constants["MIN_SAFE_SMALL_INTEGER"] = -1073741824] = "MIN_SAFE_SMALL_INTEGER"; + /** + * Max unsigned integer that fits on 8 bits. + */ + Constants[Constants["MAX_UINT_8"] = 255] = "MAX_UINT_8"; + /** + * Max unsigned integer that fits on 16 bits. + */ + Constants[Constants["MAX_UINT_16"] = 65535] = "MAX_UINT_16"; + /** + * Max unsigned integer that fits on 32 bits. + */ + Constants[Constants["MAX_UINT_32"] = 4294967295] = "MAX_UINT_32"; + Constants[Constants["UNICODE_SUPPLEMENTARY_PLANE_BEGIN"] = 65536] = "UNICODE_SUPPLEMENTARY_PLANE_BEGIN"; +})(Constants = Constants || (Constants = {})); +export function toUint8(v) { + if (v < 0) { + return 0; + } + if (v > 255 /* Constants.MAX_UINT_8 */) { + return 255 /* Constants.MAX_UINT_8 */; + } + return v | 0; +} +export function toUint32(v) { + if (v < 0) { + return 0; + } + if (v > 4294967295 /* Constants.MAX_UINT_32 */) { + return 4294967295 /* Constants.MAX_UINT_32 */; + } + return v | 0; +} +//# sourceMappingURL=uint.js.map \ No newline at end of file diff --git a/packages/core/dist/uint.js.map b/packages/core/dist/uint.js.map new file mode 100644 index 00000000..466b2e32 --- /dev/null +++ b/packages/core/dist/uint.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uint.js","sourceRoot":"","sources":["../src/uint.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAEhG,MAAM,CAAN,IAAkB,SAiCjB;AAjCD,WAAkB,SAAS;IAC1B;;;;;OAKG;IACH,sFAAgC,CAAA;IAEhC;;;;;OAKG;IACH,uFAAmC,CAAA;IAEnC;;OAEG;IACH,uDAAgB,CAAA;IAEhB;;OAEG;IACH,2DAAmB,CAAA;IAEnB;;OAEG;IACH,gEAAwB,CAAA;IAExB,uGAA4C,CAAA;AAC7C,CAAC,EAjCiB,SAAS,GAAT,SAAS,KAAT,SAAS,QAiC1B;AAED,MAAM,UAAU,OAAO,CAAC,CAAS;IAChC,IAAI,CAAC,GAAG,CAAC,EAAE;QACV,OAAO,CAAC,CAAC;KACT;IACD,IAAI,CAAC,iCAAuB,EAAE;QAC7B,sCAA4B;KAC5B;IACD,OAAO,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,CAAS;IACjC,IAAI,CAAC,GAAG,CAAC,EAAE;QACV,OAAO,CAAC,CAAC;KACT;IACD,IAAI,CAAC,yCAAwB,EAAE;QAC9B,8CAA6B;KAC7B;IACD,OAAO,CAAC,GAAG,CAAC,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/uri.d.ts b/packages/core/dist/uri.d.ts new file mode 100644 index 00000000..c75decdf --- /dev/null +++ b/packages/core/dist/uri.d.ts @@ -0,0 +1,163 @@ +/** + * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986. + * This class is a simple parser which creates the basic component parts + * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation + * and encoding. + * + * ```txt + * foo://example.com:8042/over/there?name=ferret#nose + * \_/ \______________/\_________/ \_________/ \__/ + * | | | | | + * scheme authority path query fragment + * | _____________________|__ + * / \ / \ + * urn:example:animal:ferret:nose + * ``` + */ +export declare class URI implements UriComponents { + static isUri(thing: any): thing is URI; + /** + * scheme is the 'http' part of 'http://www.example.com/some/path?query#fragment'. + * The part before the first colon. + */ + readonly scheme: string; + /** + * authority is the 'www.example.com' part of 'http://www.example.com/some/path?query#fragment'. + * The part between the first double slashes and the next slash. + */ + readonly authority: string; + /** + * path is the '/some/path' part of 'http://www.example.com/some/path?query#fragment'. + */ + readonly path: string; + /** + * query is the 'query' part of 'http://www.example.com/some/path?query#fragment'. + */ + readonly query: string; + /** + * fragment is the 'fragment' part of 'http://www.example.com/some/path?query#fragment'. + */ + readonly fragment: string; + /** + * Returns a string representing the corresponding file system path of this URI. + * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the + * platform specific path separator. + * + * * Will *not* validate the path for invalid characters and semantics. + * * Will *not* look at the scheme of this URI. + * * The result shall *not* be used for display purposes but for accessing a file on disk. + * + * + * The *difference* to `URI#path` is the use of the platform specific separator and the handling + * of UNC paths. See the below sample of a file-uri with an authority (UNC path). + * + * ```ts + const u = URI.parse('file://server/c$/folder/file.txt') + u.authority === 'server' + u.path === '/shares/c$/file.txt' + u.fsPath === '\\server\c$\folder\file.txt' + ``` + * + * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path, + * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working + * with URIs that represent files on disk (`file` scheme). + */ + get fsPath(): string; + with(change: { + scheme?: string; + authority?: string | null; + path?: string | null; + query?: string | null; + fragment?: string | null; + }): URI; + /** + * Creates a new URI from a string, e.g. `http://www.example.com/some/path`, + * `file:///usr/home`, or `scheme:with/path`. + * + * @param value A string which represents an URI (see `URI#toString`). + */ + static parse(value: string, _strict?: boolean): URI; + /** + * Creates a new URI from a file system path, e.g. `c:\my\files`, + * `/usr/home`, or `\\server\share\some\path`. + * + * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument + * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as** + * `URI.parse('file://' + path)` because the path might contain characters that are + * interpreted (# and ?). See the following sample: + * ```ts + const good = URI.file('/coding/c#/project1'); + good.scheme === 'file'; + good.path === '/coding/c#/project1'; + good.fragment === ''; + const bad = URI.parse('file://' + '/coding/c#/project1'); + bad.scheme === 'file'; + bad.path === '/coding/c'; // path is now broken + bad.fragment === '/project1'; + ``` + * + * @param path A file system path (see `URI#fsPath`) + */ + static file(path: string): URI; + /** + * Creates new URI from uri components. + * + * Unless `strict` is `true` the scheme is defaults to be `file`. This function performs + * validation and should be used for untrusted uri components retrieved from storage, + * user input, command arguments etc + */ + static from(components: UriComponents, strict?: boolean): URI; + /** + * Join a URI path with path fragments and normalizes the resulting path. + * + * @param uri The input URI. + * @param pathFragment The path fragment to add to the URI path. + * @returns The resulting URI. + */ + static joinPath(uri: URI, ...pathFragment: string[]): URI; + /** + * Creates a string representation for this URI. It's guaranteed that calling + * `URI.parse` with the result of this function creates an URI which is equal + * to this URI. + * + * * The result shall *not* be used for display purposes but for externalization or transport. + * * The result will be encoded using the percentage encoding and encoding happens mostly + * ignore the scheme-specific encoding rules. + * + * @param skipEncoding Do not encode the result, default is `false` + */ + toString(skipEncoding?: boolean): string; + toJSON(): UriComponents; + /** + * A helper function to revive URIs. + * + * **Note** that this function should only be used when receiving URI#toJSON generated data + * and that it doesn't do any validation. Use {@link URI.from} when received "untrusted" + * uri components such as command arguments or data from storage. + * + * @param data The URI components or URI to revive. + * @returns The revived URI or undefined or null. + */ + static revive(data: UriComponents | URI): URI; + static revive(data: UriComponents | URI | undefined): URI | undefined; + static revive(data: UriComponents | URI | null): URI | null; + static revive(data: UriComponents | URI | undefined | null): URI | undefined | null; +} +export interface UriComponents { + scheme: string; + authority?: string; + path?: string; + query?: string; + fragment?: string; +} +export declare function isUriComponents(thing: any): thing is UriComponents; +/** + * Compute `fsPath` for the given uri + */ +export declare function uriToFsPath(uri: URI, keepDriveLetterCasing: boolean): string; +/** + * Mapped-type that replaces all occurrences of URI with UriComponents + */ +export type UriDto = { + [K in keyof T]: T[K] extends URI ? UriComponents : UriDto; +}; diff --git a/packages/core/dist/uri.js b/packages/core/dist/uri.js new file mode 100644 index 00000000..037b5962 --- /dev/null +++ b/packages/core/dist/uri.js @@ -0,0 +1,636 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import * as paths from './path.js'; +import { isWindows } from './platform.js'; +const _schemePattern = /^\w[\w\d+.-]*$/; +const _singleSlashStart = /^\//; +const _doubleSlashStart = /^\/\//; +function _validateUri(ret, _strict) { + // scheme, must be set + if (!ret.scheme && _strict) { + throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`); + } + // scheme, https://tools.ietf.org/html/rfc3986#section-3.1 + // ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + if (ret.scheme && !_schemePattern.test(ret.scheme)) { + throw new Error('[UriError]: Scheme contains illegal characters.'); + } + // path, http://tools.ietf.org/html/rfc3986#section-3.3 + // If a URI contains an authority component, then the path component + // must either be empty or begin with a slash ("/") character. If a URI + // does not contain an authority component, then the path cannot begin + // with two slash characters ("//"). + if (ret.path) { + if (ret.authority) { + if (!_singleSlashStart.test(ret.path)) { + throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character'); + } + } + else { + if (_doubleSlashStart.test(ret.path)) { + throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")'); + } + } + } +} +// for a while we allowed uris *without* schemes and this is the migration +// for them, e.g. an uri without scheme and without strict-mode warns and falls +// back to the file-scheme. that should cause the least carnage and still be a +// clear warning +function _schemeFix(scheme, _strict) { + if (!scheme && !_strict) { + return 'file'; + } + return scheme; +} +// implements a bit of https://tools.ietf.org/html/rfc3986#section-5 +function _referenceResolution(scheme, path) { + // the slash-character is our 'default base' as we don't + // support constructing URIs relative to other URIs. This + // also means that we alter and potentially break paths. + // see https://tools.ietf.org/html/rfc3986#section-5.1.4 + switch (scheme) { + case 'https': + case 'http': + case 'file': + if (!path) { + path = _slash; + } + else if (path[0] !== _slash) { + path = _slash + path; + } + break; + } + return path; +} +const _empty = ''; +const _slash = '/'; +const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; +/** + * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986. + * This class is a simple parser which creates the basic component parts + * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation + * and encoding. + * + * ```txt + * foo://example.com:8042/over/there?name=ferret#nose + * \_/ \______________/\_________/ \_________/ \__/ + * | | | | | + * scheme authority path query fragment + * | _____________________|__ + * / \ / \ + * urn:example:animal:ferret:nose + * ``` + */ +export class URI { + static isUri(thing) { + if (thing instanceof URI) { + return true; + } + if (!thing) { + return false; + } + return typeof thing.authority === 'string' + && typeof thing.fragment === 'string' + && typeof thing.path === 'string' + && typeof thing.query === 'string' + && typeof thing.scheme === 'string' + && typeof thing.fsPath === 'string' + && typeof thing.with === 'function' + && typeof thing.toString === 'function'; + } + /** + * scheme is the 'http' part of 'http://www.example.com/some/path?query#fragment'. + * The part before the first colon. + */ + scheme; + /** + * authority is the 'www.example.com' part of 'http://www.example.com/some/path?query#fragment'. + * The part between the first double slashes and the next slash. + */ + authority; + /** + * path is the '/some/path' part of 'http://www.example.com/some/path?query#fragment'. + */ + path; + /** + * query is the 'query' part of 'http://www.example.com/some/path?query#fragment'. + */ + query; + /** + * fragment is the 'fragment' part of 'http://www.example.com/some/path?query#fragment'. + */ + fragment; + /** + * @internal + */ + constructor(schemeOrData, authority, path, query, fragment, _strict = false) { + if (typeof schemeOrData === 'object') { + this.scheme = schemeOrData.scheme || _empty; + this.authority = schemeOrData.authority || _empty; + this.path = schemeOrData.path || _empty; + this.query = schemeOrData.query || _empty; + this.fragment = schemeOrData.fragment || _empty; + // no validation because it's this URI + // that creates uri components. + // _validateUri(this); + } + else { + this.scheme = _schemeFix(schemeOrData, _strict); + this.authority = authority || _empty; + this.path = _referenceResolution(this.scheme, path || _empty); + this.query = query || _empty; + this.fragment = fragment || _empty; + _validateUri(this, _strict); + } + } + // ---- filesystem path ----------------------- + /** + * Returns a string representing the corresponding file system path of this URI. + * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the + * platform specific path separator. + * + * * Will *not* validate the path for invalid characters and semantics. + * * Will *not* look at the scheme of this URI. + * * The result shall *not* be used for display purposes but for accessing a file on disk. + * + * + * The *difference* to `URI#path` is the use of the platform specific separator and the handling + * of UNC paths. See the below sample of a file-uri with an authority (UNC path). + * + * ```ts + const u = URI.parse('file://server/c$/folder/file.txt') + u.authority === 'server' + u.path === '/shares/c$/file.txt' + u.fsPath === '\\server\c$\folder\file.txt' + ``` + * + * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path, + * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working + * with URIs that represent files on disk (`file` scheme). + */ + get fsPath() { + // if (this.scheme !== 'file') { + // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`); + // } + return uriToFsPath(this, false); + } + // ---- modify to new ------------------------- + with(change) { + if (!change) { + return this; + } + let { scheme, authority, path, query, fragment } = change; + if (scheme === undefined) { + scheme = this.scheme; + } + else if (scheme === null) { + scheme = _empty; + } + if (authority === undefined) { + authority = this.authority; + } + else if (authority === null) { + authority = _empty; + } + if (path === undefined) { + path = this.path; + } + else if (path === null) { + path = _empty; + } + if (query === undefined) { + query = this.query; + } + else if (query === null) { + query = _empty; + } + if (fragment === undefined) { + fragment = this.fragment; + } + else if (fragment === null) { + fragment = _empty; + } + if (scheme === this.scheme + && authority === this.authority + && path === this.path + && query === this.query + && fragment === this.fragment) { + return this; + } + return new Uri(scheme, authority, path, query, fragment); + } + // ---- parse & validate ------------------------ + /** + * Creates a new URI from a string, e.g. `http://www.example.com/some/path`, + * `file:///usr/home`, or `scheme:with/path`. + * + * @param value A string which represents an URI (see `URI#toString`). + */ + static parse(value, _strict = false) { + const match = _regexp.exec(value); + if (!match) { + return new Uri(_empty, _empty, _empty, _empty, _empty); + } + return new Uri(match[2] || _empty, percentDecode(match[4] || _empty), percentDecode(match[5] || _empty), percentDecode(match[7] || _empty), percentDecode(match[9] || _empty), _strict); + } + /** + * Creates a new URI from a file system path, e.g. `c:\my\files`, + * `/usr/home`, or `\\server\share\some\path`. + * + * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument + * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as** + * `URI.parse('file://' + path)` because the path might contain characters that are + * interpreted (# and ?). See the following sample: + * ```ts + const good = URI.file('/coding/c#/project1'); + good.scheme === 'file'; + good.path === '/coding/c#/project1'; + good.fragment === ''; + const bad = URI.parse('file://' + '/coding/c#/project1'); + bad.scheme === 'file'; + bad.path === '/coding/c'; // path is now broken + bad.fragment === '/project1'; + ``` + * + * @param path A file system path (see `URI#fsPath`) + */ + static file(path) { + let authority = _empty; + // normalize to fwd-slashes on windows, + // on other systems bwd-slashes are valid + // filename character, eg /f\oo/ba\r.txt + if (isWindows) { + path = path.replace(/\\/g, _slash); + } + // check for authority as used in UNC shares + // or use the path as given + if (path[0] === _slash && path[1] === _slash) { + const idx = path.indexOf(_slash, 2); + if (idx === -1) { + authority = path.substring(2); + path = _slash; + } + else { + authority = path.substring(2, idx); + path = path.substring(idx) || _slash; + } + } + return new Uri('file', authority, path, _empty, _empty); + } + /** + * Creates new URI from uri components. + * + * Unless `strict` is `true` the scheme is defaults to be `file`. This function performs + * validation and should be used for untrusted uri components retrieved from storage, + * user input, command arguments etc + */ + static from(components, strict) { + const result = new Uri(components.scheme, components.authority, components.path, components.query, components.fragment, strict); + return result; + } + /** + * Join a URI path with path fragments and normalizes the resulting path. + * + * @param uri The input URI. + * @param pathFragment The path fragment to add to the URI path. + * @returns The resulting URI. + */ + static joinPath(uri, ...pathFragment) { + if (!uri.path) { + throw new Error(`[UriError]: cannot call joinPath on URI without path`); + } + let newPath; + if (isWindows && uri.scheme === 'file') { + newPath = URI.file(paths.win32.join(uriToFsPath(uri, true), ...pathFragment)).path; + } + else { + newPath = paths.posix.join(uri.path, ...pathFragment); + } + return uri.with({ path: newPath }); + } + // ---- printing/externalize --------------------------- + /** + * Creates a string representation for this URI. It's guaranteed that calling + * `URI.parse` with the result of this function creates an URI which is equal + * to this URI. + * + * * The result shall *not* be used for display purposes but for externalization or transport. + * * The result will be encoded using the percentage encoding and encoding happens mostly + * ignore the scheme-specific encoding rules. + * + * @param skipEncoding Do not encode the result, default is `false` + */ + toString(skipEncoding = false) { + return _asFormatted(this, skipEncoding); + } + toJSON() { + return this; + } + static revive(data) { + if (!data) { + return data; + } + else if (data instanceof URI) { + return data; + } + else { + const result = new Uri(data); + result._formatted = data.external ?? null; + result._fsPath = data._sep === _pathSepMarker ? data.fsPath ?? null : null; + return result; + } + } + [Symbol.for('debug.description')]() { + return `URI(${this.toString()})`; + } +} +export function isUriComponents(thing) { + if (!thing || typeof thing !== 'object') { + return false; + } + return typeof thing.scheme === 'string' + && (typeof thing.authority === 'string' || typeof thing.authority === 'undefined') + && (typeof thing.path === 'string' || typeof thing.path === 'undefined') + && (typeof thing.query === 'string' || typeof thing.query === 'undefined') + && (typeof thing.fragment === 'string' || typeof thing.fragment === 'undefined'); +} +const _pathSepMarker = isWindows ? 1 : undefined; +// This class exists so that URI is compatible with vscode.Uri (API). +class Uri extends URI { + _formatted = null; + _fsPath = null; + get fsPath() { + if (!this._fsPath) { + this._fsPath = uriToFsPath(this, false); + } + return this._fsPath; + } + toString(skipEncoding = false) { + if (!skipEncoding) { + if (!this._formatted) { + this._formatted = _asFormatted(this, false); + } + return this._formatted; + } + else { + // we don't cache that + return _asFormatted(this, true); + } + } + toJSON() { + // eslint-disable-next-line local/code-no-dangerous-type-assertions + const res = { + $mid: 1 /* MarshalledId.Uri */ + }; + // cached state + if (this._fsPath) { + res.fsPath = this._fsPath; + res._sep = _pathSepMarker; + } + if (this._formatted) { + res.external = this._formatted; + } + //--- uri components + if (this.path) { + res.path = this.path; + } + // TODO + // this isn't correct and can violate the UriComponents contract but + // this is part of the vscode.Uri API and we shouldn't change how that + // works anymore + if (this.scheme) { + res.scheme = this.scheme; + } + if (this.authority) { + res.authority = this.authority; + } + if (this.query) { + res.query = this.query; + } + if (this.fragment) { + res.fragment = this.fragment; + } + return res; + } +} +// reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2 +const encodeTable = { + [58 /* CharCode.Colon */]: '%3A', + [47 /* CharCode.Slash */]: '%2F', + [63 /* CharCode.QuestionMark */]: '%3F', + [35 /* CharCode.Hash */]: '%23', + [91 /* CharCode.OpenSquareBracket */]: '%5B', + [93 /* CharCode.CloseSquareBracket */]: '%5D', + [64 /* CharCode.AtSign */]: '%40', + [33 /* CharCode.ExclamationMark */]: '%21', + [36 /* CharCode.DollarSign */]: '%24', + [38 /* CharCode.Ampersand */]: '%26', + [39 /* CharCode.SingleQuote */]: '%27', + [40 /* CharCode.OpenParen */]: '%28', + [41 /* CharCode.CloseParen */]: '%29', + [42 /* CharCode.Asterisk */]: '%2A', + [43 /* CharCode.Plus */]: '%2B', + [44 /* CharCode.Comma */]: '%2C', + [59 /* CharCode.Semicolon */]: '%3B', + [61 /* CharCode.Equals */]: '%3D', + [32 /* CharCode.Space */]: '%20', +}; +function encodeURIComponentFast(uriComponent, isPath, isAuthority) { + let res = undefined; + let nativeEncodePos = -1; + for (let pos = 0; pos < uriComponent.length; pos++) { + const code = uriComponent.charCodeAt(pos); + // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3 + if ((code >= 97 /* CharCode.a */ && code <= 122 /* CharCode.z */) + || (code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */) + || (code >= 48 /* CharCode.Digit0 */ && code <= 57 /* CharCode.Digit9 */) + || code === 45 /* CharCode.Dash */ + || code === 46 /* CharCode.Period */ + || code === 95 /* CharCode.Underline */ + || code === 126 /* CharCode.Tilde */ + || (isPath && code === 47 /* CharCode.Slash */) + || (isAuthority && code === 91 /* CharCode.OpenSquareBracket */) + || (isAuthority && code === 93 /* CharCode.CloseSquareBracket */) + || (isAuthority && code === 58 /* CharCode.Colon */)) { + // check if we are delaying native encode + if (nativeEncodePos !== -1) { + res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); + nativeEncodePos = -1; + } + // check if we write into a new string (by default we try to return the param) + if (res !== undefined) { + res += uriComponent.charAt(pos); + } + } + else { + // encoding needed, we need to allocate a new string + if (res === undefined) { + res = uriComponent.substr(0, pos); + } + // check with default table first + const escaped = encodeTable[code]; + if (escaped !== undefined) { + // check if we are delaying native encode + if (nativeEncodePos !== -1) { + res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); + nativeEncodePos = -1; + } + // append escaped variant to result + res += escaped; + } + else if (nativeEncodePos === -1) { + // use native encode only when needed + nativeEncodePos = pos; + } + } + } + if (nativeEncodePos !== -1) { + res += encodeURIComponent(uriComponent.substring(nativeEncodePos)); + } + return res !== undefined ? res : uriComponent; +} +function encodeURIComponentMinimal(path) { + let res = undefined; + for (let pos = 0; pos < path.length; pos++) { + const code = path.charCodeAt(pos); + if (code === 35 /* CharCode.Hash */ || code === 63 /* CharCode.QuestionMark */) { + if (res === undefined) { + res = path.substr(0, pos); + } + res += encodeTable[code]; + } + else { + if (res !== undefined) { + res += path[pos]; + } + } + } + return res !== undefined ? res : path; +} +/** + * Compute `fsPath` for the given uri + */ +export function uriToFsPath(uri, keepDriveLetterCasing) { + let value; + if (uri.authority && uri.path.length > 1 && uri.scheme === 'file') { + // unc path: file://shares/c$/far/boo + value = `//${uri.authority}${uri.path}`; + } + else if (uri.path.charCodeAt(0) === 47 /* CharCode.Slash */ + && (uri.path.charCodeAt(1) >= 65 /* CharCode.A */ && uri.path.charCodeAt(1) <= 90 /* CharCode.Z */ || uri.path.charCodeAt(1) >= 97 /* CharCode.a */ && uri.path.charCodeAt(1) <= 122 /* CharCode.z */) + && uri.path.charCodeAt(2) === 58 /* CharCode.Colon */) { + if (!keepDriveLetterCasing) { + // windows drive letter: file:///c:/far/boo + value = uri.path[1].toLowerCase() + uri.path.substr(2); + } + else { + value = uri.path.substr(1); + } + } + else { + // other path + value = uri.path; + } + if (isWindows) { + value = value.replace(/\//g, '\\'); + } + return value; +} +/** + * Create the external version of a uri + */ +function _asFormatted(uri, skipEncoding) { + const encoder = !skipEncoding + ? encodeURIComponentFast + : encodeURIComponentMinimal; + let res = ''; + let { scheme, authority, path, query, fragment } = uri; + if (scheme) { + res += scheme; + res += ':'; + } + if (authority || scheme === 'file') { + res += _slash; + res += _slash; + } + if (authority) { + let idx = authority.indexOf('@'); + if (idx !== -1) { + // @ + const userinfo = authority.substr(0, idx); + authority = authority.substr(idx + 1); + idx = userinfo.lastIndexOf(':'); + if (idx === -1) { + res += encoder(userinfo, false, false); + } + else { + // :@ + res += encoder(userinfo.substr(0, idx), false, false); + res += ':'; + res += encoder(userinfo.substr(idx + 1), false, true); + } + res += '@'; + } + authority = authority.toLowerCase(); + idx = authority.lastIndexOf(':'); + if (idx === -1) { + res += encoder(authority, false, true); + } + else { + // : + res += encoder(authority.substr(0, idx), false, true); + res += authority.substr(idx); + } + } + if (path) { + // lower-case windows drive letters in /C:/fff or C:/fff + if (path.length >= 3 && path.charCodeAt(0) === 47 /* CharCode.Slash */ && path.charCodeAt(2) === 58 /* CharCode.Colon */) { + const code = path.charCodeAt(1); + if (code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */) { + path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; // "/c:".length === 3 + } + } + else if (path.length >= 2 && path.charCodeAt(1) === 58 /* CharCode.Colon */) { + const code = path.charCodeAt(0); + if (code >= 65 /* CharCode.A */ && code <= 90 /* CharCode.Z */) { + path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; // "/c:".length === 3 + } + } + // encode the rest of the path + res += encoder(path, true, false); + } + if (query) { + res += '?'; + res += encoder(query, false, false); + } + if (fragment) { + res += '#'; + res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment; + } + return res; +} +// --- decode +function decodeURIComponentGraceful(str) { + try { + return decodeURIComponent(str); + } + catch { + if (str.length > 3) { + return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3)); + } + else { + return str; + } + } +} +const _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g; +function percentDecode(str) { + if (!str.match(_rEncodedAsHex)) { + return str; + } + return str.replace(_rEncodedAsHex, (match) => decodeURIComponentGraceful(match)); +} +//# sourceMappingURL=uri.js.map \ No newline at end of file diff --git a/packages/core/dist/uri.js.map b/packages/core/dist/uri.js.map new file mode 100644 index 00000000..a6080e8e --- /dev/null +++ b/packages/core/dist/uri.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uri.js","sourceRoot":"","sources":["../src/uri.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAIhG,OAAO,KAAK,KAAK,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C,MAAM,cAAc,GAAG,gBAAgB,CAAC;AACxC,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAChC,MAAM,iBAAiB,GAAG,OAAO,CAAC;AAElC,SAAS,YAAY,CAAC,GAAQ,EAAE,OAAiB;IAEhD,sBAAsB;IACtB,IAAI,CAAC,GAAG,CAAC,MAAM,IAAI,OAAO,EAAE;QAC3B,MAAM,IAAI,KAAK,CAAC,2DAA2D,GAAG,CAAC,SAAS,aAAa,GAAG,CAAC,IAAI,cAAc,GAAG,CAAC,KAAK,iBAAiB,GAAG,CAAC,QAAQ,IAAI,CAAC,CAAC;KACvK;IAED,0DAA0D;IAC1D,6CAA6C;IAC7C,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;QACnD,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;KACnE;IAED,uDAAuD;IACvD,oEAAoE;IACpE,wEAAwE;IACxE,sEAAsE;IACtE,oCAAoC;IACpC,IAAI,GAAG,CAAC,IAAI,EAAE;QACb,IAAI,GAAG,CAAC,SAAS,EAAE;YAClB,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;gBACtC,MAAM,IAAI,KAAK,CAAC,0IAA0I,CAAC,CAAC;aAC5J;SACD;aAAM;YACN,IAAI,iBAAiB,CAAC,I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CAAC,cAAc,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,0BAA0B,CAAC,KAAK,CAAC,CAAC,CAAC;AAClF,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/utils.d.ts b/packages/core/dist/utils.d.ts new file mode 100644 index 00000000..396efd15 --- /dev/null +++ b/packages/core/dist/utils.d.ts @@ -0,0 +1,76 @@ +/// +export declare function StingEnum(o: Array): { + [K in T]: K; +}; +export declare const DefaultDelimiter: { + begin: string; + end: string; +}; +export declare const hasFlag: (field: any, enumValue: any) => boolean; +export declare const hasFlagHex: (field: any, enumValue: any) => boolean; +export declare const disableFlag: (enumValue: any, field: any) => any; +/** + * The minimum location of high surrogates + */ +export declare const HIGH_SURROGATE_MIN = 55296; +/** + * The maximum location of high surrogates + */ +export declare const HIGH_SURROGATE_MAX = 56319; +/** + * The minimum location of low surrogates + */ +export declare const LOW_SURROGATE_MIN = 56320; +/** + * The maximum location of low surrogates + */ +export declare const LOW_SURROGATE_MAX = 57343; +export declare const capitalize: (word: any) => any; +export declare const getJson: (inData: any, validOnly: any, ommit: any) => any; +/** + * Escapes a string so that it can safely be passed to the RegExp constructor. + * @param text The string to be escaped + * @return The escaped string + */ +export declare function escapeRegExpEx(text: string): string; +/** + * Sanitizes a string to protect against tag injection. + * @param xml The string to be escaped + * @param forAttribute Whether to also escape ', ", and > in addition to < and & + * @return The escaped string + */ +export declare function escapeXml(xml: string, forAttribute?: boolean): string; +export declare function createUUID(): string; +export declare function escapeRegExp(str: string): string; +export declare function replaceAll(find: string, replace: string, str: string): string; +export interface IDelimiter { + begin: string; + end: string; +} +export declare const substitute: (template: any, map: any) => any; +export type ByteBuffer = Uint16Array | Uint8Array | Buffer | number[]; +export interface Codec { + encode(data: string): number[]; + decode(data: ByteBuffer): string; +} +/** + * Provides facilities for encoding a string into an ASCII-encoded byte buffer and + * decoding an ASCII-encoded byte buffer into a string. + */ +export declare const ascii: Codec; +/** + * Provides facilities for encoding a string into a Base64-encoded byte buffer and + * decoding a Base64-encoded byte buffer into a string. + */ +export declare const base64: Codec; +/** + * Provides facilities for encoding a string into a hex-encoded byte buffer and + * decoding a hex-encoded byte buffer into a string. + */ +export declare const hex: Codec; +/** + * Provides facilities for encoding a string into a UTF-8-encoded byte buffer and + * decoding a UTF-8-encoded byte buffer into a string. + * Inspired by the work of: https://github.com/mathiasbynens/utf8.js + */ +export declare const utf8: Codec; diff --git a/packages/core/dist/utils.js b/packages/core/dist/utils.js new file mode 100644 index 00000000..77b0efed --- /dev/null +++ b/packages/core/dist/utils.js @@ -0,0 +1,379 @@ +export function StingEnum(o) { + return o.reduce((res, key) => { + res[key] = key; + return res; + }, Object.create(null)); +} +import { isString } from './primitives.js'; +const escapeRegExpPattern = /[[\]{}()|/\\^$.*+?]/g; +const escapeXmlPattern = /[&<]/g; +const escapeXmlForPattern = /[&<>'"]/g; +const escapeXmlMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + '\'': ''' +}; +export const DefaultDelimiter = { + begin: '<%', + end: '%>' +}; +export const hasFlag = (field, enumValue) => { + //noinspection JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage + return ((1 << enumValue) & field) ? true : false; +}; +export const hasFlagHex = (field, enumValue) => { + //noinspection JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage,JSBitwiseOperatorUsage + return enumValue & field ? true : false; +}; +export const disableFlag = (enumValue, field) => { + enumValue &= ~(1 << field); + return enumValue; +}; +/** + * The minimum location of high surrogates + */ +export const HIGH_SURROGATE_MIN = 0xD800; +/** + * The maximum location of high surrogates + */ +export const HIGH_SURROGATE_MAX = 0xDBFF; +/** + * The minimum location of low surrogates + */ +export const LOW_SURROGATE_MIN = 0xDC00; +/** + * The maximum location of low surrogates + */ +export const LOW_SURROGATE_MAX = 0xDFFF; +const BASE64_KEYSTR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +export const capitalize = (word) => { + return word.substring(0, 1).toUpperCase() + word.substring(1); +}; +export const getJson = (inData, validOnly, ommit) => { + try { + return isString(inData) ? JSON.parse(inData) : validOnly === true ? null : inData; + } + catch (e) { + ommit !== false && console.error('error parsing json data ' + inData + ' error = ' + e); + } + return null; +}; +/** + * Escapes a string so that it can safely be passed to the RegExp constructor. + * @param text The string to be escaped + * @return The escaped string + */ +export function escapeRegExpEx(text) { + return !text ? text : text.replace(escapeRegExpPattern, '\\$&'); +} +/** + * Sanitizes a string to protect against tag injection. + * @param xml The string to be escaped + * @param forAttribute Whether to also escape ', ", and > in addition to < and & + * @return The escaped string + */ +export function escapeXml(xml, forAttribute = true) { + if (!xml) { + return xml; + } + const pattern = forAttribute ? escapeXmlForPattern : escapeXmlPattern; + return xml.replace(pattern, function (character) { + return escapeXmlMap[character]; + }); +} +export function createUUID() { + const S4 = function () { + return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); + }; + return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4()); +} +export function escapeRegExp(str) { + const special = ['[', ']', '(', ')', '{', '}', '*', '+', '.', '|', '||']; + for (let n = 0; n < special.length; n++) { + str = str.replace(special[n], '\\' + special[n]); + } + return str; +} +; +export function replaceAll(find, replace, str) { + return str ? str.split(find).join(replace) : ''; +} +; +export const substitute = (template, map) => { + const transform = (k) => k || ''; + return template.replace(/\$\{([^\s:}]+)(?::([^\s:}]+))?\}/g, (match, key, format) => transform(map[key]).toString()); +}; +function decodeUtf8EncodedCodePoint(codePoint, validationRange = [0, Infinity], checkSurrogate) { + if (codePoint < validationRange[0] || codePoint > validationRange[1]) { + throw Error('Invalid continuation byte'); + } + if (checkSurrogate && codePoint >= HIGH_SURROGATE_MIN && codePoint <= LOW_SURROGATE_MAX) { + throw Error('Surrogate is not a scalar value'); + } + let encoded = ''; + if (codePoint > 0xFFFF) { + codePoint -= 0x010000; + encoded += String.fromCharCode(codePoint >>> 0x10 & 0x03FF | HIGH_SURROGATE_MIN); + codePoint = LOW_SURROGATE_MIN | codePoint & 0x03FF; + } + encoded += String.fromCharCode(codePoint); + return encoded; +} +function validateUtf8EncodedCodePoint(codePoint) { + if ((codePoint & 0xC0) !== 0x80) { + throw Error('Invalid continuation byte'); + } +} +/** + * Provides facilities for encoding a string into an ASCII-encoded byte buffer and + * decoding an ASCII-encoded byte buffer into a string. + */ +export const ascii = { + /** + * Encodes a string into an ASCII-encoded byte buffer. + * + * @param data The text string to encode + */ + encode(data) { + if (data == null) { + return []; + } + const buffer = []; + for (let i = 0, length = data.length; i < length; i++) { + buffer[i] = data.charCodeAt(i); + } + return buffer; + }, + /** + * Decodes an ASCII-encoded byte buffer into a string. + * + * @param data The byte buffer to decode + */ + decode(data) { + if (data == null) { + return ''; + } + let decoded = ''; + for (let i = 0, length = data.length; i < length; i++) { + decoded += String.fromCharCode(data[i]); + } + return decoded; + } +}; +/** + * Provides facilities for encoding a string into a Base64-encoded byte buffer and + * decoding a Base64-encoded byte buffer into a string. + */ +export const base64 = { + /** + * Encodes a Base64-encoded string into a Base64 byte buffer. + * + * @param data The Base64-encoded string to encode + */ + encode(data) { + if (data == null) { + return []; + } + const buffer = []; + let i = 0; + let length = data.length; + while (data[--length] === '=') { } + while (i < length) { + let encoded = BASE64_KEYSTR.indexOf(data[i++]) << 18; + if (i <= length) { + encoded |= BASE64_KEYSTR.indexOf(data[i++]) << 12; + } + if (i <= length) { + encoded |= BASE64_KEYSTR.indexOf(data[i++]) << 6; + } + if (i <= length) { + encoded |= BASE64_KEYSTR.indexOf(data[i++]); + } + buffer.push((encoded >>> 16) & 0xff); + buffer.push((encoded >>> 8) & 0xff); + buffer.push(encoded & 0xff); + } + while (buffer[buffer.length - 1] === 0) { + buffer.pop(); + } + return buffer; + }, + /** + * Decodes a Base64-encoded byte buffer into a Base64-encoded string. + * + * @param data The byte buffer to decode + */ + decode(data) { + if (data == null) { + return ''; + } + let decoded = ''; + let i = 0; + for (let length = data.length - (data.length % 3); i < length;) { + const encoded = data[i++] << 16 | data[i++] << 8 | data[i++]; + decoded += BASE64_KEYSTR.charAt((encoded >>> 18) & 0x3F); + decoded += BASE64_KEYSTR.charAt((encoded >>> 12) & 0x3F); + decoded += BASE64_KEYSTR.charAt((encoded >>> 6) & 0x3F); + decoded += BASE64_KEYSTR.charAt(encoded & 0x3F); + } + if (data.length % 3 === 1) { + const encoded = data[i++] << 16; + decoded += BASE64_KEYSTR.charAt((encoded >>> 18) & 0x3f); + decoded += BASE64_KEYSTR.charAt((encoded >>> 12) & 0x3f); + decoded += '=='; + } + else if (data.length % 3 === 2) { + const encoded = data[i++] << 16 | data[i++] << 8; + decoded += BASE64_KEYSTR.charAt((encoded >>> 18) & 0x3f); + decoded += BASE64_KEYSTR.charAt((encoded >>> 12) & 0x3f); + decoded += BASE64_KEYSTR.charAt((encoded >>> 6) & 0x3f); + decoded += '='; + } + return decoded; + } +}; +/** + * Provides facilities for encoding a string into a hex-encoded byte buffer and + * decoding a hex-encoded byte buffer into a string. + */ +export const hex = { + /** + * Encodes a string into a hex-encoded byte buffer. + * + * @param data The hex-encoded string to encode + */ + encode(data) { + if (data == null) { + return []; + } + const buffer = []; + for (let i = 0, length = data.length; i < length; i += 2) { + const encodedChar = parseInt(data.substr(i, 2), 16); + buffer.push(encodedChar); + } + return buffer; + }, + /** + * Decodes a hex-encoded byte buffer into a hex-encoded string. + * + * @param data The byte buffer to decode + */ + decode(data) { + if (data == null) { + return ''; + } + let decoded = ''; + for (let i = 0, length = data.length; i < length; i++) { + decoded += data[i].toString(16).toUpperCase(); + } + return decoded; + } +}; +/** + * Provides facilities for encoding a string into a UTF-8-encoded byte buffer and + * decoding a UTF-8-encoded byte buffer into a string. + * Inspired by the work of: https://github.com/mathiasbynens/utf8.js + */ +export const utf8 = { + /** + * Encodes a string into a UTF-8-encoded byte buffer. + * + * @param data The text string to encode + */ + encode(data) { + if (data == null) { + return []; + } + const buffer = []; + for (let i = 0, length = data.length; i < length; i++) { + let encodedChar = data.charCodeAt(i); + /** + * Surrogates + * http://en.wikipedia.org/wiki/Universal_Character_Set_characters + */ + if (encodedChar >= HIGH_SURROGATE_MIN && encodedChar <= HIGH_SURROGATE_MAX) { + const lowSurrogate = data.charCodeAt(i + 1); + if (lowSurrogate >= LOW_SURROGATE_MIN && lowSurrogate <= LOW_SURROGATE_MAX) { + encodedChar = 0x010000 + (encodedChar - HIGH_SURROGATE_MIN) * 0x0400 + (lowSurrogate - LOW_SURROGATE_MIN); + i++; + } + } + if (encodedChar < 0x80) { + buffer.push(encodedChar); + } + else { + if (encodedChar < 0x800) { + buffer.push(((encodedChar >> 0x06) & 0x1F) | 0xC0); + } + else if (encodedChar < 0x010000) { + if (encodedChar >= HIGH_SURROGATE_MIN && encodedChar <= LOW_SURROGATE_MAX) { + throw Error('Surrogate is not a scalar value'); + } + buffer.push(((encodedChar >> 0x0C) & 0x0F) | 0xE0); + buffer.push(((encodedChar >> 0x06) & 0x3F) | 0x80); + } + else if (encodedChar < 0x200000) { + buffer.push(((encodedChar >> 0x12) & 0x07) | 0xF0); + buffer.push(((encodedChar >> 0x0C) & 0x3F) | 0x80); + buffer.push(((encodedChar >> 0x06) & 0x3F) | 0x80); + } + buffer.push((encodedChar & 0x3F) | 0x80); + } + } + return buffer; + }, + /** + * Decodes a UTF-8-encoded byte buffer into a string. + * + * @param data The byte buffer to decode + */ + decode(data) { + if (data == null) { + return ''; + } + let decoded = ''; + for (let i = 0, length = data.length; i < length; i++) { + const byte1 = data[i] & 0xFF; + if ((byte1 & 0x80) === 0) { + decoded += decodeUtf8EncodedCodePoint(byte1); + } + else if ((byte1 & 0xE0) === 0xC0) { + let byte2 = data[++i] & 0xFF; + validateUtf8EncodedCodePoint(byte2); + byte2 = byte2 & 0x3F; + const encodedByte = ((byte1 & 0x1F) << 0x06) | byte2; + decoded += decodeUtf8EncodedCodePoint(encodedByte, [0x80, Infinity]); + } + else if ((byte1 & 0xF0) === 0xE0) { + let byte2 = data[++i] & 0xFF; + validateUtf8EncodedCodePoint(byte2); + byte2 = byte2 & 0x3F; + let byte3 = data[++i] & 0xFF; + validateUtf8EncodedCodePoint(byte3); + byte3 = byte3 & 0x3F; + const encodedByte = ((byte1 & 0x1F) << 0x0C) | (byte2 << 0x06) | byte3; + decoded += decodeUtf8EncodedCodePoint(encodedByte, [0x0800, Infinity], true); + } + else if ((byte1 & 0xF8) === 0xF0) { + let byte2 = data[++i] & 0xFF; + validateUtf8EncodedCodePoint(byte2); + byte2 = byte2 & 0x3F; + let byte3 = data[++i] & 0xFF; + validateUtf8EncodedCodePoint(byte3); + byte3 = byte3 & 0x3F; + let byte4 = data[++i] & 0xFF; + validateUtf8EncodedCodePoint(byte4); + byte4 = byte4 & 0x3F; + const encodedByte = ((byte1 & 0x1F) << 0x0C) | (byte2 << 0x0C) | (byte3 << 0x06) | byte4; + decoded += decodeUtf8EncodedCodePoint(encodedByte, [0x010000, 0x10FFFF]); + } + else { + validateUtf8EncodedCodePoint(byte1); + } + } + return decoded; + } +}; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/packages/core/dist/utils.js.map b/packages/core/dist/utils.js.map new file mode 100644 index 00000000..097872ba --- /dev/null +++ b/packages/core/dist/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,SAAS,CAAmB,CAAW;IACnD,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QACzB,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;QACf,OAAO,GAAG,CAAC;IACf,CAAC,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AAC5B,C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I,CAAC;gBAErB,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,GAAG,KAAK,CAAC;gBACzF,OAAO,IAAI,0BAA0B,CAAC,WAAW,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;aAC5E;iBAAM;gBACH,4BAA4B,CAAC,KAAK,CAAC,CAAC;aACvC;SACJ;QACD,OAAO,OAAO,CAAC;IACnB,CAAC;CACJ,CAAC"} \ No newline at end of file diff --git a/packages/core/dist/uuid.d.ts b/packages/core/dist/uuid.d.ts new file mode 100644 index 00000000..e53e30bd --- /dev/null +++ b/packages/core/dist/uuid.d.ts @@ -0,0 +1,22 @@ +/** + * Represents a UUID as defined by rfc4122. + */ +export interface UUID { + /** + * @returns the canonical representation in sets of hexadecimal numbers separated by dashes. + */ + asHex(): string; + equals(other: UUID): boolean; +} +/** + * An empty UUID that contains only zeros. + */ +export declare const empty: UUID; +export declare function v4(): UUID; +export declare function isUUID(value: string): boolean; +/** + * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. + * @param value A uuid string. + */ +export declare function parse(value: string): UUID; +export declare function generateUuid(): string; diff --git a/packages/core/dist/uuid.js b/packages/core/dist/uuid.js new file mode 100644 index 00000000..4afd5e77 --- /dev/null +++ b/packages/core/dist/uuid.js @@ -0,0 +1,93 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +'use strict'; +class ValueUUID { + _value; + constructor(_value) { + this._value = _value; + // empty + } + asHex() { + return this._value; + } + equals(other) { + return this.asHex() === other.asHex(); + } +} +class V4UUID extends ValueUUID { + static _chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; + static _timeHighBits = ['8', '9', 'a', 'b']; + static _oneOf(array) { + return array[Math.floor(array.length * Math.random())]; + } + static _randomHex() { + return V4UUID._oneOf(V4UUID._chars); + } + constructor() { + super([ + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + '-', + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + '-', + '4', + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + '-', + V4UUID._oneOf(V4UUID._timeHighBits), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + '-', + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + V4UUID._randomHex(), + ].join('')); + } +} +/** + * An empty UUID that contains only zeros. + */ +export const empty = new ValueUUID('00000000-0000-0000-0000-000000000000'); +export function v4() { + return new V4UUID(); +} +const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +export function isUUID(value) { + return _UUIDPattern.test(value); +} +/** + * Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. + * @param value A uuid string. + */ +export function parse(value) { + if (!isUUID(value)) { + throw new Error('invalid uuid'); + } + return new ValueUUID(value); +} +export function generateUuid() { + return v4().asHex(); +} +//# sourceMappingURL=uuid.js.map \ No newline at end of file diff --git a/packages/core/dist/uuid.js.map b/packages/core/dist/uuid.js.map new file mode 100644 index 00000000..ce901f4d --- /dev/null +++ b/packages/core/dist/uuid.js.map @@ -0,0 +1 @@ +{"version":3,"file":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AK,CAAC,EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC;KAChC;IAED,OAAO,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC;AAC7B,CAAC;AAED,MAAM,UAAU,YAAY;IAC3B,OAAO,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/packages/core/package.json b/packages/core/package.json index 3d0c0d34..6ec55051 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -24,6 +24,14 @@ "./primitives.js": { "import": "./dist/primitives.js", "require": "./dist/primitives.js" + }, + "./types.js": { + "import": "./dist/types.js", + "require": "./dist/types.js" + }, + "./constants.js": { + "import": "./dist/constants.js", + "require": "./dist/constants.js" } }, "main": "dist/index.js", diff --git a/packages/fs/dist/append.d.ts b/packages/fs/dist/append.d.ts new file mode 100644 index 00000000..40d74338 --- /dev/null +++ b/packages/fs/dist/append.d.ts @@ -0,0 +1,8 @@ +export interface Options { + mode: string; + encoding?: string; + flag?: string; +} +export declare const validateInput: (methodName: string, path: string, data: any, options?: Options) => void; +export declare const sync: (path: string, data: any, options: Options) => void; +export declare const async: (path: string, data: string | Buffer | object, options?: Options) => Promise; diff --git a/packages/fs/dist/append.js b/packages/fs/dist/append.js new file mode 100644 index 00000000..cbcb1373 --- /dev/null +++ b/packages/fs/dist/append.js @@ -0,0 +1,50 @@ +import * as fs from 'fs'; +const Q = require('q'); +import { sync as writeSync, async as writeASync } from './write.js'; +import { validateArgument, validateOptions } from './utils/validate.js'; +export const validateInput = (methodName, path, data, options) => { + const methodSignature = methodName + '(path, data, [options])'; + validateArgument(methodSignature, 'path', path, ['string']); + validateArgument(methodSignature, 'data', data, ['string', 'buffer']); + validateOptions(methodSignature, 'options', options, { + mode: ['string', 'number'] + }); +}; +// --------------------------------------------------------- +// SYNC +// --------------------------------------------------------- +export const sync = (path, data, options) => { + try { + fs.appendFileSync(path, data, options ? { encoding: options.encoding, mode: options.mode } : {}); + } + catch (err) { + if (err.code === 'ENOENT') { + // Parent directory doesn't exist, so just pass the task to `write`, + // which will create the folder and file. + writeSync(path, data, options); + } + else { + throw err; + } + } +}; +// --------------------------------------------------------- +// ASYNC +// --------------------------------------------------------- +const promisedAppendFile = Q.denodeify(fs.appendFile); +export const async = (path, data, options) => { + return new Promise((resolve, reject) => { + promisedAppendFile(path, data, options) + .then(resolve) + .catch((err) => { + if (err.code === 'ENOENT') { + // Parent directory doesn't exist, so just pass the task to `write`, + // which will create the folder and file. + writeASync(path, data, options).then(resolve, reject); + } + else { + reject(err); + } + }); + }); +}; diff --git a/packages/fs/dist/copy.d.ts b/packages/fs/dist/copy.d.ts new file mode 100644 index 00000000..c1a4476f --- /dev/null +++ b/packages/fs/dist/copy.d.ts @@ -0,0 +1,15 @@ +import type { ICopyOptions, TCopyResult } from './interfaces.js'; +import { EResolveMode } from './interfaces.js'; +export declare function validateInput(methodName: string, from: string, to: string, options?: ICopyOptions): void; +export declare function sync(from: string, to: string, options?: ICopyOptions): void; +export declare function copySymlinkAsync(from: string, to: string): Promise; +export declare function resolveConflict(from: string, to: string, options: ICopyOptions, resolveMode: EResolveMode): boolean; +/** + * Final async copy function. + * @export + * @param {string} from + * @param {string} to + * @param {ICopyOptions} [options] + * @returns + */ +export declare function async(from: string, to: string, options?: ICopyOptions): Promise; diff --git a/packages/fs/dist/copy.js b/packages/fs/dist/copy.js new file mode 100644 index 00000000..9d2e13f5 --- /dev/null +++ b/packages/fs/dist/copy.js @@ -0,0 +1,621 @@ +import * as pathUtil from 'path'; +import * as fs from 'fs'; +import { symlinkSync, readFileSync, createReadStream, createWriteStream } from 'fs'; +import { sync as mkdirp } from 'mkdirp'; +import { sync as existsSync, async as existsASync } from './exists.js'; +import { create as matcher } from './utils/matcher.js'; +import { normalizeFileMode as fileMode } from './utils/mode.js'; +import { sync as treeWalkerSync } from './utils/tree_walker.js'; +import { validateArgument, validateOptions } from './utils/validate.js'; +import { sync as writeSync } from './write.js'; +import { ErrDestinationExists, ErrDoesntExists } from './errors.js'; +import { ErrnoException, ENodeType, ECopyFlags, ENodeOperationStatus, EError, EInspectFlags, EResolveMode, EResolve } from './interfaces.js'; +import { createItem } from './inspect.js'; +import { sync as rmSync } from './remove.js'; +import { promisify } from './promisify.js'; +import { async as iteratorAsync } from './iterator.js'; +//import { ArrayIterator } from '@polymech/core/iterator'; +const promisedSymlink = promisify(fs.symlink); +const promisedReadlink = promisify(fs.readlink); +const promisedUnlink = promisify(fs.unlink); +const promisedMkdirp = promisify(mkdirp); +const progress = require('progress-stream'); +const CPROGRESS_THRESHOLD = 1048576 * 5; // minimum file size threshold to use write progress = 5MB +export function validateInput(methodName, from, to, options) { + const methodSignature = methodName + '(from, to, [options])'; + validateArgument(methodSignature, 'from', from, ['string']); + validateArgument(methodSignature, 'to', to, ['string']); + validateOptions(methodSignature, 'options', options, { + overwrite: ['boolean'], + matching: ['string', 'array of string'], + progress: ['function'], + content: ['function'], + writeProgress: ['function'], + conflictCallback: ['function'], + conflictSettings: ['object'], + throttel: ['number'], + debug: ['boolean'], + flags: ['number'] + }); +} +const parseOptions = (options, from) => { + const opts = options || {}; + const parsedOptions = {}; + parsedOptions.overwrite = opts.overwrite; + parsedOptions.progress = opts.progress; + parsedOptions.writeProgress = opts.writeProgress; + parsedOptions.content = opts.content; + parsedOptions.conflictCallback = opts.conflictCallback; + parsedOptions.conflictSettings = opts.conflictSettings; + parsedOptions.debug = opts.debug; + parsedOptions.throttel = opts.throttel; + parsedOptions.renameCallback = opts.renameCallback; + parsedOptions.flags = opts.flags || 0; + if (!opts.filter) { + if (opts.matching) { + parsedOptions.filter = matcher(from, opts.matching); + } + else { + parsedOptions.filter = () => { + return true; + }; + } + } + return parsedOptions; +}; +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +const checksBeforeCopyingSync = (from, to, options = {}) => { + if (!existsSync(from)) { + throw ErrDoesntExists(from); + } + if (existsSync(to) && !options.overwrite) { + throw ErrDestinationExists(to); + } +}; +async function copyFileSyncWithProgress(from, to, options = {}) { + return new Promise((resolve, reject) => { + const started = Date.now(); + let cbCalled = false; + let elapsed = Date.now(); + let speed = 0; + const done = (err) => { + if (!cbCalled) { + cbCalled = true; + resolve(1); + } + }; + const rd = createReadStream(from). + on('error', (err) => done(err)); + const str = progress({ + length: fs.statSync(from).size, + time: 100 + }).on('progress', (e) => { + elapsed = (Date.now() - started) / 1000; + speed = e.transferred / elapsed; + if (options.writeProgress) { + options.writeProgress(from, e.transferred, e.length); + } + }); + const wr = createWriteStream(to); + wr.on('error', (err) => done(err)); + wr.on('close', done); + rd.pipe(str).pipe(wr); + }); +} +async function copyFileSync(from, to, mode, options) { + let data = readFileSync(from); + const writeOptions = { + mode: mode + }; + if (options.renameCallback) { + const rename = options.renameCallback(from, to); + if (rename) { + to = rename; + } + } + if (options.content) { + data = options.content(from, data, createItem(from)); + } + if (options && options.writeProgress) { + await copyFileSyncWithProgress(from, to, options); + } + else { + writeSync(to, data, writeOptions); + } +} +const copySymlinkSync = (from, to) => { + const symlinkPointsAt = fs.readlinkSync(from); + try { + symlinkSync(symlinkPointsAt, to); + } + catch (err) { + // There is already file/symlink with this name on destination location. + // Must erase it manually, otherwise system won't allow us to place symlink there. + if (err.code === 'EEXIST') { + fs.unlinkSync(to); + // Retry... + fs.symlinkSync(symlinkPointsAt, to); + } + else { + throw err; + } + } +}; +async function copyItemSync(from, inspectData, to, options) { + const mode = fileMode(inspectData.mode); + if (inspectData.type === ENodeType.DIR) { + if (options.renameCallback) { + const rename = options.renameCallback(from, to); + if (rename) { + to = rename; + } + } + mkdirp(to, { mode: parseInt(mode, 8), fs: null }); + } + else if (inspectData.type === ENodeType.FILE) { + await copyFileSync(from, to, mode, options); + } + else if (inspectData.type === ENodeType.SYMLINK) { + if (options.renameCallback) { + const rename = options.renameCallback(from, to); + if (rename) { + to = rename; + } + } + copySymlinkSync(from, to); + } +} +export function sync(from, to, options) { + const opts = parseOptions(options, from); + checksBeforeCopyingSync(from, to, opts); + const nodes = []; + let sizeTotal = 0; + if (options && options.flags & ECopyFlags.EMPTY) { + const dstStat = fs.statSync(to); + if (dstStat.isDirectory()) { + rmSync(to); + } + } + const visitor = (path, inspectData) => { + if (opts.filter(path)) { + nodes.push({ + path: path, + item: inspectData, + dst: pathUtil.resolve(to, pathUtil.relative(from, path)) + }); + sizeTotal += inspectData.size; + } + }; + treeWalkerSync(from, { + inspectOptions: { + mode: true, + symlinks: true + } + }, visitor); + nodes.map((item, current) => { + copyItemSync(item.path, item.item, item.dst, options); + if (opts.progress) { + opts.progress(item.path, current, nodes.length, item.item, item.dst); + } + }); +} +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +/** + * + * + * @param {string} from + * @param {string} to + * @param {ICopyOptions} opts + * @returns {(Promise)} + */ +const checkAsync = (from, to, opts) => { + return existsASync(from) + .then(srcPathExists => { + if (!srcPathExists) { + throw ErrDoesntExists(from); + } + else { + return existsASync(to); + } + }) + .then(destPathExists => { + if (destPathExists) { + if (opts.conflictSettings) { + return Promise.resolve(opts.conflictSettings); + } + if (opts.conflictCallback) { + const promise = opts.conflictCallback(to, createItem(to), EError.EXISTS); + promise.then((settings) => { + settings.error = EError.EXISTS; + }); + return promise; + } + if (!opts.overwrite) { + throw ErrDestinationExists(to); + } + } + }); +}; +const copyFileAsync = (from, to, mode, options, retriedAttempt) => { + return new Promise((resolve, reject) => { + const readStream = fs.createReadStream(from); + const writeStream = fs.createWriteStream(to, { mode: mode }); + readStream.on('error', reject); + writeStream.on('error', (err) => { + const toDirPath = pathUtil.dirname(to); + // Force read stream to close, since write stream errored + // read stream serves us no purpose. + readStream.resume(); + if (err.code === EError.NOEXISTS && retriedAttempt === undefined) { + // Some parent directory doesn't exits. Create it and retry. + promisedMkdirp(toDirPath, null).then(() => { + // Make retry attempt only once to prevent vicious infinite loop + // (when for some obscure reason I/O will keep returning ENOENT error). + // Passing retriedAttempt = true. + copyFileAsync(from, to, mode, null, true) + .then(resolve) + .catch(reject); + }); + } + else { + reject(err); + } + }); + writeStream.on('finish', () => { + // feature: preserve times + if (options && options.flags & ECopyFlags.PRESERVE_TIMES) { + const sourceStat = fs.statSync(from); + fs.open(to, 'w', (err, fd) => { + if (err) { + throw err; + } + fs.futimes(fd, sourceStat.atime, sourceStat.mtime, (err2) => { + if (err2) { + throw err2; + } + fs.close(fd, null); + resolve(1); + }); + }); + } + else { + resolve(1); + } + }); + const size = fs.statSync(from).size; + let progressStream = null; + if (options && options.writeProgress && size > CPROGRESS_THRESHOLD) { + progressStream = progress({ + length: fs.statSync(from).size, + time: 100 // call progress each 100 ms + }); + let elapsed = Date.now(); + let speed = 0; + const started = Date.now(); + progressStream.on('progress', (e) => { + elapsed = (Date.now() - started) / 1000; + speed = e.transferred / elapsed; + options.writeProgress(from, e.transferred, e.length); + if (options.debug) { + console.log('write ' + from + ' (' + e.transferred + ' of ' + e.length); + } + }); + readStream.pipe(progressStream).pipe(writeStream); + } + else { + if (options && options.debug) { + console.log('write ' + from + ' to ' + to); + } + readStream.pipe(writeStream); + } + }); +}; +export function copySymlinkAsync(from, to) { + return promisedReadlink(from) + .then((symlinkPointsAt) => { + return new Promise((resolve, reject) => { + promisedSymlink(symlinkPointsAt, to, null) + .then(resolve) + .catch((err) => { + if (err.code === EError.EXISTS) { + // There is already file/symlink with this name on destination location. + // Must erase it manually, otherwise system won't allow us to place symlink there. + promisedUnlink(to, null) + // Retry... + .then(() => { + return promisedSymlink(symlinkPointsAt, to, null); + }) + .then(resolve, reject); + } + else { + reject(err); + } + }); + }); + }); +} +const copyItemAsync = (from, inspectData, to, options) => { + const mode = fileMode(inspectData.mode); + if (inspectData.type === ENodeType.DIR) { + return promisedMkdirp(to, { mode: mode }); + } + else if (inspectData.type === ENodeType.FILE) { + return copyFileAsync(from, to, mode, options); + } + else if (inspectData.type === ENodeType.SYMLINK) { + return copySymlinkAsync(from, to); + } + // EInspectItemType.OTHER + return Promise.resolve(); +}; +// handle user side setting "THROW" and non enum values (null) +const onConflict = (from, to, options, settings) => { + switch (settings.overwrite) { + case EResolveMode.THROW: { + throw ErrDestinationExists(to); + } + case EResolveMode.OVERWRITE: + case EResolveMode.APPEND: + case EResolveMode.IF_NEWER: + case EResolveMode.ABORT: + case EResolveMode.IF_SIZE_DIFFERS: + case EResolveMode.SKIP: { + return settings.overwrite; + } + default: { + return undefined; + } + } +}; +export function resolveConflict(from, to, options, resolveMode) { + if (resolveMode === undefined) { + return true; + } + const src = createItem(from); + const dst = createItem(to); + if (resolveMode === EResolveMode.SKIP) { + return false; + } + else if (resolveMode === EResolveMode.IF_NEWER) { + if (src.type === ENodeType.DIR && dst.type === ENodeType.DIR) { + return true; + } + if (dst.modifyTime.getTime() > src.modifyTime.getTime()) { + return false; + } + } + else if (resolveMode === EResolveMode.IF_SIZE_DIFFERS) { + // @TODO : not implemented: copy EInspectItemType.DIR with ECopyResolveMode.IF_SIZE_DIFFERS + if (src.type === ENodeType.DIR && dst.type === ENodeType.DIR) { + return true; + } + else if (src.type === ENodeType.FILE && dst.type === ENodeType.FILE) { + if (src.size === dst.size) { + return false; + } + } + } + else if (resolveMode === EResolveMode.OVERWRITE) { + return true; + } + else if (resolveMode === EResolveMode.ABORT) { + return false; + } +} +function isDone(nodes) { + let done = true; + nodes.forEach((element) => { + if (element.status !== ENodeOperationStatus.DONE) { + done = false; + } + }); + return done; +} +/** + * A callback for treeWalkerStream. This is called when a node has been found. + * + * @param {string} from + * @param {string} to + * @param {*} vars + * @param {{ path: string, item: INode }} item + * @returns {Promise} + */ +async function visitor(from, to, vars, item) { + const options = vars.options; + let rel; + let destPath; + if (!item) { + return; + } + rel = pathUtil.relative(from, item.path); + destPath = pathUtil.resolve(to, rel); + item.status = ENodeOperationStatus.PROCESSING; + const done = () => { + item.status = ENodeOperationStatus.DONE; + if (isDone(vars.nodes)) { + return vars.resolve(vars.result); + } + }; + if (isDone(vars.nodes)) { + return vars.resolve(vars.result); + } + vars.filesInProgress += 1; + // our main function after sanity checks + const checked = (subResolveSettings) => { + item.status = ENodeOperationStatus.CHECKED; + // feature : report + if (subResolveSettings && options && options.flags && options.flags & ECopyFlags.REPORT) { + vars.result.push({ + error: subResolveSettings.error, + node: item, + resolved: subResolveSettings + }); + } + if (subResolveSettings) { + // if the first resolve callback returned an individual resolve settings "THIS", + // ask the user again with the same item + const always = subResolveSettings.mode === EResolve.ALWAYS; + if (always) { + options.conflictSettings = subResolveSettings; + } + let overwriteMode = subResolveSettings.overwrite; + overwriteMode = onConflict(item.path, destPath, options, subResolveSettings); + if (overwriteMode === EResolveMode.ABORT) { + vars.abort = true; + } + if (vars.abort) { + return; + } + if (!resolveConflict(item.path, destPath, options, overwriteMode)) { + done(); + return; + } + } + item.status = ENodeOperationStatus.PROCESS; + copyItemAsync(item.path, item.item, destPath, options).then(() => { + vars.filesInProgress -= 1; + if (options.progress) { + if (options.progress(item.path, vars.filesInProgress, vars.filesInProgress, item.item) === false) { + vars.abort = true; + return vars.resolve(); + } + } + done(); + }).catch((err) => { + if (options && options.conflictCallback) { + if (err.code === EError.PERMISSION || err.code === EError.NOEXISTS) { + options.conflictCallback(item.path, createItem(destPath), err.code).then((errorResolveSettings) => { + // the user has set the conflict resolver to always, so we use the last one + if (vars.onCopyErrorResolveSettings) { + errorResolveSettings = vars.onCopyErrorResolveSettings; + } + // user said use this settings always, we track and use this last setting from now on + if (errorResolveSettings.mode === EResolve.ALWAYS && !vars.onCopyErrorResolveSettings) { + vars.onCopyErrorResolveSettings = errorResolveSettings; + } + if (errorResolveSettings.overwrite === EResolveMode.ABORT) { + vars.abort = true; + return vars.resolve(); + } + if (errorResolveSettings.overwrite === EResolveMode.THROW) { + vars.abort = true; + return vars.reject(err); + } + if (errorResolveSettings.overwrite === EResolveMode.SKIP) { + vars.filesInProgress -= 1; + } + // user error, should never happen, unintended + if (errorResolveSettings.overwrite === EResolveMode.IF_NEWER || + errorResolveSettings.overwrite === EResolveMode.IF_SIZE_DIFFERS || + errorResolveSettings.overwrite === EResolveMode.OVERWRITE) { + vars.reject(new ErrnoException('settings make no sense : errorResolveSettings.overwrite = ' + errorResolveSettings.overwrite)); + } + }); + } + } + vars.reject(err); + }); + }; + return checkAsync(item.path, destPath, options).then(checked); +} +function next(nodes) { + for (let i = 0; i < nodes.length; i++) { + if (nodes[i].status === ENodeOperationStatus.COLLECTED) { + return nodes[i]; + } + } + return null; +} +/** + * Final async copy function. + * @export + * @param {string} from + * @param {string} to + * @param {ICopyOptions} [options] + * @returns + */ +export function async(from, to, options) { + options = parseOptions(options, from); + return new Promise((resolve, reject) => { + checkAsync(from, to, options).then((resolver) => { + if (!resolver) { + resolver = options.conflictSettings || { + mode: EResolve.THIS, + overwrite: EResolveMode.OVERWRITE + }; + } + else { + if (resolver.mode === EResolve.ALWAYS) { + options.conflictSettings = resolver; + } + } + let overwriteMode = resolver.overwrite; + let result = void 0; + if (options && options.flags && options.flags & ECopyFlags.REPORT) { + result = []; + } + // call onConflict to eventually throw an error + overwriteMode = onConflict(from, to, options, resolver); + // now evaluate the copy conflict settings and eventually abort + if (options && options.conflictSettings && !resolveConflict(from, to, options, overwriteMode)) { + return resolve(); + } + // feature: clean before + if (options && options.flags) { + const dstStat = fs.statSync(to); + if (dstStat.isDirectory()) { + rmSync(to); + } + } + // walker variables + const visitorArgs = { + resolve: resolve, + reject: reject, + abort: false, + filesInProgress: 0, + resolveSettings: resolver, + options: options, + result: result, + nodes: [], + onCopyErrorResolveSettings: null + }; + const nodes = visitorArgs.nodes; + // a function called when the treeWalkerStream or visitor has been finished + const process = function () { + visitorArgs.nodes = nodes; + if (isDone(nodes)) { + return resolve(result); + } + if (nodes.length) { + const item = next(nodes); + if (item) { + visitor(item.path, item.dst, visitorArgs, item).then(process); + } + } + }; + let flags = EInspectFlags.MODE; + if (options && options.flags && options.flags & ECopyFlags.FOLLOW_SYMLINKS) { + flags |= EInspectFlags.SYMLINKS; + } + iteratorAsync(from, { + filter: options.filter, + flags: flags + }).then((it) => { + let node; + while (node = it.next()) { + nodes.push({ + path: node.path, + item: node.item, + dst: pathUtil.resolve(to, pathUtil.relative(from, node.path)), + status: ENodeOperationStatus.COLLECTED + }); + } + process(); + }); + }).catch(reject); + }); +} diff --git a/packages/fs/dist/dir.d.ts b/packages/fs/dist/dir.d.ts new file mode 100644 index 00000000..3e5667fc --- /dev/null +++ b/packages/fs/dist/dir.d.ts @@ -0,0 +1,7 @@ +export interface IOptions { + empty?: boolean; + mode?: number | string; +} +export declare const validateInput: (methodName: string, path: string, options?: IOptions) => void; +export declare const sync: (path: string, options?: IOptions) => void; +export declare const async: (path: string, passedCriteria?: IOptions) => Promise; diff --git a/packages/fs/dist/dir.js b/packages/fs/dist/dir.js new file mode 100644 index 00000000..1d4611d5 --- /dev/null +++ b/packages/fs/dist/dir.js @@ -0,0 +1,185 @@ +import * as pathUtil from 'path'; +import { stat, statSync, readdirSync, readdir } from 'fs'; +import { promisify } from 'util'; +import * as fs from 'fs'; +import { sync as removeSync, async as removeAsync } from './remove.js'; +import { normalizeFileMode as modeUtil } from './utils/mode.js'; +import { validateArgument, validateOptions } from './utils/validate.js'; +import { ErrNoDirectory } from './errors.js'; +import { EError } from './interfaces.js'; +import * as mkdirp from 'mkdirp'; +export const validateInput = (methodName, path, options) => { + const methodSignature = methodName + '(path, [criteria])'; + validateArgument(methodSignature, 'path', path, ['string']); + validateOptions(methodSignature, 'criteria', options, { + empty: ['boolean'], + mode: ['string', 'number'] + }); +}; +const defaults = (options) => { + const result = options || {}; + if (typeof result.empty !== 'boolean') { + result.empty = false; + } + if (result.mode !== undefined) { + result.mode = modeUtil(result.mode); + } + return result; +}; +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +const dirStatsSync = (path) => { + let _stat; + try { + _stat = statSync(path); + } + catch (err) { + // Detection if path already exists + if (err.code !== EError.NOEXISTS) { + throw err; + } + } + if (_stat && !_stat.isDirectory()) { + throw ErrNoDirectory(path); + } + return _stat; +}; +function mkdirSync(path, criteria) { + mkdirp.sync(path, { mode: criteria.mode, fs: null }); +} +function checkDirSync(path, _stat, options) { + const check = function () { + if (options.mode !== undefined) { + fs.chmodSync(path, options.mode); + } + }; + const checkEmptiness = function () { + let list; + if (options.empty) { + // Delete everything inside this directory + list = readdirSync(path); + list.forEach(function (filename) { + removeSync(pathUtil.resolve(path, filename)); + }); + } + }; + check(); + checkEmptiness(); +} +export const sync = (path, options) => { + const criteria = defaults(options); + const _stat = dirStatsSync(path); + if (_stat) { + checkDirSync(path, _stat, criteria); + } + else { + mkdirSync(path, criteria); + } +}; +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +const promisedStat = promisify(stat); +const promisedReaddir = promisify(readdir); +const dirStatAsync = (path) => { + return new Promise((resolve, reject) => { + promisedStat(path) + .then((_stat) => { + if (_stat.isDirectory()) { + resolve(_stat); + } + else { + reject(ErrNoDirectory(path)); + } + }) + .catch((err) => (err.code === EError.NOEXISTS ? resolve(undefined) : reject(err))); + }); +}; +// Delete all files and directores inside given directory +const emptyAsync = (path) => { + return new Promise((resolve, reject) => { + promisedReaddir(path) + .then(function (list) { + const doOne = function (index) { + let subPath; + if (index === list.length) { + resolve(1); + } + else { + subPath = pathUtil.resolve(path, list[index]); + removeAsync(subPath).then(() => doOne(index + 1)); + } + }; + doOne(0); + }) + .catch(reject); + }); +}; +const checkMode = function (criteria, _stat, path) { + if (criteria.mode !== undefined) { + return promisify(fs.chmod)(path, criteria.mode); + } + return Promise.resolve(null); +}; +const checkDirAsync = (path, _stat, options) => { + return new Promise((resolve, reject) => { + const checkEmptiness = function () { + if (options.empty) { + return emptyAsync(path); + } + return Promise.resolve(); + }; + checkMode(options, _stat, path) + .then(checkEmptiness) + .then(resolve, reject); + }); +}; +const mkdirAsync = (path, criteria) => { + const options = criteria || {}; + return new Promise((resolve, reject) => { + promisify(fs.mkdir)(path, options.mode) + .then(resolve) + .catch((err) => { + if (err.code === 'ENOENT') { + // Parent directory doesn't exist. Need to create it first. + mkdirAsync(pathUtil.dirname(path), options) + .then(() => { + // Now retry creating this directory. + return promisify(fs.mkdir)(path, options.mode); + }) + .then(resolve) + .catch((err2) => { + if (err2.code === 'EEXIST') { + // Hmm, something other have already created the directory? + // No problem for us. + resolve(1); + } + else { + reject(err2); + } + }); + } + else if (err.code === 'EEXIST') { + // The path already exists. We're fine. + resolve(1); + } + else { + reject(err); + } + }); + }); +}; +export const async = (path, passedCriteria) => { + const criteria = defaults(passedCriteria); + return new Promise((resolve, reject) => { + dirStatAsync(path) + .then((_stat) => { + if (_stat !== undefined) { + return checkDirAsync(path, _stat, criteria); + } + return mkdirAsync(path, criteria); + }) + .then(resolve, reject); + }); +}; diff --git a/packages/fs/dist/errors.d.ts b/packages/fs/dist/errors.d.ts new file mode 100644 index 00000000..69149de1 --- /dev/null +++ b/packages/fs/dist/errors.d.ts @@ -0,0 +1,7 @@ +export declare const ErrNoFileOrDir: (path: string) => Error; +export declare const ErrCantDelete: (path: string) => Error; +export declare const ErrNotFile: (path: string) => Error; +export declare const ErrNoDirectory: (path: string) => Error; +export declare const ErrDoesntExists: (path: string) => Error; +export declare const ErrDestinationExists: (path: string) => Error; +export declare const ErrIsNotDirectory: (path: string) => Error; diff --git a/packages/fs/dist/errors.js b/packages/fs/dist/errors.js new file mode 100644 index 00000000..63ad6843 --- /dev/null +++ b/packages/fs/dist/errors.js @@ -0,0 +1,41 @@ +import { ErrnoException } from './interfaces.js'; +const errno = require('errno'); +Object.keys(errno.code).forEach(function (code) { + const e = errno.code[code]; + exports[code] = (path) => { + const err = new Error(code + ', ' + e.description + (path ? ' \'' + path + '\'' : '')); + err.errno = e.errno; + err.code = code; + err.path = path; + return err; + }; +}); +export const ErrNoFileOrDir = (path) => { + return new Error('Can\'t remove ' + path + ' The path is not file nor directory'); +}; +export const ErrCantDelete = (path) => { + return new Error('Can\'t remove ' + path); +}; +export const ErrNotFile = (path) => { + return new Error('Path ' + path + ' exists but is not a file.' + + ' Halting jetpack.file() call for safety reasons.'); +}; +export const ErrNoDirectory = (path) => { + return new Error('Path ' + path + ' exists but is not a directory.' + + ' Halting jetpack.dir() call for safety reasons.'); +}; +export const ErrDoesntExists = (path) => { + const err = new Error('Path to copy doesn\'t exist ' + path); + err.code = 'ENOENT'; + return err; +}; +export const ErrDestinationExists = (path) => { + const err = new Error('Destination path already exists ' + path); + err.code = 'EEXIST'; + return err; +}; +export const ErrIsNotDirectory = (path) => { + const err = new ErrnoException('Path you want to find stuff in must be a directory ' + path); + err.code = 'ENOTDIR'; + return err; +}; diff --git a/packages/fs/dist/exists.d.ts b/packages/fs/dist/exists.d.ts new file mode 100644 index 00000000..2fa8e98f --- /dev/null +++ b/packages/fs/dist/exists.d.ts @@ -0,0 +1,4 @@ +import { ENodeType } from './interfaces.js'; +export declare function validateInput(methodName: string, path: string): void; +export declare function sync(path: string): boolean | string; +export declare function async(path: string): Promise; diff --git a/packages/fs/dist/exists.js b/packages/fs/dist/exists.js new file mode 100644 index 00000000..e26b0096 --- /dev/null +++ b/packages/fs/dist/exists.js @@ -0,0 +1,55 @@ +import { statSync, lstat } from 'fs'; +import { validateArgument } from './utils/validate.js'; +import { ENodeType } from './interfaces.js'; +export function validateInput(methodName, path) { + const methodSignature = methodName + '(path)'; + validateArgument(methodSignature, 'path', path, ['string']); +} +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +export function sync(path) { + let stat; + try { + stat = statSync(path); + if (stat.isDirectory()) { + return 'dir'; + } + else if (stat.isFile()) { + return 'file'; + } + return 'other'; + } + catch (err) { + if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') { + throw err; + } + } + return false; +} +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +export function async(path) { + return new Promise((resolve, reject) => { + lstat(path, (err, stat) => { + if (err) { + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') { + resolve(false); + } + else { + reject(err); + } + } + else if (stat.isDirectory()) { + resolve(ENodeType.DIR); + } + else if (stat.isFile()) { + resolve(ENodeType.FILE); + } + else { + resolve(ENodeType.OTHER); + } + }); + }); +} diff --git a/packages/fs/dist/file.d.ts b/packages/fs/dist/file.d.ts new file mode 100644 index 00000000..67fa5714 --- /dev/null +++ b/packages/fs/dist/file.d.ts @@ -0,0 +1,9 @@ +export interface IOptions { + content: string | Buffer | object | Array; + jsonIndent: number; + mode: string; +} +export declare function validateInput(methodName: string, path: string, options?: IOptions): void; +export declare function defaults(passedCriteria: IOptions | null): IOptions; +export declare function sync(path: string, options: IOptions): void; +export declare function async(path: string, options: IOptions): Promise; diff --git a/packages/fs/dist/file.js b/packages/fs/dist/file.js new file mode 100644 index 00000000..7ce70629 --- /dev/null +++ b/packages/fs/dist/file.js @@ -0,0 +1,148 @@ +import * as fs from 'fs'; +const Q = require('q'); +import { normalizeFileMode } from './utils/mode.js'; +import { validateArgument, validateOptions } from './utils/validate.js'; +import { sync as writeSync, async as writeASync } from './write.js'; +import { ErrNotFile } from './errors.js'; +import { EError } from './interfaces.js'; +const promisedStat = Q.denodeify(fs.stat); +const promisedChmod = Q.denodeify(fs.chmod); +export function validateInput(methodName, path, options) { + const methodSignature = methodName + '(path, [criteria])'; + validateArgument(methodSignature, 'path', path, ['string']); + validateOptions(methodSignature, 'criteria', options, { + content: ['string', 'buffer', 'object', 'array'], + jsonIndent: ['number'], + mode: ['string', 'number'] + }); +} +export function defaults(passedCriteria) { + const criteria = passedCriteria || {}; + if (criteria.mode !== undefined) { + criteria.mode = normalizeFileMode(criteria.mode); + } + return criteria; +} +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +const isFile = (path) => { + let stat; + try { + stat = fs.statSync(path); + } + catch (err) { + // Detection if path exists + if (err.code !== EError.NOEXISTS) { + throw err; + } + } + if (stat && !stat.isFile()) { + throw ErrNotFile(path); + } + return stat; +}; +const checkContent = function (path, mode, options) { + if (options.content !== undefined) { + writeSync(path, options.content, { + mode: mode, + jsonIndent: options.jsonIndent + }); + return true; + } + return false; +}; +const checkMode = function (path, mode, options) { + if (options.mode !== undefined && options.mode !== mode) { + fs.chmodSync(path, options.mode); + } +}; +const accept = (path, stat, options) => { + const mode = normalizeFileMode(stat.mode); + if (!checkContent(path, mode, options)) { + checkMode(path, mode, options); + } +}; +const touch = (path, options) => { + const content = options.content !== undefined ? options.content : ''; + writeSync(path, content, { + mode: options.mode, + jsonIndent: options.jsonIndent + }); +}; +export function sync(path, options) { + options = defaults(options); + const stat = isFile(path); + if (stat !== undefined) { + accept(path, stat, options); + } + else { + touch(path, options); + } +} +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +function isFileAsync(path) { + return new Promise((resolve, reject) => { + promisedStat(path) + .then((stat) => { + if ((stat).isFile()) { + resolve(stat); + } + else { + reject(ErrNotFile(path)); + } + }) + .catch((err) => (err.code === EError.NOEXISTS ? resolve(undefined) : reject(err))); + }); +} +const checkModeAsync = (path, mode, options) => { + if (options.mode !== undefined && options.mode !== mode) { + return promisedChmod(path, options.mode); + } + return undefined; +}; +const checkContentAsync = (path, mode, options) => { + return new Promise((resolve, reject) => { + if (options.content !== undefined) { + writeASync(path, options.content, { + mode: mode, + jsonIndent: options.jsonIndent + }).then(() => resolve(true)) + .catch(reject); + } + else { + resolve(false); + } + }); +}; +async function writeAsync(path, stat, options) { + const mode = normalizeFileMode(stat.mode); + return checkContentAsync(path, mode, options) + .then(contentReplaced => { + if (!contentReplaced) { + return checkModeAsync(path, mode, options); + } + return undefined; + }); +} +const touchAsync = (path, options) => { + return writeASync(path, options.content !== undefined ? options.content : '', { + mode: options.mode, + jsonIndent: options.jsonIndent + }); +}; +export async function async(path, options) { + return new Promise((resolve, reject) => { + options = defaults(options); + isFileAsync(path) + .then((stat) => { + if (stat !== undefined) { + return writeAsync(path, stat, options); + } + return touchAsync(path, options); + }) + .then(resolve, reject); + }); +} diff --git a/packages/fs/dist/find.d.ts b/packages/fs/dist/find.d.ts new file mode 100644 index 00000000..f07cd704 --- /dev/null +++ b/packages/fs/dist/find.d.ts @@ -0,0 +1,15 @@ +import { INode, IInspectOptions } from './interfaces.js'; +export interface IOptions { + matching?: string[]; + files?: boolean; + directories?: boolean; + recursive?: boolean; + cwd?: string; + inspectOptions?: IInspectOptions; +} +export declare function validateInput(methodName: string, path: string, options?: IOptions): void; +export declare const findSync: (path: string, options: IOptions) => string[]; +export declare const findSyncEx: (path: string, options: IOptions) => INode[]; +export declare function sync(path: string, options: IOptions): string[]; +export declare const syncEx: (path: string, options: IOptions) => INode[]; +export declare function async(path: string, options: IOptions): Promise; diff --git a/packages/fs/dist/find.js b/packages/fs/dist/find.js new file mode 100644 index 00000000..b1344689 --- /dev/null +++ b/packages/fs/dist/find.js @@ -0,0 +1,114 @@ +import * as pathUtil from 'path'; +import { sync as treeWalkerSync, stream as treeWalkerStream } from './utils/tree_walker.js'; +import { sync as inspectSync, async as inspectASync } from './inspect.js'; +import { create as matcher } from './utils/matcher.js'; +import { validateArgument, validateOptions } from './utils/validate.js'; +import { ENodeType } from './interfaces.js'; +import { ErrDoesntExists, ErrIsNotDirectory } from './errors.js'; +export function validateInput(methodName, path, options) { + const methodSignature = methodName + '([path], options)'; + validateArgument(methodSignature, 'path', path, ['string']); + validateOptions(methodSignature, 'options', options, { + matching: ['string', 'array of string'], + files: ['boolean'], + directories: ['boolean'], + recursive: ['boolean'] + }); +} +const defaults = (options) => { + const opts = options || {}; + // defaults: + if (opts.files === undefined) { + opts.files = true; + } + if (opts.directories === undefined) { + opts.directories = false; + } + if (opts.recursive === undefined) { + opts.recursive = true; + } + return opts; +}; +const processFoundObjects = (foundObjects, cwd) => foundObjects.map((inspectObj) => pathUtil.relative(cwd, inspectObj.absolutePath)); +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +export const findSync = (path, options) => processFoundObjects(findSyncEx(path, options), options.cwd); +export const findSyncEx = (path, options) => { + const foundInspectObjects = []; + const matchesAnyOfGlobs = matcher(path, options.matching); + treeWalkerSync(path, { + maxLevelsDeep: options.recursive ? Infinity : 1, + inspectOptions: { + absolutePath: true, + ...options.inspectOptions || {} + } + }, (itemPath, item) => { + if (itemPath !== path && matchesAnyOfGlobs(itemPath)) { + if ((item.type === ENodeType.FILE && options.files === true) + || (item.type === ENodeType.DIR && options.directories === true)) { + foundInspectObjects.push(item); + } + } + }); + return foundInspectObjects; +}; +export function sync(path, options) { + const entryPointInspect = inspectSync(path); + if (entryPointInspect === undefined) { + throw ErrDoesntExists(path); + } + else if (entryPointInspect.type !== 'dir') { + throw ErrIsNotDirectory(path); + } + return findSync(path, defaults(options)); +} +export const syncEx = (path, options) => { + const entryPointInspect = inspectSync(path); + if (entryPointInspect === undefined) { + throw ErrDoesntExists(path); + } + else if (entryPointInspect.type !== 'dir') { + throw ErrIsNotDirectory(path); + } + return findSyncEx(path, defaults(options)); +}; +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +const findAsync = (path, options) => { + return new Promise((resolve, reject) => { + const foundInspectObjects = []; + const matchesAnyOfGlobs = matcher(path, options.matching); + const walker = treeWalkerStream(path, { + maxLevelsDeep: options.recursive ? Infinity : 1, + inspectOptions: { + absolutePath: true + } + }).on('readable', () => { + const data = walker.read(); + let item; + if (data && data.path !== path && matchesAnyOfGlobs(data.path)) { + item = data.item; + if ((item.type === ENodeType.FILE && options.files === true) + || (item.type === ENodeType.DIR && options.directories === true)) { + foundInspectObjects.push(item); + } + } + }).on('error', reject) + .on('end', () => { + resolve(processFoundObjects(foundInspectObjects, options.cwd)); + }); + }); +}; +export function async(path, options) { + return inspectASync(path).then(entryPointInspect => { + if (entryPointInspect === undefined) { + throw ErrDoesntExists(path); + } + else if (entryPointInspect.type !== ENodeType.DIR) { + throw ErrIsNotDirectory(path); + } + return findAsync(path, defaults(options)); + }); +} diff --git a/packages/fs/dist/imports.d.ts b/packages/fs/dist/imports.d.ts new file mode 100644 index 00000000..59a920de --- /dev/null +++ b/packages/fs/dist/imports.d.ts @@ -0,0 +1,10 @@ +export declare const file: { + write_atomic: any; +}; +export declare const json: { + parse: (text: string, reviver?: (this: any, key: string, value: any) => any) => any; + serialize: { + (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string; + (value: any, replacer?: (number | string)[] | null, space?: string | number): string; + }; +}; diff --git a/packages/fs/dist/imports.js b/packages/fs/dist/imports.js new file mode 100644 index 00000000..ff41c9be --- /dev/null +++ b/packages/fs/dist/imports.js @@ -0,0 +1,8 @@ +const writefs = require('write-file-atomic'); +export const file = { + write_atomic: writefs +}; +export const json = { + parse: JSON.parse, + serialize: JSON.stringify +}; diff --git a/packages/fs/dist/index.d.ts b/packages/fs/dist/index.d.ts new file mode 100644 index 00000000..921c3740 --- /dev/null +++ b/packages/fs/dist/index.d.ts @@ -0,0 +1,61 @@ +import { Options as AppendOptions } from './append.js'; +import { IOptions as DirOptions } from './dir.js'; +import { IOptions as FileOptions } from './file.js'; +import { IOptions as FindOptions } from './find.js'; +import { Options as InspectTreeOptions } from './inspect_tree.js'; +import { IWriteOptions } from './interfaces.js'; +import { ICopyOptions, INode, IInspectOptions } from './interfaces.js'; +import { ReadWriteDataType, TCopyResult, ENodeType, TDeleteResult } from './interfaces.js'; +export interface IJetpack { + cwd(w?: any): IJetpack | string; + path(): string; + append(path: string, data: string | Buffer | object, options?: AppendOptions): void; + appendAsync(path: string, data: string | Buffer | object, options?: AppendOptions): Promise; + copy(from: string, to: string, options?: ICopyOptions): void; + copyAsync(from: string, to: string, options?: ICopyOptions): Promise; + createWriteStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + }): any; + createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + }): any; + dir(path: string, criteria?: DirOptions): IJetpack; + dirAsync(path: string, criteria?: DirOptions): Promise; + exists(path: string): boolean | string; + existsAsync(path: string): Promise; + file(path: string, criteria?: FileOptions): void; + fileAsync(path: string, criteria?: FileOptions): Promise; + find(startPath: string, options: FindOptions): string[]; + findAsync(startPath: string, options: FindOptions): Promise; + inspect(path: string, fieldsToInclude: IInspectOptions): INode; + inspectAsync(path: string, fieldsToInclude: IInspectOptions): Promise; + inspectTree(path: string, options?: InspectTreeOptions): INode; + inspectTreeAsync(path: string, options?: InspectTreeOptions): Promise; + list(path: string): string[]; + listAsync(path: string): Promise; + move(from: string, to: string): void; + moveAsync(from: string, to: string): Promise; + read(path: string, returnAs?: string): ReadWriteDataType; + readAsync(path: string, returnAs?: string): Promise; + remove(path: string): void; + removeAsync(path: string): Promise; + rename(path: string, newName: string): void; + renameAsync(path: string, newName: string): Promise; + symlink(symlinkValue: string, path: string): void; + symlinkAsync(symlinkValue: string, path: string): Promise; + write(path: string, data: string | Buffer | object, options?: IWriteOptions): void; + writeAsync(path: string, data: string | Buffer | object, options?: IWriteOptions): Promise; +} +export declare const fs: (cwdPath?: string) => IJetpack; +export default fs; diff --git a/packages/fs/dist/index.js b/packages/fs/dist/index.js new file mode 100644 index 00000000..9f58f41a --- /dev/null +++ b/packages/fs/dist/index.js @@ -0,0 +1,224 @@ +import * as util from 'util'; +import * as pathUtil from 'path'; +import * as append from './append.js'; +import * as dir from './dir.js'; +import * as file from './file.js'; +import * as find from './find.js'; +import * as inspect from './inspect.js'; +import * as inspectTree from './inspect_tree.js'; +import * as copy from './copy.js'; +import * as exists from './exists.js'; +import * as list from './list.js'; +import * as move from './move.js'; +import * as remove from './remove.js'; +import * as rename from './rename.js'; +import * as symlink from './symlink.js'; +import * as streams from './streams.js'; +import * as write from './write.js'; +import * as read from './read.js'; +const Q = require('q'); +// The Jetpack Context object. +// It provides the public API, and resolves all paths regarding to +// passed cwdPath, or default process.cwd() if cwdPath was not specified. +export const fs = (cwdPath) => { + const getCwdPath = function () { + return cwdPath || process.cwd(); + }; + const cwd = function (w) { + let args; + let pathParts; + // return current CWD if no arguments specified... + if (arguments.length === 0) { + return getCwdPath(); + } + // ...create new CWD context otherwise + args = Array.prototype.slice.call(arguments); + pathParts = [getCwdPath()].concat(args); + const res = fs(pathUtil.resolve.apply(null, pathParts)); + return res; + }; + // resolves path to inner CWD path of this jetpack instance + const resolvePath = function (path) { + return pathUtil.resolve(getCwdPath(), path); + }; + const getPath = function () { + // add CWD base path as first element of arguments array + Array.prototype.unshift.call(arguments, getCwdPath()); + return pathUtil.resolve.apply(null, arguments); + }; + const normalizeOptions = function (options) { + return options || { cwd: getCwdPath() }; + }; + // API + const api = { + cwd: cwd, + path: getPath, + append: function (path, data, options) { + append.validateInput('append', path, data, options); + append.sync(resolvePath(path), data, options); + }, + appendAsync: function (path, data, options) { + append.validateInput('appendAsync', path, data, options); + return append.async(resolvePath(path), data, options); + }, + copy: function (from, to, options) { + copy.validateInput('copy', from, to, options); + copy.sync(resolvePath(from), resolvePath(to), options); + }, + copyAsync: function (from, to, options) { + copy.validateInput('copyAsync', from, to, options); + return copy.async(resolvePath(from), resolvePath(to), options); + }, + createWriteStream: function (path, options) { + return streams.createWriteStream(resolvePath(path), options); + }, + createReadStream: function (path, options) { + return streams.createReadStream(resolvePath(path), options); + }, + dir: function (path, criteria) { + let normalizedPath; + dir.validateInput('dir', path, criteria); + normalizedPath = resolvePath(path); + dir.sync(normalizedPath, criteria); + return cwd(normalizedPath); + }, + dirAsync: function (path, criteria) { + const deferred = Q.defer(); + let normalizedPath; + dir.validateInput('dirAsync', path, criteria); + normalizedPath = resolvePath(path); + dir.async(normalizedPath, criteria) + .then(function () { + deferred.resolve(cwd(normalizedPath)); + }, deferred.reject); + return deferred.promise; + }, + exists: function (path) { + exists.validateInput('exists', path); + return exists.sync(resolvePath(path)); + }, + existsAsync: function (path) { + exists.validateInput('existsAsync', path); + return exists.async(resolvePath(path)); + }, + file: function (path, criteria) { + file.validateInput('file', path, criteria); + file.sync(resolvePath(path), criteria); + return this; + }, + fileAsync: function (path, criteria) { + const deferred = Q.defer(); + const that = this; + file.validateInput('fileAsync', path, criteria); + file.async(resolvePath(path), criteria) + .then(function () { + deferred.resolve(that); + }, deferred.reject); + return deferred.promise; + }, + find: function (startPath, options) { + // startPath is optional parameter, if not specified move rest of params + // to proper places and default startPath to CWD. + if (typeof options === 'undefined' && typeof startPath === 'object') { + options = startPath; + startPath = '.'; + } + find.validateInput('find', startPath, options); + return find.sync(resolvePath(startPath), normalizeOptions(options)); + }, + findAsync: function (startPath, options) { + // startPath is optional parameter, if not specified move rest of params + // to proper places and default startPath to CWD. + if (typeof options === 'undefined' && typeof startPath === 'object') { + options = startPath; + startPath = '.'; + } + find.validateInput('findAsync', startPath, options); + return find.async(resolvePath(startPath), normalizeOptions(options)); + }, + inspect: function (path, fieldsToInclude) { + inspect.validateInput('inspect', path, fieldsToInclude); + return inspect.sync(resolvePath(path), fieldsToInclude); + }, + inspectAsync: function (path, fieldsToInclude) { + inspect.validateInput('inspectAsync', path, fieldsToInclude); + return inspect.async(resolvePath(path), fieldsToInclude); + }, + inspectTree: function (path, options) { + inspectTree.validateInput('inspectTree', path, options); + return inspectTree.sync(resolvePath(path), options); + }, + inspectTreeAsync: function (path, options) { + inspectTree.validateInput('inspectTreeAsync', path, options); + return inspectTree.async(resolvePath(path), options); + }, + list: function (path) { + list.validateInput('list', path); + return list.sync(resolvePath(path || '.')); + }, + listAsync: function (path) { + list.validateInput('listAsync', path); + return list.async(resolvePath(path || '.')); + }, + move: function (from, to) { + move.validateInput('move', from, to); + move.sync(resolvePath(from), resolvePath(to)); + }, + moveAsync: function (from, to) { + move.validateInput('moveAsync', from, to); + return move.async(resolvePath(from), resolvePath(to)); + }, + read: function (path, returnAs) { + read.validateInput('read', path, returnAs); + return read.sync(resolvePath(path), returnAs); + }, + readAsync: function (path, returnAs) { + read.validateInput('readAsync', path, returnAs); + return read.async(resolvePath(path), returnAs); + }, + remove: function (path) { + remove.validateInput('remove', path); + // If path not specified defaults to CWD + remove.sync(resolvePath(path || '.')); + }, + removeAsync: function (path) { + remove.validateInput('removeAsync', path); + // If path not specified defaults to CWD + return remove.async(resolvePath(path || '.')); + }, + rename: function (path, newName) { + rename.validateInput('rename', path, newName); + rename.sync(resolvePath(path), newName); + }, + renameAsync: function (path, newName) { + rename.validateInput('renameAsync', path, newName); + return rename.async(resolvePath(path), newName); + }, + symlink: function (symlinkValue, path) { + symlink.validateInput('symlink', symlinkValue, path); + symlink.sync(symlinkValue, resolvePath(path)); + }, + symlinkAsync: function (symlinkValue, path) { + symlink.validateInput('symlinkAsync', symlinkValue, path); + return symlink.async(symlinkValue, resolvePath(path)); + }, + write: function (path, data, options) { + write.validateInput('write', path, data, options); + write.sync(resolvePath(path), data, options); + }, + writeAsync: function (path, data, options) { + write.validateInput('writeAsync', path, data, options); + return write.async(resolvePath(path), data, options); + } + }; + if (util.inspect['custom'] !== undefined) { + // Without this console.log(jetpack) throws obscure error. Details: + // https://github.com/szwacz/fs-jetpack/issues/29 + // https://nodejs.org/api/util.html#util_custom_inspection_functions_on_objects + api[util.inspect['custom']] = function () { + return getCwdPath(); + }; + } + return api; +}; +export default fs; diff --git a/packages/fs/dist/inspect.d.ts b/packages/fs/dist/inspect.d.ts new file mode 100644 index 00000000..8d934006 --- /dev/null +++ b/packages/fs/dist/inspect.d.ts @@ -0,0 +1,7 @@ +import { INode, IInspectOptions } from './interfaces.js'; +export declare const supportedChecksumAlgorithms: string[]; +export declare function DefaultInspectOptions(): IInspectOptions; +export declare function validateInput(methodName: string, path: string, options?: IInspectOptions): void; +export declare function createItem(path: string, options?: IInspectOptions): INode; +export declare function sync(path: string, options?: IInspectOptions): INode; +export declare const async: (path: string, options?: IInspectOptions) => Promise; diff --git a/packages/fs/dist/inspect.js b/packages/fs/dist/inspect.js new file mode 100644 index 00000000..4fdc9ee2 --- /dev/null +++ b/packages/fs/dist/inspect.js @@ -0,0 +1,135 @@ +import * as fs from 'node:fs'; +import { readlinkSync, statSync, lstatSync, readFileSync } from 'node:fs'; +import { getType } from 'mime'; +import * as pathUtil from 'node:path'; +import { createHash } from 'node:crypto'; +import { validateArgument, validateOptions } from './utils/validate.js'; +import { ENodeType } from './interfaces.js'; +export const supportedChecksumAlgorithms = ['md5', 'sha1', 'sha256', 'sha512']; +export function DefaultInspectOptions() { + return { + times: true, + mode: true + }; +} +export function validateInput(methodName, path, options) { + const methodSignature = methodName + '(path, [options])'; + validateArgument(methodSignature, 'path', path, ['string']); + validateOptions(methodSignature, 'options', options, { + checksum: ['string'], + mode: ['boolean'], + times: ['boolean'], + absolutePath: ['boolean'], + symlinks: ['boolean'], + size: 'number', + mime: 'string' + }); + if (options && options.checksum !== undefined + && !supportedChecksumAlgorithms.includes(options.checksum)) { + throw new Error('Argument "options.checksum" passed to ' + methodSignature + + ' must have one of values: ' + supportedChecksumAlgorithms.join(', ')); + } +} +const createInspectObj = (path, options, stat) => { + const obj = {}; + obj.name = pathUtil.basename(path); + if (stat.isFile()) { + obj.type = ENodeType.FILE; + obj.size = stat.size; + } + else if (stat.isDirectory()) { + obj.type = ENodeType.DIR; + } + else if (stat.isSymbolicLink()) { + obj.type = ENodeType.SYMLINK; + } + else { + obj.type = ENodeType.OTHER; + } + if (options.mode) { + obj.mode = stat.mode; + } + if (options.mime) { + if (stat.isDirectory()) { + obj.mime = 'inode/directory'; + } + else if (stat.isBlockDevice()) { + obj.mime = 'inode/blockdevice'; + } + else if (stat.isCharacterDevice()) { + obj.mime = 'inode/chardevice'; + } + else if (stat.isSymbolicLink()) { + obj.mime = 'inode/symlink'; + } + else if (stat.isFIFO()) { + obj.mime = 'inode/fifo'; + } + else if (stat.isSocket()) { + obj.mime = 'inode/socket'; + } + else { + obj.mime = getType(path); + } + } + if (options.times) { + obj.accessTime = stat.atime; + obj.modifyTime = stat.mtime; + obj.changeTime = stat.ctime; + obj.birthTime = stat.birthtime; + } + if (options.absolutePath) { + obj.absolutePath = path; + } + return obj; +}; +export function createItem(path, options) { + options = options || DefaultInspectOptions(); + const stat = (options.symlinks ? lstatSync : statSync)(path); + return createInspectObj(path, options, stat); +} +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +const fileChecksum = (path, algo) => { + const hash = createHash(algo); + const data = readFileSync(path); + hash.update(data); + return hash.digest('hex'); +}; +const addExtraFieldsSync = (path, inspectObj, options) => { + if (inspectObj.type === ENodeType.FILE && options.checksum) { + inspectObj[options.checksum] = fileChecksum(path, options.checksum); + } + else if (inspectObj.type === ENodeType.SYMLINK) { + inspectObj.pointsAt = readlinkSync(path); + } + return inspectObj; +}; +export function sync(path, options) { + let statOperation = fs.lstatSync; + let stat; + const opts = options || {}; + if (opts.symlinks === "follow") { + statOperation = fs.statSync; + } + try { + stat = statOperation(path); + } + catch (err) { + // Detection if path exists + if (err.code === "ENOENT") { + // Doesn't exist. Return undefined instead of throwing. + return undefined; + } + throw err; + } + const inspectObj = createInspectObj(path, opts, stat); + addExtraFieldsSync(path, inspectObj, opts); + return inspectObj; +} +export const async = async (path, options) => { + options = options || {}; + const stat = await (options.symlinks ? fs.promises.lstat : fs.promises.statfs)(path); + return addExtraFieldsSync(path, createInspectObj(path, options, stat), options); +}; diff --git a/packages/fs/dist/inspect_tree.d.ts b/packages/fs/dist/inspect_tree.d.ts new file mode 100644 index 00000000..7a8b0f39 --- /dev/null +++ b/packages/fs/dist/inspect_tree.d.ts @@ -0,0 +1,9 @@ +import type { INode } from './interfaces.js'; +export interface Options { + checksum: string; + relativePath: boolean; + symlinks: boolean; +} +export declare function validateInput(methodName: string, path: string, options: Options): void; +export declare function sync(path: string, options?: any): any | undefined; +export declare function async(path: string, options?: Options): Promise; diff --git a/packages/fs/dist/inspect_tree.js b/packages/fs/dist/inspect_tree.js new file mode 100644 index 00000000..7cdbb348 --- /dev/null +++ b/packages/fs/dist/inspect_tree.js @@ -0,0 +1,127 @@ +import { createHash } from 'node:crypto'; +import * as pathUtil from 'node:path'; +import { sync as inspectSync, async as inspectASync, supportedChecksumAlgorithms } from './inspect.js'; +import { ENodeType } from './interfaces.js'; +import { sync as listSync, async as listASync } from './list.js'; +import { validateArgument, validateOptions } from './utils/validate.js'; +export function validateInput(methodName, path, options) { + const methodSignature = methodName + '(path, options)'; + validateArgument(methodSignature, 'path', path, ['string']); + validateOptions(methodSignature, 'options', options, { + checksum: ['string'], + relativePath: ['boolean'] + }); + if (options && options.checksum !== undefined + && supportedChecksumAlgorithms.indexOf(options.checksum) === -1) { + throw new Error('Argument "options.checksum" passed to ' + methodSignature + + ' must have one of values: ' + supportedChecksumAlgorithms.join(', ')); + } +} +function generateTreeNodeRelativePath(parent, path) { + if (!parent) { + return '.'; + } + return parent.relativePath + '/' + pathUtil.basename(path); +} +// Creates checksum of a directory by using +// checksums and names of all its children inside. +const checksumOfDir = (inspectList, algo) => { + const hash = createHash(algo); + inspectList.forEach(function (inspectObj) { + hash.update(inspectObj.name + inspectObj[algo]); + }); + return hash.digest('hex'); +}; +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +function inspectTreeNodeSync(path, options, parent) { + const treeBranch = inspectSync(path, { checksum: options.checksum, symlinks: options.symlinks }); + if (treeBranch) { + if (options.relativePath) { + treeBranch.relativePath = generateTreeNodeRelativePath(parent, path); + } + if (treeBranch.type === ENodeType.DIR /*|| (options.symlinks && treeBranch.type === 'symlink')*/) { + treeBranch.size = 0; + treeBranch.children = (listSync(path) || []).map(function (filename) { + const subBranchPath = pathUtil.join(path, filename); + const treeSubBranch = inspectTreeNodeSync(subBranchPath, options, treeBranch); + // Add together all childrens' size to get directory combined size. + treeBranch.size += treeSubBranch.size || 0; + // treeBranch.total += treeSubBranch.total; + return treeSubBranch; + }); + if (options.checksum) { + treeBranch[options.checksum] = checksumOfDir(treeBranch.children, options.checksum); + } + } + } + return treeBranch; +} +export function sync(path, options) { + options = options || {}; + options.symlinks = true; + return inspectTreeNodeSync(path, options, undefined); +} +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +function inspectTreeNodeAsync(path, options, parent) { + return new Promise((resolve, reject) => { + const inspectAllChildren = (treeBranch) => { + return new Promise((resolve, reject) => { + listASync(path).then((children) => { + const doNext = (index) => { + let subPath; + if (index === children.length) { + if (options.checksum) { + // We are done, but still have to calculate checksum of whole directory. + [options.checksum] = checksumOfDir(treeBranch.children, options.checksum); + } + resolve(1); + } + else { + subPath = pathUtil.join(path, children[index]); + inspectTreeNodeAsync(subPath, options, treeBranch) + .then((treeSubBranch) => { + children[index] = treeSubBranch; + treeBranch.size += treeSubBranch.size || 0; + doNext(index + 1); + }) + .catch(reject); + } + }; + treeBranch.children = children; + treeBranch.size = 0; + doNext(0); + }); + }); + }; + inspectASync(path, options) + .then((treeBranch) => { + if (!treeBranch) { + // Given path doesn't exist. We are done. + resolve(treeBranch); + } + else { + if (options.relativePath) { + treeBranch.relativePath = generateTreeNodeRelativePath(parent, path); + } + if (treeBranch.type !== ENodeType.DIR) { + resolve(treeBranch); + } + else { + inspectAllChildren(treeBranch) + .then(() => resolve(treeBranch)) + .catch(reject); + } + } + }) + .catch(reject); + }); +} +export function async(path, options) { + options = options || {}; + options.symlinks = true; + return inspectTreeNodeAsync(path, options); +} diff --git a/packages/fs/dist/interfaces.d.ts b/packages/fs/dist/interfaces.d.ts new file mode 100644 index 00000000..78a66764 --- /dev/null +++ b/packages/fs/dist/interfaces.d.ts @@ -0,0 +1,460 @@ +export declare enum ENodeType { + FILE = "file", + DIR = "dir", + SYMLINK = "symlink", + OTHER = "other", + BLOCK = "block" +} +/** + * Native errors. + * @todo : replace with errno. + */ +export declare let EError: any; +export interface INode { + name: string; + type: ENodeType | string; + size: number; + accessTime?: Date; + modifyTime?: Date; + changeTime?: Date; + birthTime?: Date; + absolutePath?: string; + mode?: number; + pointsAt?: string; + relativePath?: string; + children: INode[]; + total?: number; + checksum?: string; + mime?: string; +} +/** + * The options for "inspect". + * + * @export + * @interface IInspectOptions + */ +export interface IInspectOptions { + checksum?: string; + mode?: boolean; + times?: boolean; + absolutePath?: boolean; + symlinks?: boolean | string; + size?: boolean; + mime?: boolean; +} +export interface INodeReport { + node: IProcessingNode; + error: string; + resolved: IConflictSettings; +} +/** + * The accepted types for write and read as union. + */ +export type ReadWriteDataType = string | Buffer | object; +/** + * An extended version of Error to make typescript happy. This has been copied from + * the official Node typings. + * + * @export + * @class ErrnoException + * @extends {Error} + */ +export declare class ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; +} +/** + * Structure for file operations. + */ +export interface IProcessingNode { + path: string; + item: INode; + status?: ENodeOperationStatus; + dst?: string; +} +/** + * Basic flags during a file operation. + * + * @export + * @enum {number} + */ +export declare enum EBaseFlags { + /** + * When copying, don't copy symlinks but resolve them instead. + */ + FOLLOW_SYMLINKS = 8 +} +/** + * Flags to determine certain properties during inspection. + * + * @export + * @enum {number} + */ +export declare enum EInspectFlags { + MODE = 2, + TIMES = 4, + SYMLINKS = 8, + FILE_SIZE = 16, + DIRECTORY_SIZE = 32, + CHECKSUM = 64, + MIME = 128 +} +/** + * Basic options for file operations: used by cp, mv, rename and rm. + * + * @export + * @interface IBaseOptions + */ +export interface IBaseOptions { + /** + * Array of glob minimatch patterns + * + * @type {string[]} + * @memberOf IBaseOptions + */ + matching?: string[]; + /** + * A function called to reject or accept nodes. This is used only when matching + * has been left empty. + * @memberOf IBaseOptions + */ + filter?: (from: string) => boolean; + /** + * Flags to determine properties per node + * + * @type {EInspectFlags} + * @memberOf IBaseOptions + */ + flags?: EInspectFlags; +} +/** + * Callback prototype signature when an item has been copied. + * This is used to abort the copy process when returning false. + * + * @param {string} path The path of the item + * @param {number} current The current index of the item + * @param {number} total The total of all items + * @param {INode} [item] The node data for the item + * @param {string} [item] The destination path + * @returns {boolean} + */ +export type ItemProgressCallback = (path: string, current: number, total: number, item?: INode, dst?: string) => boolean; +/** + * Callback prototype signature when an item conflict occurs. + * It's async since the conflict might be resolved in an client application and hence + * we have to wait til the user decided. + * + * This is not being called if: + * - a previous callback returned with IConflictSettings#mode == ALWAYS + * - the options object already contains pre-defined conflict settings. + * + * @param {string} path The path of the item. + * @param {INode} item The node data. + * @param {string} err The native error code of the conflict (EEXIST,...) + * @returns {Promise} + */ +export type ResolveConflictCallback = (path: string, item: INode, err: string) => Promise; +/** + * Callback prototype signature when an item is written during a copy. +**/ +export type ContentCallback = (path: string, data: Buffer, item: INode) => Buffer; +/** + * Callback prototype signature to rename an item when copied + * + * @param {string} from The source path. + * @param {string} from The target path. + * @returns {string|null} + */ +export type RenameCallback = (from: string, to: string) => string | null; +/** + * Callback prototype signature when a file with at least 5MB size is being copied. + * + * @param {string} path The path of the item. + * @param {number} current The current copied bytes. + * @param {number} total The total size in bytes. + * @returns {Promise} + */ +export type WriteProgressCallback = (path: string, current: number, total: number) => void; +/** + * Status of a node operation. + * + * @export + * @enum {number} + */ +export declare enum ENodeOperationStatus { + COLLECTED = 0, + CHECKED = 1, + PROCESSING = 2, + PROCESS = 3, + ASKING = 4, + ANSWERED = 5, + DONE = 6 +} +/** + * The possible modes to resolve a conflict during copy and move. + * + * @export + * @enum {number} + */ +export declare enum EResolveMode { + SKIP = 0, + OVERWRITE = 1, + IF_NEWER = 2, + IF_SIZE_DIFFERS = 3, + APPEND = 4, + THROW = 5, + RETRY = 6, + ABORT = 7 +} +/** + * Additional flags for copy + * + * @export + * @enum {number} + */ +export declare enum ECopyFlags { + /** + * Transfer atime and mtime of source to target + */ + NONE = 0, + /** + * Transfer atime and mtime of source to target + */ + PRESERVE_TIMES = 2, + /** + * Empty the target folder + */ + EMPTY = 4, + /** + * When copying, don't copy symlinks but resolve them instead. + */ + FOLLOW_SYMLINKS = 8, + /** + * Collect errors & success + */ + REPORT = 16 +} +export interface IStatOptions { + /** + * Array of glob minimatch patterns + * + * @type {string[]} + * @memberOf ICopyOptions + */ + matching?: string[]; + /** + * A function called to reject or accept nodes to be copied. This is used only when matching + * has been left empty. + * @memberOf ICopyOptions + */ + filter?: (from: string) => boolean; + /** + * A progress callback for any copied item. Only executed in async. + */ + progress?: ItemProgressCallback; +} +/** + * Copy options + * + * @export + * @interface ICopyOptions + */ +export interface ICopyOptions { + /** + * @type {boolean} + * @memberOf ICopyOptions + */ + overwrite?: boolean; + /** + * Array of glob minimatch patterns + * + * @type {string[]} + * @memberOf ICopyOptions + */ + matching?: string[]; + /** + * A function called to reject or accept nodes to be copied. This is used only when matching + * has been left empty. + * @memberOf ICopyOptions + */ + filter?: (from: string) => boolean; + /** + * A progress callback for any copied item. Only executed in async. + */ + progress?: ItemProgressCallback; + /** + * A progress function called for async and larger files only. + * + * @type {WriteProgressCallback} + * @memberOf ICopyOptions + */ + writeProgress?: WriteProgressCallback; + /** + * Callback function when writing source content + */ + content?: ContentCallback; + /** + * A callback when a conflict or error occurs. This is being called only if the user + * didn't provide conflictSettings. + * + * @type {ResolveConflictCallback} + * @memberOf ICopyOptions + */ + conflictCallback?: ResolveConflictCallback; + /** + * A callback to rename nodes during copy + * @type {ResolveConflictCallback} + * @memberOf ICopyOptions + */ + renameCallback?: RenameCallback; + /** + * Ability to set conflict resolver settings in advance, so that no callback will be called. + * + * @type {IConflictSettings} + * @memberOf ICopyOptions + */ + conflictSettings?: IConflictSettings; + /** + * Throttel copy for larger files. This will be only used when writeProgress is set and the file is at least 5MB. + * + * @type {number} + * @memberOf ICopyOptions + */ + throttel?: number; + /** + * Print some debug messages. + * + * @type {boolean} + * @memberOf ICopyOptions + */ + debug?: boolean; + /** + * The copy flags. + * + * @type {ECopyFlags} + * @memberOf ICopyOptions + */ + flags?: ECopyFlags; +} +/** + * An enumeration to narrow a conflict resolve to a single item or for all following conflicts. + * + * @export + * @enum {number} + */ +export declare enum EResolve { + /** + * Always will use the chose conflict settings for all following conflicts. + */ + ALWAYS = 0, + /** + * 'This' will use the conflict settings for a single conflict so the conflict callback will be triggered again for the next conflict. + */ + THIS = 1 +} +/** + * A composite conflict settings and it's scope. This is the result type + * for the conflict callback. + * + * @export + * @interface IConflictSettings + */ +export interface IConflictSettings { + /** + * How to resolve this conflict/error. + * + * @type {EResolveMode} + * @memberOf IConflictSettings + */ + overwrite: EResolveMode; + /** + * The scope of this conflict resolver: always or this. + * + * @type {EResolve} + * @memberOf IConflictSettings + */ + mode: EResolve; + /** + * Track the origin error type for this settings. + * + * @type {string} + * @memberOf IConflictSettings + */ + error?: string; +} +export type TCopyResult = void | INodeReport[]; +/** + * fs/write options. + * + * @export + * @interface IWriteOptions + */ +export interface IWriteOptions { + atomic?: boolean; + jsonIndent?: number; + mode?: string; +} +export type TDeleteResult = void | INodeReport[]; +/** + * Additional flags for delete + * + * @export + * @enum {number} + */ +export declare enum EDeleteFlags { + REPORT = 16 +} +/** + * Delete options + * + * @export + * @interface IDeleteOptions + */ +export interface IDeleteOptions { + /** + * Array of glob minimatch patterns + * + * @type {string[]} + * @memberOf IDeleteOptions + */ + matching?: string[]; + /** + * A callback when a conflict or error occurs. This is being called only if the user + * didn't provide conflictSettings. + * + * @type {ResolveConflictCallback} + * @memberOf IDeleteOptions + */ + conflictCallback?: ResolveConflictCallback; + /** + * Ability to set conflict resolver settings in advance, so that no callback will be called. + * + * @type {IConflictSettings} + * @memberOf IDeleteOptions + */ + conflictSettings?: IConflictSettings; + /** + * + * A progress callback for any deleted item. Only excecuted in async. + * @type {ItemProgressCallback} + * @memberOf IDeleteOptions + */ + progress?: ItemProgressCallback; + /** + * Print some messages. + * + * @type {boolean} + * @memberOf IDeleteOptions + */ + debug?: boolean; + /** + * A function called to reject or accept nodes to be copied. This is used only when matching + * has been left empty. + * @memberOf IDeleteOptions + */ + filter?: (from: string) => boolean; + flags?: EDeleteFlags; +} diff --git a/packages/fs/dist/interfaces.js b/packages/fs/dist/interfaces.js new file mode 100644 index 00000000..2d79c9bf --- /dev/null +++ b/packages/fs/dist/interfaces.js @@ -0,0 +1,163 @@ +///////////////////////////////////////////////////////// +// +// Enums +// +export var ENodeType; +(function (ENodeType) { + ENodeType["FILE"] = "file"; + ENodeType["DIR"] = "dir"; + ENodeType["SYMLINK"] = "symlink"; + ENodeType["OTHER"] = "other"; + ENodeType["BLOCK"] = "block"; +})(ENodeType || (ENodeType = {})); +/** + * Native errors. + * @todo : replace with errno. + */ +export let EError = { + NONE: 'None', + EXISTS: 'EEXIST', + PERMISSION: 'EACCES', + NOEXISTS: 'ENOENT', + CROSS_DEVICE: 'EXDEV' +}; +/** + * An extended version of Error to make typescript happy. This has been copied from + * the official Node typings. + * + * @export + * @class ErrnoException + * @extends {Error} + */ +export class ErrnoException extends Error { + errno; + code; + path; + syscall; + stack; +} +/** + * Basic flags during a file operation. + * + * @export + * @enum {number} + */ +export var EBaseFlags; +(function (EBaseFlags) { + /** + * When copying, don't copy symlinks but resolve them instead. + */ + EBaseFlags[EBaseFlags["FOLLOW_SYMLINKS"] = 8] = "FOLLOW_SYMLINKS"; +})(EBaseFlags || (EBaseFlags = {})); +/** + * Flags to determine certain properties during inspection. + * + * @export + * @enum {number} + */ +export var EInspectFlags; +(function (EInspectFlags) { + EInspectFlags[EInspectFlags["MODE"] = 2] = "MODE"; + EInspectFlags[EInspectFlags["TIMES"] = 4] = "TIMES"; + EInspectFlags[EInspectFlags["SYMLINKS"] = 8] = "SYMLINKS"; + EInspectFlags[EInspectFlags["FILE_SIZE"] = 16] = "FILE_SIZE"; + EInspectFlags[EInspectFlags["DIRECTORY_SIZE"] = 32] = "DIRECTORY_SIZE"; + EInspectFlags[EInspectFlags["CHECKSUM"] = 64] = "CHECKSUM"; + EInspectFlags[EInspectFlags["MIME"] = 128] = "MIME"; +})(EInspectFlags || (EInspectFlags = {})); +/** + * Status of a node operation. + * + * @export + * @enum {number} + */ +export var ENodeOperationStatus; +(function (ENodeOperationStatus) { + // Node has been collected + ENodeOperationStatus[ENodeOperationStatus["COLLECTED"] = 0] = "COLLECTED"; + // Node has been checked for existence + ENodeOperationStatus[ENodeOperationStatus["CHECKED"] = 1] = "CHECKED"; + // Node is in progress, before copy + ENodeOperationStatus[ENodeOperationStatus["PROCESSING"] = 2] = "PROCESSING"; + // Node is in process + ENodeOperationStatus[ENodeOperationStatus["PROCESS"] = 3] = "PROCESS"; + // Node is in conflict, and user is being asked what to do + ENodeOperationStatus[ENodeOperationStatus["ASKING"] = 4] = "ASKING"; + // Node conflict has been resolved by user + ENodeOperationStatus[ENodeOperationStatus["ANSWERED"] = 5] = "ANSWERED"; + // Node has been copied + ENodeOperationStatus[ENodeOperationStatus["DONE"] = 6] = "DONE"; +})(ENodeOperationStatus || (ENodeOperationStatus = {})); +/** + * The possible modes to resolve a conflict during copy and move. + * + * @export + * @enum {number} + */ +export var EResolveMode; +(function (EResolveMode) { + EResolveMode[EResolveMode["SKIP"] = 0] = "SKIP"; + EResolveMode[EResolveMode["OVERWRITE"] = 1] = "OVERWRITE"; + EResolveMode[EResolveMode["IF_NEWER"] = 2] = "IF_NEWER"; + EResolveMode[EResolveMode["IF_SIZE_DIFFERS"] = 3] = "IF_SIZE_DIFFERS"; + EResolveMode[EResolveMode["APPEND"] = 4] = "APPEND"; + EResolveMode[EResolveMode["THROW"] = 5] = "THROW"; + EResolveMode[EResolveMode["RETRY"] = 6] = "RETRY"; + EResolveMode[EResolveMode["ABORT"] = 7] = "ABORT"; +})(EResolveMode || (EResolveMode = {})); +/** + * Additional flags for copy + * + * @export + * @enum {number} + */ +export var ECopyFlags; +(function (ECopyFlags) { + /** + * Transfer atime and mtime of source to target + */ + ECopyFlags[ECopyFlags["NONE"] = 0] = "NONE"; + /** + * Transfer atime and mtime of source to target + */ + ECopyFlags[ECopyFlags["PRESERVE_TIMES"] = 2] = "PRESERVE_TIMES"; + /** + * Empty the target folder + */ + ECopyFlags[ECopyFlags["EMPTY"] = 4] = "EMPTY"; + /** + * When copying, don't copy symlinks but resolve them instead. + */ + ECopyFlags[ECopyFlags["FOLLOW_SYMLINKS"] = 8] = "FOLLOW_SYMLINKS"; + /** + * Collect errors & success + */ + ECopyFlags[ECopyFlags["REPORT"] = 16] = "REPORT"; +})(ECopyFlags || (ECopyFlags = {})); +/** + * An enumeration to narrow a conflict resolve to a single item or for all following conflicts. + * + * @export + * @enum {number} + */ +export var EResolve; +(function (EResolve) { + /** + * Always will use the chose conflict settings for all following conflicts. + */ + EResolve[EResolve["ALWAYS"] = 0] = "ALWAYS"; + /** + * 'This' will use the conflict settings for a single conflict so the conflict callback will be triggered again for the next conflict. + */ + EResolve[EResolve["THIS"] = 1] = "THIS"; +})(EResolve || (EResolve = {})); +/** + * Additional flags for delete + * + * @export + * @enum {number} + */ +export var EDeleteFlags; +(function (EDeleteFlags) { + EDeleteFlags[EDeleteFlags["REPORT"] = 16] = "REPORT"; +})(EDeleteFlags || (EDeleteFlags = {})); diff --git a/packages/fs/dist/iterator.d.ts b/packages/fs/dist/iterator.d.ts new file mode 100644 index 00000000..4e5e23b9 --- /dev/null +++ b/packages/fs/dist/iterator.d.ts @@ -0,0 +1,4 @@ +import { IProcessingNode, IBaseOptions } from './interfaces.js'; +import { ArrayIterator } from '@polymech/core/iterator'; +export declare function async(from: string, options: IBaseOptions): Promise>; +export declare function sync(from: string, options: IBaseOptions): ArrayIterator; diff --git a/packages/fs/dist/iterator.js b/packages/fs/dist/iterator.js new file mode 100644 index 00000000..3a9b79e8 --- /dev/null +++ b/packages/fs/dist/iterator.js @@ -0,0 +1,72 @@ +import { sync as treeWalkerSync } from './utils/tree_walker.js'; +import { ENodeOperationStatus, EInspectFlags } from './interfaces.js'; +import { create as matcher } from './utils/matcher.js'; +import { ArrayIterator } from '@polymech/core/iterator'; +export async function async(from, options) { + if (options && !options.filter) { + if (options.matching) { + options.filter = matcher(from, options.matching); + } + else { + options.filter = () => true; + } + } + const collectorSync = function (path, item) { + if (!item) { + return; + } + if (options.filter(path)) { + nodes.push({ + path: path, + item: item, + status: ENodeOperationStatus.COLLECTED + }); + } + }; + const nodes = []; + return new Promise((resolve, reject) => { + treeWalkerSync(from, { + inspectOptions: { + mode: options ? options.flags & EInspectFlags.MODE ? true : false : false, + times: options ? options.flags & EInspectFlags.TIMES ? true : false : false, + checksum: options ? options.flags & EInspectFlags.CHECKSUM ? 'md5' : null : null, + symlinks: options ? options.flags & EInspectFlags.SYMLINKS ? false : true : true, + mime: options ? options.flags & EInspectFlags.MIME ? true : false : false + } + }, collectorSync); + resolve(new ArrayIterator(nodes)); + }); +} +export function sync(from, options) { + if (options && !options.filter) { + if (options.matching) { + options.filter = matcher(from, options.matching); + } + else { + options.filter = () => true; + } + } + const nodes = []; + const collectorSync = function (path, item) { + if (!item) { + return; + } + if (options.filter(path)) { + nodes.push({ + path: path, + item: item, + status: ENodeOperationStatus.COLLECTED + }); + } + }; + treeWalkerSync(from, { + inspectOptions: { + mode: options ? options.flags & EInspectFlags.MODE ? true : false : false, + times: options ? options.flags & EInspectFlags.TIMES ? true : false : false, + checksum: options ? options.flags & EInspectFlags.CHECKSUM ? 'md5' : null : null, + symlinks: options ? options.flags & EInspectFlags.SYMLINKS ? false : true : true, + mime: options ? options.flags & EInspectFlags.MIME ? true : false : false + } + }, collectorSync); + return new ArrayIterator(nodes); +} diff --git a/packages/fs/dist/list.d.ts b/packages/fs/dist/list.d.ts new file mode 100644 index 00000000..ba5cbcf7 --- /dev/null +++ b/packages/fs/dist/list.d.ts @@ -0,0 +1,4 @@ +export declare function validateInput(methodName: string, path: string): void; +export declare function _readdirSync(path: string): string[]; +export declare function sync(path: string): string[]; +export declare function async(path: string): Promise; diff --git a/packages/fs/dist/list.js b/packages/fs/dist/list.js new file mode 100644 index 00000000..dea602f0 --- /dev/null +++ b/packages/fs/dist/list.js @@ -0,0 +1,62 @@ +import { readdirSync, readdir } from 'fs'; +import { validateArgument } from './utils/validate.js'; +import { isMacintosh } from './utils/platform.js'; +import { normalizeNFC } from './utils/strings.js'; +export function validateInput(methodName, path) { + const methodSignature = methodName + '(path)'; + validateArgument(methodSignature, 'path', path, ['string', 'undefined']); +} +export function _readdirSync(path) { + // Mac: uses NFD unicode form on disk, but we want NFC + // See also https://github.com/nodejs/node/issues/2165 + if (isMacintosh) { + return readdirSync(path).map(c => normalizeNFC(c)); + } + return readdirSync(path); +} +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +export function sync(path) { + try { + return _readdirSync(path); + } + catch (err) { + if (err.code === 'ENOENT') { + // Doesn't exist. Return undefined instead of throwing. + return undefined; + } + throw err; + } +} +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +function readdirASync(path) { + // export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + // Mac: uses NFD unicode form on disk, but we want NFC + // See also https://github.com/nodejs/node/issues/2165 + return new Promise((resolve, reject) => { + if (isMacintosh) { + readdir(path, (err, files) => { + if (err) { + reject(err); + } + resolve(files); + }); + } + readdir(path, (err, files) => { + if (err) { + reject(err); + } + resolve(files); + }); + }); +} +export function async(path) { + return new Promise((resolve, reject) => { + readdirASync(path) + .then((list) => resolve(list)) + .catch(err => (err.code === 'ENOENT' ? resolve(undefined) : reject(err))); + }); +} diff --git a/packages/fs/dist/main.d.ts b/packages/fs/dist/main.d.ts new file mode 100644 index 00000000..b7988016 --- /dev/null +++ b/packages/fs/dist/main.d.ts @@ -0,0 +1,2 @@ +#!/usr/bin/env node +export {}; diff --git a/packages/fs/dist/main.js b/packages/fs/dist/main.js new file mode 100644 index 00000000..f23327c2 --- /dev/null +++ b/packages/fs/dist/main.js @@ -0,0 +1,10 @@ +#!/usr/bin/env node +import * as cli from 'yargs'; +const argv = cli.argv; +if (argv.h || argv.help) { + cli.showHelp(); + process.exit(); +} +else if (argv.v || argv.version) { + process.exit(); +} diff --git a/packages/fs/dist/move.d.ts b/packages/fs/dist/move.d.ts new file mode 100644 index 00000000..e6b0f9a3 --- /dev/null +++ b/packages/fs/dist/move.d.ts @@ -0,0 +1,3 @@ +export declare const validateInput: (methodName: string, from: string, to: string) => void; +export declare const sync: (from: string, to: string) => void; +export declare const async: (from: string, to: string) => Promise; diff --git a/packages/fs/dist/move.js b/packages/fs/dist/move.js new file mode 100644 index 00000000..df4d812e --- /dev/null +++ b/packages/fs/dist/move.js @@ -0,0 +1,106 @@ +import * as pathUtil from 'path'; +import { rename, renameSync } from 'fs'; +import { async as existsAsync, sync as existsSync } from './exists.js'; +import { validateArgument } from './utils/validate.js'; +import { ErrDoesntExists } from './errors.js'; +import { EError } from './interfaces.js'; +import { sync as copySync } from './copy.js'; +import { sync as removeSync } from './remove.js'; +import { promisify } from 'util'; +import { async as mkdirAsync, sync as dirSync } from './dir.js'; +export const validateInput = (methodName, from, to) => { + const methodSignature = methodName + '(from, to)'; + validateArgument(methodSignature, 'from', from, ['string']); + validateArgument(methodSignature, 'to', to, ['string']); +}; +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +export const sync = (from, to) => { + try { + renameSync(from, to); + } + catch (err) { + // not the same device, rename doesnt work here + if (err.code === EError.CROSS_DEVICE) { + try { + copySync(from, to); + } + catch (e) { + throw e; + } + try { + removeSync(from); + } + catch (e) { + throw e; + } + return; + } + if (err.code !== EError.NOEXISTS) { + // We can't make sense of this error. Rethrow it. + throw err; + } + else { + // Ok, source or destination path doesn't exist. + // Must do more investigation. + if (!existsSync(from)) { + throw ErrDoesntExists(from); + } + if (!existsSync(to)) { + // Some parent directory doesn't exist. Create it. + dirSync(pathUtil.dirname(to)); + // Retry the attempt + renameSync(from, to); + } + } + } +}; +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +const ensureDestinationPathExistsAsync = (to) => { + return new Promise((resolve, reject) => { + const destDir = pathUtil.dirname(to); + existsAsync(destDir) + .then(dstExists => { + if (!dstExists) { + mkdirAsync(destDir).then(resolve, reject); + } + else { + // Hah, no idea. + reject(); + } + }) + .catch(reject); + }); +}; +export const async = (from, to) => { + return new Promise((resolve, reject) => { + promisify(rename)(from, to) + .then(resolve) + .catch(err => { + if (err.code !== EError.NOEXISTS) { + // Something unknown. Rethrow original error. + reject(err); + } + else { + // Ok, source or destination path doesn't exist. + // Must do more investigation. + existsAsync(from) + .then(srcExists => { + if (!srcExists) { + reject(ErrDoesntExists(from)); + } + else { + ensureDestinationPathExistsAsync(to) + // Retry the attempt + .then(() => promisify(rename)(from, to)) + .then(resolve, reject); + } + }) + .catch(reject); + } + }); + }); +}; diff --git a/packages/fs/dist/promisify.d.ts b/packages/fs/dist/promisify.d.ts new file mode 100644 index 00000000..c12ae2cd --- /dev/null +++ b/packages/fs/dist/promisify.d.ts @@ -0,0 +1,15 @@ +export declare function promisify(f: (cb: (err: any, res: T) => void) => void, thisContext?: any): () => Promise; +export declare function promisify(f: (arg: A, cb: (err: any, res: T) => void) => void, thisContext?: any): (arg: A) => Promise; +export declare function promisify(f: (arg: A, arg2: A2, cb: (err: any, res: T) => void) => void, thisContext?: any): (arg: A, arg2: A2) => Promise; +export declare function promisify(f: (arg: A, arg2: A2, arg3: A3, cb: (err: any, res: T) => void) => void, thisContext?: any): (arg: A, arg2: A2, arg3: A3) => Promise; +export declare function promisify(f: (arg: A, arg2: A2, arg3: A3, arg4: A4, cb: (err: any, res: T) => void) => void, thisContext?: any): (arg: A, arg2: A2, arg3: A3, arg4: A4) => Promise; +export declare function promisify(f: (arg: A, arg2: A2, arg3: A3, arg4: A4, arg5: A5, cb: (err: any, res: T) => void) => void, thisContext?: any): (arg: A, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise; +export declare function map(elts: PromiseLike[]>, f: (t: T) => U | PromiseLike): Promise; +export declare function map(elts: PromiseLike, f: (t: T) => U | PromiseLike): Promise; +export declare function map(elts: PromiseLike[], f: (t: T) => U | PromiseLike): Promise; +export declare function map(elts: T[], f: (t: T) => U | PromiseLike): Promise; +export declare function _try(f: () => T): Promise; +export declare function _try(f: (arg: any) => T, arg: any): Promise; +export declare function _try(f: (arg: any, arg2: any) => T, arg: any, arg2: any): Promise; +export declare function _try(f: (arg: any, arg2: any, arg3: any) => T, arg: any, arg2: any, arg3: any): Promise; +export declare function _try(f: (arg: any, arg2: any, arg3: any, arg4: any) => T, arg: any, arg2: any, arg3: any, arg4: any): Promise; diff --git a/packages/fs/dist/promisify.js b/packages/fs/dist/promisify.js new file mode 100644 index 00000000..8b21fd21 --- /dev/null +++ b/packages/fs/dist/promisify.js @@ -0,0 +1,25 @@ +export function promisify(f, thisContext) { + return function () { + const args = Array.prototype.slice.call(arguments); + return new Promise((resolve, reject) => { + args.push((err, result) => err !== null ? reject(err) : resolve(result)); + f.apply(thisContext, args); + }); + }; +} +export function map(elts, f) { + const apply = (appElts) => Promise.all(appElts.map((elt) => typeof elt.then === 'function' ? elt.then(f) : f(elt))); + return typeof elts.then === 'function' ? elts.then(apply) : apply(elts); +} +export function _try(f, thisContext) { + const args = Array.prototype.slice.call(arguments); + return new Promise((res, rej) => { + try { + args.shift(); + res(f.apply(thisContext, args)); + } + catch (err) { + rej(err); + } + }); +} diff --git a/packages/fs/dist/read.d.ts b/packages/fs/dist/read.d.ts new file mode 100644 index 00000000..2268ea5a --- /dev/null +++ b/packages/fs/dist/read.d.ts @@ -0,0 +1,4 @@ +import type { ReadWriteDataType } from './interfaces.js'; +export declare function validateInput(methodName: string, path: string, returnAs: string): void; +export declare function sync(path: string, returnAs?: string): ReadWriteDataType | undefined; +export declare function async(path: string, returnAs?: string): Promise; diff --git a/packages/fs/dist/read.js b/packages/fs/dist/read.js new file mode 100644 index 00000000..4ad47a05 --- /dev/null +++ b/packages/fs/dist/read.js @@ -0,0 +1,89 @@ +import { readFile, readFileSync } from 'fs'; +import { json } from './imports.js'; +import { validateArgument } from './utils/validate.js'; +const Q = require('q'); +const supportedReturnAs = ['utf8', 'buffer', 'json', 'jsonWithDates']; +const promisedReadFile = Q.denodeify(readFile); +export function validateInput(methodName, path, returnAs) { + const methodSignature = methodName + '(path, returnAs)'; + validateArgument(methodSignature, 'path', path, ['string']); + validateArgument(methodSignature, 'returnAs', returnAs, ['string', 'undefined']); + if (returnAs && !supportedReturnAs.includes(returnAs)) { + throw new Error('Argument "returnAs" passed to ' + methodSignature + + ' must have one of values: ' + supportedReturnAs.join(', ')); + } +} +// Matches strings generated by Date.toJSON() +// which is called to serialize date to JSON. +const jsonDateParser = (key, value) => { + const reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}\.\d*)(?:Z|(\+|-)([\d|:]*))?$/; + if (typeof value === 'string') { + if (reISO.test(value)) { + return new Date(value); + } + } + return value; +}; +const ErrJson = (path, err) => { + const nicerError = new Error('JSON parsing failed while reading ' + + path + ' [' + err + ']'); + nicerError.originalError = err; + return nicerError; +}; +// --------------------------------------------------------- +// SYNC +// --------------------------------------------------------- +export function sync(path, returnAs) { + const retAs = returnAs || 'utf8'; + let data; + try { + data = readFileSync(path, { encoding: retAs === 'buffer' ? null : 'utf8' }); + } + catch (err) { + if (err.code === 'ENOENT') { + // If file doesn't exist return undefined instead of throwing. + return undefined; + } + // Otherwise rethrow the error + throw err; + } + try { + if (retAs === 'json') { + data = json.parse(data); + } + else if (retAs === 'jsonWithDates') { + data = json.parse(data, jsonDateParser); + } + } + catch (err) { + throw ErrJson(path, err); + } + return data; +} +// --------------------------------------------------------- +// ASYNC +// --------------------------------------------------------- +export function async(path, returnAs) { + return new Promise((resolve, reject) => { + const retAs = returnAs || 'utf8'; + promisedReadFile(path, { encoding: retAs === 'buffer' ? null : 'utf8' }) + .then((data) => { + // Make final parsing of the data before returning. + try { + if (retAs === 'json') { + resolve(json.parse(data)); + } + else if (retAs === 'jsonWithDates') { + resolve(json.parse(data, jsonDateParser)); + } + else { + resolve(data); + } + } + catch (err) { + reject(ErrJson(path, err)); + } + }) + .catch((err) => (err.code === 'ENOENT' ? resolve(null) : reject(err))); + }); +} diff --git a/packages/fs/dist/remove.d.ts b/packages/fs/dist/remove.d.ts new file mode 100644 index 00000000..de4c6faa --- /dev/null +++ b/packages/fs/dist/remove.d.ts @@ -0,0 +1,6 @@ +import { IDeleteOptions } from './interfaces.js'; +import { TDeleteResult, EResolveMode } from './interfaces.js'; +export declare function validateInput(methodName: string, path: string): void; +export declare function sync(path: string, options?: IDeleteOptions): void; +export declare function resolveConflict(path: string, resolveMode: EResolveMode): boolean; +export declare function async(path: string, options?: IDeleteOptions): Promise; diff --git a/packages/fs/dist/remove.js b/packages/fs/dist/remove.js new file mode 100644 index 00000000..2bea9ad7 --- /dev/null +++ b/packages/fs/dist/remove.js @@ -0,0 +1,330 @@ +import { validateArgument } from './utils/validate.js'; +import { sync as inspectSync } from './inspect.js'; +import { async as listAsync, sync as listSync } from './list.js'; +import * as pathUtil from 'path'; +import { rmdir, unlink, rmdirSync, unlinkSync } from 'fs'; +import { ErrNoFileOrDir } from './errors.js'; +import { ErrnoException } from './interfaces.js'; +import { create as matcher } from './utils/matcher.js'; +import { ENodeOperationStatus, EDeleteFlags, EResolve, EResolveMode } from './interfaces.js'; +import { createItem } from './inspect.js'; +import { async as iteratorAsync } from './iterator.js'; +import { ErrCantDelete } from './errors.js'; +export function validateInput(methodName, path) { + const methodSignature = methodName + '([path])'; + validateArgument(methodSignature, 'path', path, ['string', 'undefined']); +} +const parseOptions = (options, path) => { + const opts = options || {}; + const parsedOptions = {}; + parsedOptions.progress = opts.progress; + parsedOptions.conflictCallback = opts.conflictCallback; + parsedOptions.conflictSettings = opts.conflictSettings; + parsedOptions.debug = opts.debug; + parsedOptions.matching = opts.matching; + if (!opts.filter) { + if (opts.matching) { + parsedOptions.filter = matcher(path, opts.matching); + } + else { + parsedOptions.filter = () => { + return true; + }; + } + } + return parsedOptions; +}; +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +export function sync(path, options) { + const inspectedFile = inspectSync(path, { symlinks: true }); + if (inspectedFile === undefined) { + // The path already doesn't exits. Nothing to do here. + } + else if (inspectedFile.type === 'dir') { + listSync(path).forEach((filename) => { + sync(pathUtil.join(path, filename)); + }); + rmdirSync(path); + } + else if (inspectedFile.type === 'file' || inspectedFile.type === 'symlink') { + unlinkSync(path); + } + else { + throw ErrNoFileOrDir(path); + } +} +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +const rmASync = (path, options) => { + return new Promise((resolve, reject) => { + unlink(path, (err) => { + if (!err) { + resolve(); + } + else { + reject(err); + } + }); + }); +}; +const isDone = (nodes) => { + let done = true; + nodes.forEach((element) => { + if (element.status !== ENodeOperationStatus.DONE) { + done = false; + } + }); + return done; +}; +const next = (nodes) => { + for (let i = 0; i < nodes.length; i++) { + if (nodes[i].status === ENodeOperationStatus.COLLECTED) { + return nodes[i]; + } + } + return null; +}; +// handle user side setting "THROW" and non enum values (null) +const onConflict = (from, options, settings) => { + switch (settings.overwrite) { + case EResolveMode.THROW: { + throw ErrCantDelete(from); + } + case EResolveMode.OVERWRITE: + case EResolveMode.APPEND: + case EResolveMode.IF_NEWER: + case EResolveMode.ABORT: + case EResolveMode.IF_SIZE_DIFFERS: + case EResolveMode.SKIP: { + return settings.overwrite; + } + default: { + return undefined; + } + } +}; +export function resolveConflict(path, resolveMode) { + if (resolveMode === undefined) { + return true; + } + if (resolveMode === EResolveMode.SKIP) { + return false; + } + else if (resolveMode === EResolveMode.ABORT) { + return false; + } + else if (resolveMode === EResolveMode.RETRY) { + return true; + } + return false; +} +const visitor = (path, vars, item) => { + const options = vars.options; + if (!item) { + return; + } + item.status = ENodeOperationStatus.PROCESSING; + const done = () => { + item.status = ENodeOperationStatus.DONE; + if (isDone(vars.nodes)) { + return vars.resolve(vars.result); + } + else { + if (vars.nodes.length) { + const itemInner = next(vars.nodes); + if (itemInner) { + visitor(itemInner.path, vars, itemInner); + } + else { + vars.resolve(vars.result); + } + } + } + }; + if (isDone(vars.nodes)) { + return vars.resolve(vars.result); + } + vars.filesInProgress += 1; + rmASync(path, options) + .then((res) => { + done(); + }) + .catch((err) => { + if (err.code === 'EACCES' || err.code === 'EPERM' || err.code === 'EISDIR' || err.code === 'ENOTEMPTY') { + const resolved = (settings) => { + settings.error = err.code; + // feature : report + if (settings && options && options.flags && options.flags & EDeleteFlags.REPORT) { + vars.result.push({ + error: settings.error, + node: item, + resolved: settings + }); + } + if (settings) { + // if the first resolve callback returned an individual resolve settings "THIS", + // ask the user again with the same item + const always = settings.mode === EResolve.ALWAYS; + if (always) { + options.conflictSettings = settings; + } + let how = settings.overwrite; + how = onConflict(item.path, options, settings); + if (how === EResolveMode.ABORT) { + vars.abort = true; + } + if (vars.abort) { + done(); + return; + } + if (!resolveConflict(item.path, how)) { + done(); + return; + } + item.status = ENodeOperationStatus.PROCESS; + if (settings.overwrite === EResolveMode.RETRY) { + item.status = ENodeOperationStatus.COLLECTED; + visitor(path, vars, item); + } + } + }; + if (!options.conflictSettings) { + const promise = options.conflictCallback(path, createItem(path), err.code); + promise.then(resolved); + } + else { + resolved(options.conflictSettings); + } + } + }); +}; +async function collect(path, options) { + return new Promise((resolve, reject) => { + const all = []; + iteratorAsync(path, { + filter: options.filter + }).then((it) => { + let node; + while (node = it.next()) { + all.push({ + path: node.path, + item: node.item, + status: ENodeOperationStatus.COLLECTED + }); + } + resolve(all); + }).catch((err) => { + console.error('read error', err); + }); + }); +} +export async function async(path, options) { + options = parseOptions(options, path); + const onError = (err, resolve, reject, nodes) => { + if (err.code === 'EPERM' || err.code === 'EISDIR' || err.code === 'ENOTEMPTY') { + const proceed = () => { + // It's not a file, it's a directory. + // Must delete everything inside first. + listAsync(path).then((filenamesInsideDir) => { + const promises = filenamesInsideDir.map((filename) => { + return async(pathUtil.join(path, filename), options); + }); + return Promise.all(promises); + }).then(() => { + // Everything inside directory has been removed, + // it's safe now to go for the directory itself. + return rmdir(path, (err2) => { + if (err2) { + reject(err2); + } + }); + }) + .then(resolve, reject); + }; + // we have a user conflict callback, + // collect nodes and start asking + if (options.conflictCallback) { + const result = void 0; + // walker variables + const visitorArgs = { + resolve: resolve, + reject: reject, + abort: false, + filesInProgress: 0, + resolveSettings: null, + options: options, + result: result, + nodes: nodes || [] + }; + const process = () => { + visitorArgs.nodes = nodes; + if (isDone(nodes)) { + return resolve(result); + } + if (nodes.length) { + const item = next(nodes); + if (item) { + visitor(item.path, visitorArgs, item); + } + } + }; + if (!nodes) { + const _nodes = visitorArgs.nodes; + iteratorAsync(path, { + filter: options.filter + }).then((it) => { + let node; + while (node = it.next()) { + _nodes.push({ + path: node.path, + item: node.item, + status: ENodeOperationStatus.COLLECTED + }); + } + process(); + }).catch((err2) => { + console.error('read error', err2); + }); + } + else { + process(); + } + } + else { + proceed(); + } + } + else if (err.code === 'ENOENT') { + // File already doesn't exist. We're done. + resolve(); + } + else { + // Something unexpected happened. Rethrow original error. + reject(err); + } + }; + // if matching is set, its like rm somePath/*.ext + // in this case, we collect the inner matching nodes and proceed as it + // would be an error + if (options.matching) { + const nodes = await collect(path, options); + const err = new ErrnoException('dummy'); + err.code = 'ENOTEMPTY'; + return new Promise((resolve, reject) => { + onError(err, resolve, reject, nodes); + }); + } + else { + return new Promise((resolve, reject) => { + // Assume the path is a file or directory and just try to remove it. + rmASync(path, options) + .then((res) => resolve()) + .catch((err) => { + onError(err, resolve, reject); + }); + }); + } +} diff --git a/packages/fs/dist/rename.d.ts b/packages/fs/dist/rename.d.ts new file mode 100644 index 00000000..573dcb03 --- /dev/null +++ b/packages/fs/dist/rename.d.ts @@ -0,0 +1,3 @@ +export declare function validateInput(methodName: string, path: string, newName: string): void; +export declare function sync(path: string, newName: string): void; +export declare function async(path: string, newName: string): Promise; diff --git a/packages/fs/dist/rename.js b/packages/fs/dist/rename.js new file mode 100644 index 00000000..18c245f8 --- /dev/null +++ b/packages/fs/dist/rename.js @@ -0,0 +1,20 @@ +import * as pathUtil from 'path'; +import { sync as moveSync, async as moveASync } from './move.js'; +import { validateArgument } from './utils/validate.js'; +export function validateInput(methodName, path, newName) { + const methodSignature = methodName + '(path, newName)'; + validateArgument(methodSignature, 'path', path, ['string']); + validateArgument(methodSignature, 'newName', newName, ['string']); +} +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +export function sync(path, newName) { + moveSync(path, pathUtil.join(pathUtil.dirname(path), newName)); +} +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +export function async(path, newName) { + return moveASync(path, pathUtil.join(pathUtil.dirname(path), newName)); +} diff --git a/packages/fs/dist/stats.d.ts b/packages/fs/dist/stats.d.ts new file mode 100644 index 00000000..ad252d81 --- /dev/null +++ b/packages/fs/dist/stats.d.ts @@ -0,0 +1,3 @@ +import { IStatOptions } from './interfaces.js'; +export declare const sync: (path: string, options: IStatOptions) => void; +export declare const async: (path: string, options: IStatOptions) => Promise; diff --git a/packages/fs/dist/stats.js b/packages/fs/dist/stats.js new file mode 100644 index 00000000..90b60a08 --- /dev/null +++ b/packages/fs/dist/stats.js @@ -0,0 +1,4 @@ +export const sync = (path, options) => { +}; +export const async = async (path, options) => { +}; diff --git a/packages/fs/dist/streams.d.ts b/packages/fs/dist/streams.d.ts new file mode 100644 index 00000000..5021dc61 --- /dev/null +++ b/packages/fs/dist/streams.d.ts @@ -0,0 +1,2 @@ +export { createWriteStream } from 'fs'; +export { createReadStream } from 'fs'; diff --git a/packages/fs/dist/streams.js b/packages/fs/dist/streams.js new file mode 100644 index 00000000..5021dc61 --- /dev/null +++ b/packages/fs/dist/streams.js @@ -0,0 +1,2 @@ +export { createWriteStream } from 'fs'; +export { createReadStream } from 'fs'; diff --git a/packages/fs/dist/symlink.d.ts b/packages/fs/dist/symlink.d.ts new file mode 100644 index 00000000..54620946 --- /dev/null +++ b/packages/fs/dist/symlink.d.ts @@ -0,0 +1,3 @@ +export declare function validateInput(methodName: string, symlinkValue: string, path: string): void; +export declare function sync(symlinkValue: string, path: string): void; +export declare function async(symlinkValue: string, path: string): Promise; diff --git a/packages/fs/dist/symlink.js b/packages/fs/dist/symlink.js new file mode 100644 index 00000000..d157d2e5 --- /dev/null +++ b/packages/fs/dist/symlink.js @@ -0,0 +1,51 @@ +const Q = require('q'); +import * as fs from 'fs'; +import * as mkdirp from 'mkdirp'; +import * as pathUtil from "path"; +import { validateArgument } from './utils/validate.js'; +const promisedSymlink = Q.denodeify(fs.symlink); +const promisedMkdirp = Q.denodeify(mkdirp); +export function validateInput(methodName, symlinkValue, path) { + const methodSignature = methodName + '(symlinkValue, path)'; + validateArgument(methodSignature, 'symlinkValue', symlinkValue, ['string']); + validateArgument(methodSignature, 'path', path, ['string']); +} +; +// --------------------------------------------------------- +// Sync +// --------------------------------------------------------- +export function sync(symlinkValue, path) { + try { + fs.symlinkSync(symlinkValue, path); + } + catch (err) { + if (err.code === 'ENOENT') { + // Parent directories don't exist. Just create them and rety. + mkdirp.sync(pathUtil.dirname(path)); + fs.symlinkSync(symlinkValue, path); + } + else { + throw err; + } + } +} +// --------------------------------------------------------- +// Async +// --------------------------------------------------------- +export function async(symlinkValue, path) { + return new Promise((resolve, reject) => { + promisedSymlink(symlinkValue, path) + .then(resolve) + .catch((err) => { + if (err.code === 'ENOENT') { + // Parent directories don't exist. Just create them and rety. + promisedMkdirp(pathUtil.dirname(path)) + .then(() => { return promisedSymlink(symlinkValue, path); }) + .then(resolve, reject); + } + else { + reject(err); + } + }); + }); +} diff --git a/packages/fs/dist/util.d.ts b/packages/fs/dist/util.d.ts new file mode 100644 index 00000000..d2b8fba8 --- /dev/null +++ b/packages/fs/dist/util.d.ts @@ -0,0 +1 @@ +export declare const substitute: (alt: boolean, template: string, vars: Record) => any; diff --git a/packages/fs/dist/util.js b/packages/fs/dist/util.js new file mode 100644 index 00000000..a05a0bb3 --- /dev/null +++ b/packages/fs/dist/util.js @@ -0,0 +1,2 @@ +import { substitute as _substitute, substituteAlt } from "@polymech/core/strings.js"; +export const substitute = (alt, template, vars) => alt ? substituteAlt(template, vars) : _substitute(template, vars); diff --git a/packages/fs/dist/utils/dot.d.ts b/packages/fs/dist/utils/dot.d.ts new file mode 100644 index 00000000..2eea99f8 --- /dev/null +++ b/packages/fs/dist/utils/dot.d.ts @@ -0,0 +1,3 @@ +export declare const DOT_DIR_REGEX: RegExp; +export declare const isDotDir: (str: string) => boolean; +export declare function isDotFile(str: string): boolean; diff --git a/packages/fs/dist/utils/dot.js b/packages/fs/dist/utils/dot.js new file mode 100644 index 00000000..0de1aa76 --- /dev/null +++ b/packages/fs/dist/utils/dot.js @@ -0,0 +1,9 @@ +export const DOT_DIR_REGEX = /(?:^|[\\/])(\.\w+)[\\/]/; +export const isDotDir = (str) => DOT_DIR_REGEX.test(str); +export function isDotFile(str) { + if (str.charCodeAt(0) === 46 /* . */ && !str.includes('/', 1)) { + return true; + } + const last = str.lastIndexOf('/'); + return last !== -1 ? str.charCodeAt(last + 1) === 46 /* . */ : false; +} diff --git a/packages/fs/dist/utils/fs.d.ts b/packages/fs/dist/utils/fs.d.ts new file mode 100644 index 00000000..cb0ff5c3 --- /dev/null +++ b/packages/fs/dist/utils/fs.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/packages/fs/dist/utils/fs.js b/packages/fs/dist/utils/fs.js new file mode 100644 index 00000000..d16064be --- /dev/null +++ b/packages/fs/dist/utils/fs.js @@ -0,0 +1,39 @@ +// Adater module exposing all `fs` methods with promises instead of callbacks. +import * as fs from 'fs'; +const promisify = require('./promisify'); +const isCallbackMethod = (key) => { + return [ + typeof fs[key] === 'function', + !key.match(/Sync$/), + !key.match(/^[A-Z]/), + !key.match(/^create/), + !key.match(/^(un)?watch/), + ].every(Boolean); +}; +const adaptMethod = (name) => { + const original = fs[name]; + return promisify(original); +}; +const adaptAllMethods = () => { + const adapted = {}; + Object.keys(fs).forEach((key) => { + if (isCallbackMethod(key)) { + if (key === 'exists') { + // fs.exists() does not follow standard + // Node callback conventions, and has + // no error object in the callback + adapted['exists'] = () => { + throw new Error('fs.exists() is deprecated'); + }; + } + else { + adapted[key] = adaptMethod(key); + } + } + else { + adapted[key] = fs[key]; + } + }); + return adapted; +}; +module.exports = adaptAllMethods(); diff --git a/packages/fs/dist/utils/matcher.d.ts b/packages/fs/dist/utils/matcher.d.ts new file mode 100644 index 00000000..d23d6c84 --- /dev/null +++ b/packages/fs/dist/utils/matcher.d.ts @@ -0,0 +1,6 @@ +export interface IOptions { + matchBase: boolean; + nocomment: boolean; + dot: boolean; +} +export declare function create(basePath: string, patterns: string[], options?: IOptions): (absolutePath: string) => boolean; diff --git a/packages/fs/dist/utils/matcher.js b/packages/fs/dist/utils/matcher.js new file mode 100644 index 00000000..3b15e8af --- /dev/null +++ b/packages/fs/dist/utils/matcher.js @@ -0,0 +1,65 @@ +import { Minimatch } from 'minimatch'; +const patternToAbsolutePath = (basePath, pattern) => { + // All patterns without slash are left as they are, if pattern contain + // any slash we need to turn it into absolute path. + const hasSlash = (pattern.includes('/')); + const isAbsolute = /^!?\//.test(pattern); + const isNegated = /^!/.test(pattern); + let separator; + if (!isAbsolute && hasSlash) { + // Throw out meaningful characters from the beginning ("!", "./"). + pattern = pattern.replace(/^!/, '').replace(/^\.\//, ''); + if (/\/$/.test(basePath)) { + separator = ''; + } + else { + separator = '/'; + } + if (isNegated) { + return '!' + basePath + separator + pattern; + } + return basePath + separator + pattern; + } + return pattern; +}; +export function create(basePath, patterns, options) { + let matchers; + if (typeof patterns === 'string') { + patterns = [patterns]; + } + matchers = patterns.map(pattern => { + return patternToAbsolutePath(basePath, pattern); + }).map(pattern => { + return new Minimatch(pattern, options || { + matchBase: true, + nocomment: true, + dot: true + }); + }); + return function performMatch(absolutePath) { + let mode = 'matching'; + let weHaveMatch = false; + let currentMatcher; + let i; + for (i = 0; i < matchers.length; i += 1) { + currentMatcher = matchers[i]; + if (currentMatcher.negate) { + mode = 'negation'; + if (i === 0) { + // There are only negated patterns in the set, + // so make everything matching by default and + // start to reject stuff. + weHaveMatch = true; + } + } + if (mode === 'negation' && weHaveMatch && !currentMatcher.match(absolutePath)) { + // One negation match is enought to know we can reject this one. + return false; + } + if (mode === 'matching' && !weHaveMatch) { + weHaveMatch = currentMatcher.match(absolutePath); + } + } + return weHaveMatch; + }; +} diff --git a/packages/fs/dist/utils/mime_match.d.ts b/packages/fs/dist/utils/mime_match.d.ts new file mode 100644 index 00000000..64111377 --- /dev/null +++ b/packages/fs/dist/utils/mime_match.d.ts @@ -0,0 +1,10 @@ +/** + * A simple function to checker whether a target mime type matches a mime-type + * pattern (e.g. image/jpeg matches image/jpeg OR image/*). + * + * @export + * @param {string} target + * @param {string} pattern + * @returns + */ +export default function (target: string, pattern: string): boolean | ((_pattern: any) => boolean); diff --git a/packages/fs/dist/utils/mime_match.js b/packages/fs/dist/utils/mime_match.js new file mode 100644 index 00000000..eb2a6a94 --- /dev/null +++ b/packages/fs/dist/utils/mime_match.js @@ -0,0 +1,19 @@ +import { default as wildcard } from './wildcard.js'; +const reMimePartSplit = /[/+.]/; +/** + * A simple function to checker whether a target mime type matches a mime-type + * pattern (e.g. image/jpeg matches image/jpeg OR image/*). + * + * @export + * @param {string} target + * @param {string} pattern + * @returns + */ +export default function (target, pattern) { + const test = (_pattern) => { + const result = wildcard(_pattern, target, reMimePartSplit); + // ensure that we have a valid mime type (should have two parts) + return result && result.length >= 2; + }; + return pattern ? test(pattern.split(';')[0]) : test; +} diff --git a/packages/fs/dist/utils/mode.d.ts b/packages/fs/dist/utils/mode.d.ts new file mode 100644 index 00000000..66725316 --- /dev/null +++ b/packages/fs/dist/utils/mode.d.ts @@ -0,0 +1 @@ +export declare const normalizeFileMode: (mode: string | number) => string; diff --git a/packages/fs/dist/utils/mode.js b/packages/fs/dist/utils/mode.js new file mode 100644 index 00000000..dde01f91 --- /dev/null +++ b/packages/fs/dist/utils/mode.js @@ -0,0 +1,11 @@ +// Converts mode to string 3 characters long. +export const normalizeFileMode = (mode) => { + let modeAsString; + if (typeof mode === 'number') { + modeAsString = mode.toString(8); + } + else { + modeAsString = mode; + } + return modeAsString.substring(modeAsString.length - 3); +}; diff --git a/packages/fs/dist/utils/paths.d.ts b/packages/fs/dist/utils/paths.d.ts new file mode 100644 index 00000000..9656d175 --- /dev/null +++ b/packages/fs/dist/utils/paths.d.ts @@ -0,0 +1,6 @@ +export declare const substitute: (alt: boolean, template: string, vars: Record) => any; +export declare const resolve: (_path: string, alt?: boolean, vars?: Record) => any; +export declare const sep = "/"; +/** + * The native path separator depending on the OS. + */ diff --git a/packages/fs/dist/utils/paths.js b/packages/fs/dist/utils/paths.js new file mode 100644 index 00000000..86dff4cf --- /dev/null +++ b/packages/fs/dist/utils/paths.js @@ -0,0 +1,41 @@ +import { substitute as _substitute, substituteAlt as _substituteAlt } from "@polymech/core/strings.js"; +export const substitute = (alt, template, vars) => alt ? _substituteAlt(template, vars) : _substitute(template, vars); +export const resolve = (_path, alt = false, vars = {}) => substitute(alt, _path, { + ...vars +}); +export const sep = '/'; +/** + * The native path separator depending on the OS. + */ +/* +export const nativeSep = isWindows ? '\\' : '/'; + +export function relative(from: string, to: string): string { + // ignore trailing slashes + const originalNormalizedFrom = rtrim(normalize(from), sep); + const originalNormalizedTo = rtrim(normalize(to), sep); + + // we're assuming here that any non=linux OS is case insensitive + // so we must compare each part in its lowercase form + const normalizedFrom = isLinux ? originalNormalizedFrom : originalNormalizedFrom.toLowerCase(); + const normalizedTo = isLinux ? originalNormalizedTo : originalNormalizedTo.toLowerCase(); + + const fromParts = normalizedFrom.split(sep); + const toParts = normalizedTo.split(sep); + + let i = 0, max = Math.min(fromParts.length, toParts.length); + + for (; i < max; i++) { + if (fromParts[i] !== toParts[i]) { + break; + } + } + + const result = [ + ...fill(fromParts.length - i, () => '..'), + ...originalNormalizedTo.split(sep).slice(i) + ]; + + return result.join(sep); +} +*/ diff --git a/packages/fs/dist/utils/platform.d.ts b/packages/fs/dist/utils/platform.d.ts new file mode 100644 index 00000000..2906c988 --- /dev/null +++ b/packages/fs/dist/utils/platform.d.ts @@ -0,0 +1,15 @@ +export declare enum Platform { + Web = 0, + Mac = 1, + Linux = 2, + Windows = 3 +} +export declare let _platform: Platform; +export declare const isWindows: boolean; +export declare const isMacintosh: boolean; +export declare const isLinux: boolean; +export declare const isRootUser: boolean; +export declare const isNative: boolean; +export declare const isWeb = false; +export declare const isQunit = false; +export declare const platform: Platform; diff --git a/packages/fs/dist/utils/platform.js b/packages/fs/dist/utils/platform.js new file mode 100644 index 00000000..f75f2770 --- /dev/null +++ b/packages/fs/dist/utils/platform.js @@ -0,0 +1,42 @@ +export var Platform; +(function (Platform) { + Platform[Platform["Web"] = 0] = "Web"; + Platform[Platform["Mac"] = 1] = "Mac"; + Platform[Platform["Linux"] = 2] = "Linux"; + Platform[Platform["Windows"] = 3] = "Windows"; +})(Platform || (Platform = {})); +let _isWindows = false; +let _isMacintosh = false; +let _isLinux = false; +let _isRootUser = false; +let _isNative = false; +let _isWeb = false; +let _isQunit = false; +export let _platform = Platform.Web; +// OS detection +if (typeof process === 'object') { + _isWindows = (process.platform === 'win32'); + _isMacintosh = (process.platform === 'darwin'); + _isLinux = (process.platform === 'linux'); + _isRootUser = !_isWindows && (process.getuid() === 0); + _isNative = true; +} +if (_isNative) { + if (_isMacintosh) { + _platform = Platform.Mac; + } + else if (_isWindows) { + _platform = Platform.Windows; + } + else if (_isLinux) { + _platform = Platform.Linux; + } +} +export const isWindows = _isWindows; +export const isMacintosh = _isMacintosh; +export const isLinux = _isLinux; +export const isRootUser = _isRootUser; +export const isNative = _isNative; +export const isWeb = _isWeb; +export const isQunit = _isQunit; +export const platform = _platform; diff --git a/packages/fs/dist/utils/stats.d.ts b/packages/fs/dist/utils/stats.d.ts new file mode 100644 index 00000000..93c97cd9 --- /dev/null +++ b/packages/fs/dist/utils/stats.d.ts @@ -0,0 +1,18 @@ +/** + * Returns an object containing the size of the folder and a list of errors encountered while traversing the folder. + * + * If any errors are returned, the returned folder size is likely smaller than the real folder size. + * + * @param {string} itemPath - Path of the folder. + * @param {object} [options] - Options. + * @param {boolean} [options.bigint] - Should the folder size be returned as a BigInt instead of a Number. + * @param {object} [options.ignore] - If a file's path matches this regex object, its size is not counted. + * @param {object} [options.fs] - The filesystem that should be used. Uses node fs by default. + * + * @returns {Promise<{size: number | bigint, errors: Array | null}>} - An object containing the size of the folder in bytes and a list of encountered errors. + */ +export declare const getFolderSize: { + (itemPath: any, options: any): Promise; + loose(itemPath: any, options: any): Promise; + strict(itemPath: any, options: any): Promise; +}; diff --git a/packages/fs/dist/utils/stats.js b/packages/fs/dist/utils/stats.js new file mode 100644 index 00000000..e12e435f --- /dev/null +++ b/packages/fs/dist/utils/stats.js @@ -0,0 +1,85 @@ +import { join as joinPaths } from 'node:path'; +/** + * Returns an object containing the size of the folder and a list of errors encountered while traversing the folder. + * + * If any errors are returned, the returned folder size is likely smaller than the real folder size. + * + * @param {string} itemPath - Path of the folder. + * @param {object} [options] - Options. + * @param {boolean} [options.bigint] - Should the folder size be returned as a BigInt instead of a Number. + * @param {object} [options.ignore] - If a file's path matches this regex object, its size is not counted. + * @param {object} [options.fs] - The filesystem that should be used. Uses node fs by default. + * + * @returns {Promise<{size: number | bigint, errors: Array | null}>} - An object containing the size of the folder in bytes and a list of encountered errors. + */ +export const getFolderSize = async (itemPath, options) => await core(itemPath, options, { errors: true }); +/** + * Returns the size of the folder. If any errors are encountered while traversing the folder, they are silently ignored. + * + * The returned folder size might be smaller than the real folder size. It is impossible to know for sure, since errors are ignored. + * + * @param {string} itemPath - Path of the folder. + * @param {object} [options] - Options. + * @param {boolean} [options.bigint] - Should the folder size be returned as a BigInt instead of a Number. + * @param {object} [options.ignore] - If a file's path matches this regex object, its size is not counted. + * @param {object} [options.fs] - The filesystem that should be used. Uses node fs by default. + * + * @returns {Promise} - The size of the folder in bytes. + */ +getFolderSize.loose = async (itemPath, options) => await core(itemPath, options); +/** + * Returns the size of the folder. If any errors are encountered while traversing the folder, this method will throw an error. + * + * Because errors will otherwise make this method fail, the returned folder size will always be accurate. + * + * @param {string} itemPath - Path of the folder. + * @param {object} [options] - Options. + * @param {boolean} [options.bigint] - Should the folder size be returned as a BigInt instead of a Number. + * @param {object} [options.ignore] - If a file's path matches this regex object, its size is not counted. + * @param {object} [options.fs] - The filesystem that should be used. Uses node fs by default. + * + * @returns {Promise} - The size of the folder in bytes. + */ +getFolderSize.strict = async (itemPath, options) => await core(itemPath, options, { strict: true }); +async function core(rootItemPath, options = {}, returnType = {}) { + const fs = options.fs || await import('fs/promises'); + const fileSizes = new Map(); + const errors = []; + await processItem(rootItemPath); + async function processItem(itemPath) { + if (options.ignore?.test(itemPath)) + return; + const stats = returnType.strict ? await fs.lstat(itemPath, { bigint: true }) : await fs.lstat(itemPath, { bigint: true }).catch(error => errors.push(error)); + if (typeof stats !== 'object') + return; + fileSizes.set(stats.ino, stats.size); + if (stats.isDirectory()) { + const directoryItems = returnType.strict ? await fs.readdir(itemPath) : await fs.readdir(itemPath).catch(error => errors.push(error)); + if (typeof directoryItems !== 'object') + return; + await Promise.all(directoryItems.map(directoryItem => processItem(joinPaths(itemPath, directoryItem)))); + } + } + let folderSize = Array.from(fileSizes.values()).reduce((total, fileSize) => total + fileSize, 0n); + if (!options.bigint) { + if (folderSize > BigInt(Number.MAX_SAFE_INTEGER)) { + const error = new RangeError('The folder size is too large to return as a Number. You can instruct this package to return a BigInt instead.'); + if (returnType.strict) { + throw error; + } + else { + errors.push(error); + } + } + folderSize = Number(folderSize); + } + if (returnType.errors) { + return { + size: folderSize, + errors: errors.length > 0 ? errors : null, + }; + } + else { + return folderSize; + } +} diff --git a/packages/fs/dist/utils/strings.d.ts b/packages/fs/dist/utils/strings.d.ts new file mode 100644 index 00000000..a2614c89 --- /dev/null +++ b/packages/fs/dist/utils/strings.d.ts @@ -0,0 +1,2 @@ +export declare let canNormalize: boolean; +export declare const normalizeNFC: (str: string) => string; diff --git a/packages/fs/dist/utils/strings.js b/packages/fs/dist/utils/strings.js new file mode 100644 index 00000000..867b2854 --- /dev/null +++ b/packages/fs/dist/utils/strings.js @@ -0,0 +1,15 @@ +export let canNormalize = typeof (''.normalize) === 'function'; +const nonAsciiCharactersPattern = /[^\u0000-\u0080]/; +export const normalizeNFC = (str) => { + if (!canNormalize || !str) { + return str; + } + let res; + if (nonAsciiCharactersPattern.test(str)) { + res = str.normalize('NFC'); + } + else { + res = str; + } + return res; +}; diff --git a/packages/fs/dist/utils/tree_walker.d.ts b/packages/fs/dist/utils/tree_walker.d.ts new file mode 100644 index 00000000..7931c78b --- /dev/null +++ b/packages/fs/dist/utils/tree_walker.d.ts @@ -0,0 +1,9 @@ +import { Readable } from 'node:stream'; +import { IInspectOptions, INode } from '../interfaces.js'; +export interface IOptions { + inspectOptions: IInspectOptions; + maxLevelsDeep?: number; + user?: any; +} +export declare function sync(path: string, options: IOptions, callback: (path: string, item: INode) => void, currentLevel?: number): void; +export declare function stream(path: string, options: IOptions): Readable; diff --git a/packages/fs/dist/utils/tree_walker.js b/packages/fs/dist/utils/tree_walker.js new file mode 100644 index 00000000..1abe57a1 --- /dev/null +++ b/packages/fs/dist/utils/tree_walker.js @@ -0,0 +1,100 @@ +import { Readable } from 'node:stream'; +import * as pathUtil from 'node:path'; +import { sync as inspectSync, async as inspectASync } from '../inspect.js'; +import { ENodeType } from '../interfaces.js'; +import { sync as listSync, async as listASync } from '../list.js'; +// --------------------------------------------------------- +// SYNC +// --------------------------------------------------------- +export function sync(path, options, callback, currentLevel) { + const item = inspectSync(path, options.inspectOptions); + if (options.maxLevelsDeep === undefined) { + options.maxLevelsDeep = Infinity; + } + if (currentLevel === undefined) { + currentLevel = 0; + } + let children = []; + const hasChildren = item && item.type === ENodeType.DIR && currentLevel < options.maxLevelsDeep; + if (hasChildren) { + children = listSync(path); + } + callback(path, item); + if (hasChildren) { + children.forEach(child => sync(path + pathUtil.sep + child, options, callback, currentLevel + 1)); + } +} +export function stream(path, options) { + const rs = new Readable({ objectMode: true }); + let nextTreeNode = { + path: path, + parent: undefined, + level: 0 + }; + let running = false; + let readSome; + const error = (err) => { + rs.emit('error', err); + }; + const findNextUnprocessedNode = (node) => { + if (node.nextSibling) { + return node.nextSibling; + } + else if (node.parent) { + return findNextUnprocessedNode(node.parent); + } + return undefined; + }; + const pushAndContinueMaybe = (data) => { + const theyWantMore = rs.push(data); + running = false; + if (!nextTreeNode) { + // Previous was the last node. The job is done. + rs.push(null); + } + else if (theyWantMore) { + readSome(); + } + }; + if (options.maxLevelsDeep === undefined) { + options.maxLevelsDeep = Infinity; + } + readSome = () => { + const theNode = nextTreeNode; + running = true; + inspectASync(theNode.path, options.inspectOptions) + .then((inspected) => { + theNode.inspected = inspected; + if (inspected && inspected.type === ENodeType.DIR && theNode.level < options.maxLevelsDeep) { + listASync(theNode.path) + .then((childrenNames) => { + const children = childrenNames.map((name) => { + return { + name: name, + path: theNode.path + pathUtil.sep + name, + parent: theNode, + level: theNode.level + 1 + }; + }); + children.forEach((child, index) => { + child.nextSibling = children[index + 1]; + }); + nextTreeNode = children[0] || findNextUnprocessedNode(theNode); + pushAndContinueMaybe({ path: theNode.path, item: inspected }); + }) + .catch(error); + } + else { + nextTreeNode = findNextUnprocessedNode(theNode); + pushAndContinueMaybe({ path: theNode.path, item: inspected }); + } + }) + .catch(error); + }; + rs['_read'] = () => { + if (!running) { + readSome(); + } + }; + return rs; +} diff --git a/packages/fs/dist/utils/validate.d.ts b/packages/fs/dist/utils/validate.d.ts new file mode 100644 index 00000000..22eedb11 --- /dev/null +++ b/packages/fs/dist/utils/validate.d.ts @@ -0,0 +1,2 @@ +export declare const validateArgument: (methodName: any, argumentName: any, argumentValue: any, argumentMustBe: any) => void; +export declare const validateOptions: (methodName: any, optionsObjName: any, obj: any, allowedOptions: any) => void; diff --git a/packages/fs/dist/utils/validate.js b/packages/fs/dist/utils/validate.js new file mode 100644 index 00000000..b1000974 --- /dev/null +++ b/packages/fs/dist/utils/validate.js @@ -0,0 +1,96 @@ +const prettyPrintTypes = (types) => { + const addArticle = (str) => { + const vowels = ["a", "e", "i", "o", "u"]; + if (vowels.includes(str[0])) { + return `an ${str}`; + } + return `a ${str}`; + }; + return types.map(addArticle).join(" or "); +}; +const isArrayOfNotation = function (typeDefinition) { + return typeDefinition.includes('array of '); +}; +const extractTypeFromArrayOfNotation = function (typeDefinition) { + // The notation is e.g. 'array of string' + return typeDefinition.split(' of ')[1]; +}; +const isValidTypeDefinition = (typeStr) => { + if (isArrayOfNotation(typeStr)) { + return isValidTypeDefinition(extractTypeFromArrayOfNotation(typeStr)); + } + return [ + "string", + "number", + "boolean", + "array", + "object", + "buffer", + "null", + "undefined", + "function", + ].some((validType) => validType === typeStr); +}; +const detectType = function (value) { + if (value === null) { + return 'null'; + } + if (Array.isArray(value)) { + return 'array'; + } + if (Buffer.isBuffer(value)) { + return 'buffer'; + } + return typeof value; +}; +const onlyUniqueValuesInArrayFilter = function (value, index, self) { + return self.indexOf(value) === index; +}; +const detectTypeDeep = (value) => { + let type = detectType(value); + let typesInArray; + if (type === "array") { + typesInArray = value + .map((element) => { + return detectType(element); + }) + .filter(onlyUniqueValuesInArrayFilter); + type += ` of ${typesInArray.join(", ")}`; + } + return type; +}; +const validateArray = (argumentValue, typeToCheck) => { + const allowedTypeInArray = extractTypeFromArrayOfNotation(typeToCheck); + if (detectType(argumentValue) !== "array") { + return false; + } + return argumentValue.every((element) => detectType(element) === allowedTypeInArray); +}; +export const validateArgument = (methodName, argumentName, argumentValue, argumentMustBe) => { + const isOneOfAllowedTypes = argumentMustBe.some((type) => { + if (!isValidTypeDefinition(type)) { + throw new Error(`Unknown type "${type}"`); + } + if (isArrayOfNotation(type)) { + return validateArray(argumentValue, type); + } + return type === detectType(argumentValue); + }); + if (!isOneOfAllowedTypes) { + throw new Error(`Argument "${argumentName}" passed to ${methodName} must be ${prettyPrintTypes(argumentMustBe)}. Received ${detectTypeDeep(argumentValue)}`); + } +}; +export const validateOptions = (methodName, optionsObjName, obj, allowedOptions) => { + if (obj !== undefined) { + validateArgument(methodName, optionsObjName, obj, ["object"]); + Object.keys(obj).forEach((key) => { + const argName = `${optionsObjName}.${key}`; + if (allowedOptions[key] !== undefined) { + validateArgument(methodName, argName, obj[key], allowedOptions[key]); + } + else { + throw new Error(`Unknown argument "${argName}" passed to ${methodName}`); + } + }); + } +}; diff --git a/packages/fs/dist/utils/wildcard.d.ts b/packages/fs/dist/utils/wildcard.d.ts new file mode 100644 index 00000000..c88df14c --- /dev/null +++ b/packages/fs/dist/utils/wildcard.d.ts @@ -0,0 +1 @@ +export default function (text: string, test: string, separator?: string | RegExp): any; diff --git a/packages/fs/dist/utils/wildcard.js b/packages/fs/dist/utils/wildcard.js new file mode 100644 index 00000000..b4ac1497 --- /dev/null +++ b/packages/fs/dist/utils/wildcard.js @@ -0,0 +1,59 @@ +function WildcardMatcher(text, separator) { + this.text = text = text || ''; + this.hasWild = ~text.indexOf('*'); + this.separator = separator; + this.parts = text.split(separator); +} +WildcardMatcher.prototype.match = (input) => { + let matches = true; + var thiz = this; + const parts = thiz.parts || []; + let ii; + const partsCount = parts.length; + let testParts; + if (typeof input === 'string' || input instanceof String) { + if (!thiz.hasWild && thiz.text !== input) { + matches = false; + } + else { + testParts = (input || '').split(thiz.separator); + for (ii = 0; matches && ii < partsCount; ii++) { + if (parts[ii] === '*') { + continue; + } + else if (ii < testParts.length) { + matches = parts[ii] === testParts[ii]; + } + else { + matches = false; + } + } + // If matches, then return the component parts + matches = matches && testParts; + } + } + else if (typeof input.splice === 'function') { + matches = []; + for (ii = input.length; ii--;) { + if (thiz.match(input[ii])) { + matches[matches.length] = input[ii]; + } + } + } + else if (typeof input === 'object') { + matches = {}; + for (const key in input) { + if (thiz.match(key)) { + matches[key] = input[key]; + } + } + } + return matches; +}; +export default function (text, test, separator) { + const matcher = new WildcardMatcher(text, separator || /[/.]/); + if (typeof test !== 'undefined') { + return matcher.match(test); + } + return matcher; +} diff --git a/packages/fs/dist/write.d.ts b/packages/fs/dist/write.d.ts new file mode 100644 index 00000000..054c7898 --- /dev/null +++ b/packages/fs/dist/write.d.ts @@ -0,0 +1,4 @@ +import { IWriteOptions, ReadWriteDataType } from './interfaces.js'; +export declare function validateInput(methodName: string, path: string, data: ReadWriteDataType, options: IWriteOptions): void; +export declare function sync(path: string, data: ReadWriteDataType, options?: IWriteOptions): void; +export declare function async(path: string, data: ReadWriteDataType, options?: IWriteOptions): Promise; diff --git a/packages/fs/dist/write.js b/packages/fs/dist/write.js new file mode 100644 index 00000000..402e3989 --- /dev/null +++ b/packages/fs/dist/write.js @@ -0,0 +1,85 @@ +import * as pathUtil from 'path'; +import * as fs from 'fs'; +import { writeFileSync } from 'fs'; +const Q = require('q'); +import * as mkdirp from 'mkdirp'; +import { json, file } from './imports.js'; +import { validateArgument, validateOptions } from './utils/validate.js'; +// Temporary file extensions used for atomic file overwriting. +const newExt = '.__new__'; +export function validateInput(methodName, path, data, options) { + const methodSignature = methodName + '(path, data, [options])'; + validateArgument(methodSignature, 'path', path, ['string']); + validateArgument(methodSignature, 'data', data, ['string', 'buffer', 'object', 'array']); + validateOptions(methodSignature, 'options', options, { + atomic: ['boolean'], + jsonIndent: ['number'], + progress: ['function'] + }); +} +const toJson = (data, jsonIndent) => { + if (typeof data === 'object' + && !Buffer.isBuffer(data) + && data !== null) { + return json.serialize(data, null, typeof jsonIndent !== 'number' ? 2 : jsonIndent); + } + return data; +}; +// --------------------------------------------------------- +// SYNC +// --------------------------------------------------------- +const _writeFileSync = (path, data, options) => { + try { + writeFileSync(path, data, options); + } + catch (err) { + if (err.code === 'ENOENT') { + // Means parent directory doesn't exist, so create it and try again. + mkdirp.sync(pathUtil.dirname(path)); + fs.writeFileSync(path, data, options); + } + else { + throw err; + } + } +}; +const writeAtomicSync = (path, data, options) => { + return file.write_atomic(path + newExt, data, options, function () { }); +}; +export function sync(path, data, options) { + const opts = options || {}; + const processedData = toJson(data, opts.jsonIndent); + const writeStrategy = opts.atomic ? writeAtomicSync : _writeFileSync; + writeStrategy(path, processedData, { mode: opts.mode }); +} +// --------------------------------------------------------- +// ASYNC +// --------------------------------------------------------- +const promisedWriteFile = Q.denodeify(fs.writeFile); +const promisedMkdirp = Q.denodeify(mkdirp); +const promisedAtomic = Q.denodeify(writeAtomicSync); +function writeFileAsync(path, data, options) { + return new Promise((resolve, reject) => { + promisedWriteFile(path, data, options) + .then(resolve) + .catch((err) => { + // First attempt to write a file ended with error. + // Check if this is not due to nonexistent parent directory. + if (err.code === 'ENOENT') { + // Parent directory doesn't exist, so create it and try again. + promisedMkdirp(pathUtil.dirname(path)) + .then(() => promisedWriteFile(path, data, options)) + .then(resolve, reject); + } + else { + // Nope, some other error, throw it. + reject(err); + } + }); + }); +} +export function async(path, data, options) { + const opts = options || {}; + const processedData = toJson(data, opts.jsonIndent); + return (opts.atomic ? promisedAtomic : writeFileAsync)(path, processedData, { mode: opts.mode }); +} diff --git a/packages/fs/package.json b/packages/fs/package.json index 836d032a..56ae71be 100644 --- a/packages/fs/package.json +++ b/packages/fs/package.json @@ -6,6 +6,20 @@ "publishConfig": { "access": "public" }, + "exports": { + "./write": { + "import": "./dist/write.js", + "require": "./dist/write.cjs" + }, + "./read": { + "import": "./dist/read.js", + "require": "./dist/read.cjs" + }, + "./exists": { + "import": "./dist/exists.js", + "require": "./dist/exists.cjs" + } + }, "dependencies": { "@polymech/core": "workspace:*", "denodeify": "^1.2.1",