From 78b767c2b1625186e17131761a0edbac25d21850 Mon Sep 17 00:00:00 2001 From: Sebastian Lorenz Date: Tue, 16 Apr 2024 11:28:46 +0200 Subject: [PATCH] Rename `ReadonlyArray` and `ReadonlyRecord` modules (#2529) --- .changeset/many-olives-sneeze.md | 20 + packages/cli/README.md | 26 +- packages/cli/examples/minigit.ts | 14 +- packages/cli/examples/naval-fate/store.ts | 20 +- packages/cli/src/Args.ts | 2 +- packages/cli/src/CommandDescriptor.ts | 2 +- packages/cli/src/HelpDoc.ts | 2 +- packages/cli/src/Options.ts | 2 +- packages/cli/src/internal/args.ts | 66 +-- packages/cli/src/internal/cliApp.ts | 48 +- packages/cli/src/internal/command.ts | 18 +- .../cli/src/internal/commandDescriptor.ts | 280 +++++----- packages/cli/src/internal/helpDoc.ts | 12 +- packages/cli/src/internal/helpDoc/span.ts | 6 +- packages/cli/src/internal/options.ts | 263 +++++---- packages/cli/src/internal/primitive.ts | 48 +- .../cli/src/internal/prompt/ansi-utils.ts | 6 +- packages/cli/src/internal/prompt/confirm.ts | 6 +- packages/cli/src/internal/prompt/date.ts | 22 +- packages/cli/src/internal/prompt/number.ts | 10 +- packages/cli/src/internal/prompt/select.ts | 8 +- packages/cli/src/internal/prompt/text.ts | 10 +- packages/cli/src/internal/prompt/toggle.ts | 6 +- packages/cli/src/internal/usage.ts | 50 +- packages/cli/test/Args.test.ts | 48 +- packages/cli/test/CliApp.test.ts | 4 +- packages/cli/test/CommandDescriptor.test.ts | 100 ++-- packages/cli/test/Options.test.ts | 102 ++-- packages/cli/test/Primitive.test.ts | 10 +- packages/cli/test/Wizard.test.ts | 6 +- packages/cli/test/services/MockConsole.ts | 8 +- packages/cli/test/services/MockTerminal.ts | 4 +- .../dtslint/{ReadonlyArray.ts => Array.ts} | 502 +++++++++--------- packages/effect/dtslint/Either.ts | 6 +- .../dtslint/{ReadonlyRecord.ts => Record.ts} | 308 +++++------ packages/effect/dtslint/Struct.ts | 4 +- .../effect/src/{ReadonlyArray.ts => Array.ts} | 70 ++- packages/effect/src/Brand.ts | 6 +- packages/effect/src/Chunk.ts | 4 +- packages/effect/src/Cron.ts | 34 +- packages/effect/src/Effect.ts | 2 +- packages/effect/src/FiberRefs.ts | 2 +- packages/effect/src/Iterable.ts | 10 +- packages/effect/src/List.ts | 6 +- packages/effect/src/MutableHashMap.ts | 2 +- .../src/{ReadonlyRecord.ts => Record.ts} | 56 +- packages/effect/src/String.ts | 4 +- packages/effect/src/TestAnnotations.ts | 2 +- packages/effect/src/index.ts | 16 +- .../internal/{readonlyArray.ts => array.ts} | 2 +- packages/effect/src/internal/cause.ts | 6 +- packages/effect/src/internal/configError.ts | 2 +- .../effect/src/internal/configProvider.ts | 101 ++-- .../src/internal/configProvider/pathPatch.ts | 2 +- packages/effect/src/internal/core-effect.ts | 18 +- packages/effect/src/internal/core.ts | 24 +- packages/effect/src/internal/dataSource.ts | 2 +- .../src/internal/differ/readonlyArrayPatch.ts | 12 +- packages/effect/src/internal/fiberRefs.ts | 2 +- .../effect/src/internal/fiberRefs/patch.ts | 2 +- packages/effect/src/internal/fiberRuntime.ts | 4 +- packages/effect/src/internal/metric.ts | 8 +- .../effect/src/internal/metric/boundaries.ts | 10 +- packages/effect/src/internal/metric/hook.ts | 34 +- packages/effect/src/internal/metric/key.ts | 6 +- packages/effect/src/internal/metric/state.ts | 10 +- packages/effect/src/internal/queue.ts | 12 +- .../src/internal/redBlackTree/iterator.ts | 4 +- packages/effect/src/internal/runtime.ts | 2 +- packages/effect/src/internal/secret.ts | 4 +- packages/effect/src/internal/sink.ts | 4 +- packages/effect/src/internal/stm/stm.ts | 2 +- packages/effect/src/internal/stm/tMap.ts | 2 +- .../effect/src/internal/stm/tPriorityQueue.ts | 22 +- packages/effect/src/internal/stm/tPubSub.ts | 2 +- packages/effect/src/internal/stm/tQueue.ts | 2 +- packages/effect/src/internal/stm/tSet.ts | 2 +- .../{ReadonlyArray.test.ts => Array.test.ts} | 2 +- packages/effect/test/Channel/mapping.test.ts | 18 +- packages/effect/test/Channel/reading.test.ts | 25 +- packages/effect/test/Chunk.test.ts | 2 +- packages/effect/test/Differ.test.ts | 2 +- .../effect/test/Effect/finalization.test.ts | 14 +- .../effect/test/Effect/interruption.test.ts | 6 +- .../effect/test/Effect/query-nested.test.ts | 8 +- packages/effect/test/Effect/query.test.ts | 8 +- .../effect/test/Effect/traversing.test.ts | 116 ++-- packages/effect/test/Fiber.test.ts | 12 +- packages/effect/test/FiberMap.test.ts | 6 +- packages/effect/test/FiberSet.test.ts | 4 +- packages/effect/test/KeyedPool.test.ts | 6 +- packages/effect/test/List.test.ts | 8 +- packages/effect/test/Metric.test.ts | 13 +- packages/effect/test/Order.test.ts | 2 +- packages/effect/test/PubSub.test.ts | 102 ++-- packages/effect/test/Queue.test.ts | 88 +-- packages/effect/test/Random.test.ts | 6 +- packages/effect/test/RateLimiter.test.ts | 44 +- ...{ReadonlyRecord.test.ts => Record.test.ts} | 2 +- packages/effect/test/Schedule.test.ts | 88 +-- packages/effect/test/ScopedCache.test.ts | 66 +-- .../effect/test/Stream/environment.test.ts | 24 +- packages/effect/test/Stream/scanning.test.ts | 8 +- packages/effect/test/TMap.test.ts | 67 ++- packages/effect/test/TPriorityQueue.test.ts | 2 +- packages/effect/test/TPubSub.test.ts | 2 +- .../experimental/examples/redis/resolver.ts | 4 +- packages/experimental/src/Machine.ts | 4 +- packages/experimental/src/Persistence/Lmdb.ts | 4 +- packages/experimental/src/RequestResolver.ts | 10 +- .../experimental/test/RequestResolver.test.ts | 16 +- .../opentelemetry/src/internal/metrics.ts | 8 +- .../platform-bun/src/internal/http/server.ts | 2 +- .../test/CommandExecutor.test.ts | 8 +- .../platform-node-shared/test/Stream.test.ts | 4 +- .../platform-node/src/internal/http/server.ts | 2 +- packages/platform/src/Command.ts | 2 +- packages/platform/src/Http/Cookies.ts | 18 +- packages/platform/src/Http/Headers.ts | 24 +- packages/platform/src/Http/ServerRequest.ts | 2 +- packages/platform/src/Http/UrlParams.ts | 28 +- .../platform/src/PlatformConfigProvider.ts | 4 +- packages/platform/src/internal/command.ts | 2 +- .../platform/src/internal/http/multiplex.ts | 4 +- .../src/internal/http/serverRequest.ts | 2 +- packages/platform/src/internal/worker.ts | 4 +- packages/printer-ansi/src/internal/ansi.ts | 50 +- packages/printer/README.md | 11 +- packages/printer/examples/main.ts | 8 +- packages/printer/src/internal/doc.ts | 24 +- packages/printer/src/internal/docTree.ts | 24 +- packages/printer/test/docTree.test.ts | 4 +- packages/rpc-http/examples/router.ts | 4 +- packages/rpc/src/Resolver.ts | 4 +- packages/rpc/src/Rpc.ts | 4 +- packages/rpc/test/Router.test.ts | 10 +- packages/schema/benchmark/union.ts | 2 +- packages/schema/src/AST.ts | 40 +- packages/schema/src/Arbitrary.ts | 4 +- packages/schema/src/ArrayFormatter.ts | 8 +- packages/schema/src/Equivalence.ts | 4 +- packages/schema/src/JSONSchema.ts | 8 +- packages/schema/src/ParseResult.ts | 28 +- packages/schema/src/Pretty.ts | 6 +- packages/schema/src/Schema.ts | 55 +- .../sql-sqlite-node/test/Resolver.test.ts | 4 +- packages/sql/src/Migrator.ts | 14 +- .../src/data/{ReadonlyArray.ts => Array.ts} | 64 +-- packages/typeclass/src/data/Identity.ts | 2 +- .../src/data/{ReadonlyRecord.ts => Record.ts} | 70 ++- packages/typeclass/test/Bicovariant.test.ts | 4 +- packages/typeclass/test/Covariant.test.ts | 4 +- packages/typeclass/test/Filterable.test.ts | 14 +- packages/typeclass/test/Foldable.test.ts | 12 +- packages/typeclass/test/Of.test.ts | 2 +- packages/typeclass/test/SemiProduct.test.ts | 14 +- packages/typeclass/test/Traversable.test.ts | 10 +- .../test/TraversableFilterable.test.ts | 16 +- .../{ReadonlyArray.test.ts => Array.test.ts} | 6 +- packages/typeclass/test/data/Option.test.ts | 2 +- ...{ReadonlyRecord.test.ts => Record.test.ts} | 10 +- 161 files changed, 2020 insertions(+), 1995 deletions(-) create mode 100644 .changeset/many-olives-sneeze.md rename packages/effect/dtslint/{ReadonlyArray.ts => Array.ts} (64%) rename packages/effect/dtslint/{ReadonlyRecord.ts => Record.ts} (65%) rename packages/effect/src/{ReadonlyArray.ts => Array.ts} (97%) rename packages/effect/src/{ReadonlyRecord.ts => Record.ts} (96%) rename packages/effect/src/internal/{readonlyArray.ts => array.ts} (72%) rename packages/effect/test/{ReadonlyArray.test.ts => Array.test.ts} (99%) rename packages/effect/test/{ReadonlyRecord.test.ts => Record.test.ts} (99%) rename packages/typeclass/src/data/{ReadonlyArray.ts => Array.ts} (68%) rename packages/typeclass/src/data/{ReadonlyRecord.ts => Record.ts} (62%) rename packages/typeclass/test/data/{ReadonlyArray.test.ts => Array.test.ts} (62%) rename packages/typeclass/test/data/{ReadonlyRecord.test.ts => Record.test.ts} (74%) diff --git a/.changeset/many-olives-sneeze.md b/.changeset/many-olives-sneeze.md new file mode 100644 index 0000000000..5b4559923c --- /dev/null +++ b/.changeset/many-olives-sneeze.md @@ -0,0 +1,20 @@ +--- +"@effect/typeclass": minor +"effect": minor +"@effect/platform-node-shared": patch +"@effect/sql-sqlite-node": patch +"@effect/opentelemetry": patch +"@effect/platform-node": patch +"@effect/experimental": patch +"@effect/platform-bun": patch +"@effect/printer-ansi": patch +"@effect/platform": patch +"@effect/rpc-http": patch +"@effect/printer": patch +"@effect/schema": patch +"@effect/cli": patch +"@effect/rpc": patch +"@effect/sql": patch +--- + +Renamed `ReadonlyArray` and `ReadonlyRecord` modules for better discoverability. diff --git a/packages/cli/README.md b/packages/cli/README.md index c7941d5308..548953d76f 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -151,7 +151,7 @@ Let's continue with our `minigit` example and and create the `add` and `clone` s ```ts import { Args, Command, Options } from "@effect/cli" -import { Console, Option, ReadonlyArray } from "effect" +import { Console, Option, Array } from "effect" // minigit [--version] [-h | --help] [-c =] const configs = Options.keyValueMap("c").pipe(Options.optional) @@ -170,9 +170,9 @@ const minigit = Command.make("minigit", { configs }, ({ configs }) => const pathspec = Args.text({ name: "pathspec" }).pipe(Args.repeated) const verbose = Options.boolean("verbose").pipe(Options.withAlias("v")) const minigitAdd = Command.make("add", { pathspec, verbose }, ({ pathspec, verbose }) => { - const paths = ReadonlyArray.match(pathspec, { + const paths = Array.match(pathspec, { onEmpty: () => "", - onNonEmpty: (paths) => ` ${ReadonlyArray.join(paths, " ")}` + onNonEmpty: (paths) => ` ${Array.join(paths, " ")}` }) return Console.log(`Running 'minigit add${paths}' with '--verbose ${verbose}'`) }) @@ -184,16 +184,16 @@ const depth = Options.integer('depth').pipe(Options.optional) const minigitClone = Command.make("clone", { repository, directory, depth }, (config) => { const depth = Option.map(config.depth, (depth) => `--depth ${depth}`) const repository = Option.some(config.repository) - const optionsAndArgs = ReadonlyArray.getSomes([depth, repository, config.directory]) + const optionsAndArgs = Array.getSomes([depth, repository, config.directory]) return Console.log( "Running 'minigit clone' with the following options and arguments: " + - `'${ReadonlyArray.join(optionsAndArgs, ", ")}'` + `'${Array.join(optionsAndArgs, ", ")}'` ) }) ``` Some things to note in the above example: - 1. We've additionally imported the `Args` module from `@effect/cli` and the `ReadonlyArray` module from `effect` + 1. We've additionally imported the `Args` module from `@effect/cli` and the `Array` module from `effect` 2. We've used the `Args` module to specify some positional arguments for our `add` and `clone` subcommands 3. We've used `Options.withAlias` to give the `--verbose` flag an alias of `-v` for our `add` subcommand @@ -209,7 +209,7 @@ Our final CLI application is as follows: ```ts import { Args, Command, Options } from "@effect/cli" import { NodeContext, NodeRuntime } from "@effect/platform-node" -import { Console, Effect, Option, ReadonlyArray } from "effect" +import { Console, Effect, Option, Array } from "effect" // minigit [--version] [-h | --help] [-c =] const configs = Options.keyValueMap("c").pipe(Options.optional) @@ -228,9 +228,9 @@ const minigit = Command.make("minigit", { configs }, ({ configs }) => const pathspec = Args.text({ name: "pathspec" }).pipe(Args.repeated) const verbose = Options.boolean("verbose").pipe(Options.withAlias("v")) const minigitAdd = Command.make("add", { pathspec, verbose }, ({ pathspec, verbose }) => { - const paths = ReadonlyArray.match(pathspec, { + const paths = Array.match(pathspec, { onEmpty: () => "", - onNonEmpty: (paths) => ` ${ReadonlyArray.join(paths, " ")}` + onNonEmpty: (paths) => ` ${Array.join(paths, " ")}` }) return Console.log(`Running 'minigit add${paths}' with '--verbose ${verbose}'`) }) @@ -242,10 +242,10 @@ const depth = Options.integer('depth').pipe(Options.optional) const minigitClone = Command.make("clone", { repository, directory, depth }, (config) => { const depth = Option.map(config.depth, (depth) => `--depth ${depth}`) const repository = Option.some(config.repository) - const optionsAndArgs = ReadonlyArray.getSomes([depth, repository, config.directory]) + const optionsAndArgs = Array.getSomes([depth, repository, config.directory]) return Console.log( "Running 'minigit clone' with the following options and arguments: " + - `'${ReadonlyArray.join(optionsAndArgs, ", ")}'` + `'${Array.join(optionsAndArgs, ", ")}'` ) }) @@ -380,14 +380,14 @@ const minigitClone = Command.make("clone", { repository, directory, depth }, (su Effect.flatMap(minigit, (parentConfig) => { const depth = Option.map(subcommandConfig.depth, (depth) => `--depth ${depth}`) const repository = Option.some(subcommandConfig.repository) - const optionsAndArgs = ReadonlyArray.getSomes([depth, repository, subcommandConfig.directory]) + const optionsAndArgs = Array.getSomes([depth, repository, subcommandConfig.directory]) const configs = Option.match(parentConfig.configs, { onNone: () => "", onSome: (map) => Array.from(map).map(([key, value]) => `${key}=${value}`).join(", ") }) return Console.log( "Running 'minigit clone' with the following options and arguments: " + - `'${ReadonlyArray.join(optionsAndArgs, ", ")}'\n` + + `'${Array.join(optionsAndArgs, ", ")}'\n` + `and the following configuration parameters: ${configs}` ) }) diff --git a/packages/cli/examples/minigit.ts b/packages/cli/examples/minigit.ts index 4133ca8b4e..2dd73d971d 100644 --- a/packages/cli/examples/minigit.ts +++ b/packages/cli/examples/minigit.ts @@ -1,6 +1,6 @@ import { Args, Command, Options } from "@effect/cli" import { NodeContext, NodeRuntime } from "@effect/platform-node" -import { Config, ConfigProvider, Console, Effect, Option, ReadonlyArray } from "effect" +import { Array, Config, ConfigProvider, Console, Effect, Option } from "effect" // minigit [--version] [-h | --help] [-c =] const configs = Options.keyValueMap("c").pipe(Options.optional) @@ -8,7 +8,7 @@ const minigit = Command.make("minigit", { configs }, ({ configs }) => Option.match(configs, { onNone: () => Console.log("Running 'minigit'"), onSome: (configs) => { - const keyValuePairs = Array.from(configs) + const keyValuePairs = Array.fromIterable(configs) .map(([key, value]) => `${key}=${value}`) .join(", ") return Console.log(`Running 'minigit' with the following configs: ${keyValuePairs}`) @@ -22,9 +22,9 @@ const verbose = Options.boolean("verbose").pipe( Options.withFallbackConfig(Config.boolean("VERBOSE")) ) const minigitAdd = Command.make("add", { pathspec, verbose }, ({ pathspec, verbose }) => { - const paths = ReadonlyArray.match(pathspec, { + const paths = Array.match(pathspec, { onEmpty: () => "", - onNonEmpty: (paths) => ` ${ReadonlyArray.join(paths, " ")}` + onNonEmpty: (paths) => ` ${Array.join(paths, " ")}` }) return Console.log(`Running 'minigit add${paths}' with '--verbose ${verbose}'`) }) @@ -43,14 +43,14 @@ const minigitClone = Command.make( Effect.flatMap(minigit, (parentConfig) => { const depth = Option.map(subcommandConfig.depth, (depth) => `--depth ${depth}`) const repository = Option.some(subcommandConfig.repository) - const optionsAndArgs = ReadonlyArray.getSomes([depth, repository, subcommandConfig.directory]) + const optionsAndArgs = Array.getSomes([depth, repository, subcommandConfig.directory]) const configs = Option.match(parentConfig.configs, { onNone: () => "", - onSome: (map) => Array.from(map).map(([key, value]) => `${key}=${value}`).join(", ") + onSome: (map) => Array.fromIterable(map).map(([key, value]) => `${key}=${value}`).join(", ") }) return Console.log( "Running 'minigit clone' with the following options and arguments: " + - `'${ReadonlyArray.join(optionsAndArgs, ", ")}'\n` + + `'${Array.join(optionsAndArgs, ", ")}'\n` + `and the following configuration parameters: ${configs}` ) }) diff --git a/packages/cli/examples/naval-fate/store.ts b/packages/cli/examples/naval-fate/store.ts index 6206b7464f..a156817a25 100644 --- a/packages/cli/examples/naval-fate/store.ts +++ b/packages/cli/examples/naval-fate/store.ts @@ -1,11 +1,11 @@ import * as KeyValueStore from "@effect/platform/KeyValueStore" import * as Schema from "@effect/schema/Schema" +import * as Array from "effect/Array" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Layer from "effect/Layer" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import { CoordinatesOccupiedError, Mine, Ship, ShipExistsError, ShipNotFoundError } from "./domain.js" /** @@ -67,8 +67,8 @@ export const make = Effect.gen(function*($) { return yield* $(Effect.fail(new ShipNotFoundError({ name, x, y }))) } const shipAtCoords = pipe( - ReadonlyArray.fromIterable(oldShips.values()), - ReadonlyArray.findFirst((ship) => ship.hasCoordinates(x, y)) + Array.fromIterable(oldShips.values()), + Array.findFirst((ship) => ship.hasCoordinates(x, y)) ) if (Option.isSome(shipAtCoords)) { return yield* $(Effect.fail( @@ -76,7 +76,7 @@ export const make = Effect.gen(function*($) { )) } const mines = yield* $(getMines) - const mineAtCoords = ReadonlyArray.findFirst(mines, (mine) => mine.hasCoordinates(x, y)) + const mineAtCoords = Array.findFirst(mines, (mine) => mine.hasCoordinates(x, y)) const ship = Option.isSome(mineAtCoords) ? foundShip.value.move(x, y).destroy() : foundShip.value.move(x, y) @@ -89,8 +89,8 @@ export const make = Effect.gen(function*($) { Effect.gen(function*($) { const oldShips = yield* $(getShips) const shipAtCoords = pipe( - ReadonlyArray.fromIterable(oldShips.values()), - ReadonlyArray.findFirst((ship) => ship.hasCoordinates(x, y)) + Array.fromIterable(oldShips.values()), + Array.findFirst((ship) => ship.hasCoordinates(x, y)) ) if (Option.isSome(shipAtCoords)) { const ship = shipAtCoords.value.destroy() @@ -102,10 +102,10 @@ export const make = Effect.gen(function*($) { const setMine: NavalFateStore["setMine"] = (x, y) => Effect.gen(function*($) { const mines = yield* $(getMines) - const mineAtCoords = ReadonlyArray.findFirst(mines, (mine) => mine.hasCoordinates(x, y)) + const mineAtCoords = Array.findFirst(mines, (mine) => mine.hasCoordinates(x, y)) if (Option.isNone(mineAtCoords)) { const mine = Mine.create(x, y) - const newMines = ReadonlyArray.append(mines, mine) + const newMines = Array.append(mines, mine) yield* $(setMines(newMines)) } }) @@ -113,9 +113,9 @@ export const make = Effect.gen(function*($) { const removeMine: NavalFateStore["removeMine"] = (x, y) => Effect.gen(function*($) { const mines = yield* $(getMines) - const mineAtCoords = ReadonlyArray.findFirstIndex(mines, (mine) => mine.hasCoordinates(x, y)) + const mineAtCoords = Array.findFirstIndex(mines, (mine) => mine.hasCoordinates(x, y)) if (Option.isSome(mineAtCoords)) { - const newMines = ReadonlyArray.remove(mines, mineAtCoords.value) + const newMines = Array.remove(mines, mineAtCoords.value) yield* $(setMines(newMines)) } }) diff --git a/packages/cli/src/Args.ts b/packages/cli/src/Args.ts index 18d8a3626e..53bc67cf32 100644 --- a/packages/cli/src/Args.ts +++ b/packages/cli/src/Args.ts @@ -5,11 +5,11 @@ import type { FileSystem } from "@effect/platform/FileSystem" import type { Path } from "@effect/platform/Path" import type { QuitException, Terminal } from "@effect/platform/Terminal" import type { Schema } from "@effect/schema/Schema" +import type { NonEmptyArray } from "effect/Array" import type { Config } from "effect/Config" import type { Effect } from "effect/Effect" import type { Option } from "effect/Option" import type { Pipeable } from "effect/Pipeable" -import type { NonEmptyArray } from "effect/ReadonlyArray" import type { Secret } from "effect/Secret" import type { CliConfig } from "./CliConfig.js" import type { HelpDoc } from "./HelpDoc.js" diff --git a/packages/cli/src/CommandDescriptor.ts b/packages/cli/src/CommandDescriptor.ts index 4b3664e35a..ab9e626234 100644 --- a/packages/cli/src/CommandDescriptor.ts +++ b/packages/cli/src/CommandDescriptor.ts @@ -4,12 +4,12 @@ import type { FileSystem } from "@effect/platform/FileSystem" import type { Path } from "@effect/platform/Path" import type { QuitException, Terminal } from "@effect/platform/Terminal" +import type { NonEmptyReadonlyArray } from "effect/Array" import type { Effect } from "effect/Effect" import type { HashMap } from "effect/HashMap" import type { HashSet } from "effect/HashSet" import type { Option } from "effect/Option" import type { Pipeable } from "effect/Pipeable" -import type { NonEmptyReadonlyArray } from "effect/ReadonlyArray" import type { Args } from "./Args.js" import type { CliConfig } from "./CliConfig.js" import type { CommandDirective } from "./CommandDirective.js" diff --git a/packages/cli/src/HelpDoc.ts b/packages/cli/src/HelpDoc.ts index 344732d9b8..05d959665b 100644 --- a/packages/cli/src/HelpDoc.ts +++ b/packages/cli/src/HelpDoc.ts @@ -2,7 +2,7 @@ * @since 1.0.0 */ import type { AnsiDoc } from "@effect/printer-ansi/AnsiDoc" -import type { NonEmptyReadonlyArray } from "effect/ReadonlyArray" +import type { NonEmptyReadonlyArray } from "effect/Array" import type { Span } from "./HelpDoc/Span.js" import * as InternalHelpDoc from "./internal/helpDoc.js" diff --git a/packages/cli/src/Options.ts b/packages/cli/src/Options.ts index 549a588575..adcbfc5657 100644 --- a/packages/cli/src/Options.ts +++ b/packages/cli/src/Options.ts @@ -5,13 +5,13 @@ import type { FileSystem } from "@effect/platform/FileSystem" import type { Path } from "@effect/platform/Path" import type { QuitException, Terminal } from "@effect/platform/Terminal" import type { Schema } from "@effect/schema/Schema" +import type { NonEmptyArray } from "effect/Array" import type { Config } from "effect/Config" import type { Effect } from "effect/Effect" import type { Either } from "effect/Either" import type { HashMap } from "effect/HashMap" import type { Option } from "effect/Option" import type { Pipeable } from "effect/Pipeable" -import type { NonEmptyArray } from "effect/ReadonlyArray" import type { Secret } from "effect/Secret" import type { CliConfig } from "./CliConfig.js" import type { HelpDoc } from "./HelpDoc.js" diff --git a/packages/cli/src/internal/args.ts b/packages/cli/src/internal/args.ts index c16ace610a..d377cf0fd6 100644 --- a/packages/cli/src/internal/args.ts +++ b/packages/cli/src/internal/args.ts @@ -3,6 +3,7 @@ import type * as Path from "@effect/platform/Path" import type * as Terminal from "@effect/platform/Terminal" import * as Schema from "@effect/schema/Schema" import * as TreeFormatter from "@effect/schema/TreeFormatter" +import * as Array from "effect/Array" import type * as Config from "effect/Config" import * as Console from "effect/Console" import * as Effect from "effect/Effect" @@ -10,7 +11,6 @@ import * as Either from "effect/Either" import { dual, pipe } from "effect/Function" import * as Option from "effect/Option" import { pipeArguments } from "effect/Pipeable" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import type * as Secret from "effect/Secret" import type * as Args from "../Args.js" @@ -161,7 +161,7 @@ export const all: < if (isArgs(arguments[0])) { return map(arguments[0], (x) => [x]) as any } else if (Array.isArray(arguments[0])) { - return allTupled(arguments[0]) as any + return allTupled(arguments[0] as Array) as any } else { const entries = Object.entries(arguments[0] as Readonly<{ [K: string]: Args.Args }>) let result = map(entries[0][1], (value) => ({ [entries[0][0]]: value })) @@ -283,11 +283,11 @@ export const text = (config?: Args.Args.BaseArgsConfig): Args.Args => export const atLeast = dual< { (times: 0): (self: Args.Args) => Args.Args> - (times: number): (self: Args.Args) => Args.Args> + (times: number): (self: Args.Args) => Args.Args> }, { (self: Args.Args, times: 0): Args.Args> - (self: Args.Args, times: number): Args.Args> + (self: Args.Args, times: number): Args.Args> } >(2, (self, times) => makeVariadic(self, Option.some(times), Option.none()) as any) @@ -304,7 +304,7 @@ export const between = dual< ( min: number, max: number - ): (self: Args.Args) => Args.Args> + ): (self: Args.Args) => Args.Args> }, { (self: Args.Args, min: 0, max: number): Args.Args> @@ -312,7 +312,7 @@ export const between = dual< self: Args.Args, min: number, max: number - ): Args.Args> + ): Args.Args> } >(3, (self, min, max) => makeVariadic(self, Option.some(min), Option.some(max)) as any) @@ -568,13 +568,13 @@ const getIdentifierInternal = (self: Instruction): Option.Option => { return getIdentifierInternal(self.args as Instruction) } case "Both": { - const ids = ReadonlyArray.getSomes([ + const ids = Array.getSomes([ getIdentifierInternal(self.left as Instruction), getIdentifierInternal(self.right as Instruction) ]) - return ReadonlyArray.match(ids, { + return Array.match(ids, { onEmpty: () => Option.none(), - onNonEmpty: (ids) => Option.some(ReadonlyArray.join(ids, ", ")) + onNonEmpty: (ids) => Option.some(Array.join(ids, ", ")) }) } } @@ -637,7 +637,7 @@ const getUsageInternal = (self: Instruction): Usage.Usage => { } case "Single": { return InternalUsage.named( - ReadonlyArray.of(self.name), + Array.of(self.name), InternalPrimitive.getChoices(self.primitiveType) ) } @@ -743,7 +743,7 @@ const validateInternal = ( } case "Single": { return Effect.suspend(() => { - return ReadonlyArray.matchLeft(args, { + return Array.matchLeft(args, { onEmpty: () => { const choices = InternalPrimitive.getChoices(self.primitiveType) if (Option.isSome(self.pseudoName) && Option.isSome(choices)) { @@ -810,13 +810,13 @@ const validateInternal = ( } return validateInternal(self.args as Instruction, args, config).pipe(Effect.matchEffect({ onFailure: (failure) => - acc.length >= min1 && ReadonlyArray.isEmptyReadonlyArray(args) + acc.length >= min1 && Array.isEmptyReadonlyArray(args) ? Effect.succeed([args, acc]) : Effect.fail(failure), - onSuccess: ([args, a]) => loop(args, ReadonlyArray.append(acc, a)) + onSuccess: ([args, a]) => loop(args, Array.append(acc, a)) })) } - return loop(args, ReadonlyArray.empty()).pipe( + return loop(args, Array.empty()).pipe( Effect.map(([args, acc]) => [args as Array, acc]) ) } @@ -888,14 +888,14 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. > => { switch (self._tag) { case "Empty": { - return Effect.succeed(ReadonlyArray.empty()) + return Effect.succeed(Array.empty()) } case "Single": { const help = getHelpInternal(self) return InternalPrimitive.wizard(self.primitiveType, help).pipe( Effect.zipLeft(Console.log()), Effect.flatMap((input) => { - const args = ReadonlyArray.of(input as string) + const args = Array.of(input as string) return validateInternal(self, args, config).pipe(Effect.as(args)) }) ) @@ -909,7 +909,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. return Effect.zipWith( wizardInternal(self.left as Instruction, config), wizardInternal(self.right as Instruction, config), - (left, right) => ReadonlyArray.appendAll(left, right) + (left, right) => Array.appendAll(left, right) ).pipe(Effect.tap((args) => validateInternal(self, args, config))) } case "Variadic": { @@ -928,11 +928,11 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. Effect.zipLeft(Console.log()), Effect.flatMap((n) => n <= 0 - ? Effect.succeed(ReadonlyArray.empty()) - : Ref.make(ReadonlyArray.empty()).pipe( + ? Effect.succeed(Array.empty()) + : Ref.make(Array.empty()).pipe( Effect.flatMap((ref) => wizardInternal(self.args as Instruction, config).pipe( - Effect.flatMap((args) => Ref.update(ref, ReadonlyArray.appendAll(args))), + Effect.flatMap((args) => Ref.update(ref, Array.appendAll(args))), Effect.repeatN(n - 1), Effect.zipRight(Ref.get(ref)), Effect.tap((args) => validateInternal(self, args, config)) @@ -958,7 +958,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. Effect.zipLeft(Console.log()), Effect.flatMap((useFallback) => useFallback - ? Effect.succeed(ReadonlyArray.empty()) + ? Effect.succeed(Array.empty()) : wizardInternal(self.args as Instruction, config) ) ) @@ -979,7 +979,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. Effect.zipLeft(Console.log()), Effect.flatMap((useFallback) => useFallback - ? Effect.succeed(ReadonlyArray.empty()) + ? Effect.succeed(Array.empty()) : wizardInternal(self.args as Instruction, config) ) ) @@ -1013,7 +1013,7 @@ const getShortDescription = (self: Instruction): string => { export const getFishCompletions = (self: Instruction): Array => { switch (self._tag) { case "Empty": { - return ReadonlyArray.empty() + return Array.empty() } case "Single": { const description = getShortDescription(self) @@ -1021,19 +1021,19 @@ export const getFishCompletions = (self: Instruction): Array => { InternalPrimitive.getFishCompletions( self.primitiveType as InternalPrimitive.Instruction ), - ReadonlyArray.appendAll( + Array.appendAll( description.length === 0 - ? ReadonlyArray.empty() - : ReadonlyArray.of(`-d '${description}'`) + ? Array.empty() + : Array.of(`-d '${description}'`) ), - ReadonlyArray.join(" "), - ReadonlyArray.of + Array.join(" "), + Array.of ) } case "Both": { return pipe( getFishCompletions(self.left as Instruction), - ReadonlyArray.appendAll(getFishCompletions(self.right as Instruction)) + Array.appendAll(getFishCompletions(self.right as Instruction)) ) } case "Map": @@ -1056,7 +1056,7 @@ export const getZshCompletions = ( ): Array => { switch (self._tag) { case "Empty": { - return ReadonlyArray.empty() + return Array.empty() } case "Single": { const multiple = state.multiple ? "*" : "" @@ -1067,8 +1067,8 @@ export const getZshCompletions = ( self.primitiveType as InternalPrimitive.Instruction ) return possibleValues.length === 0 - ? ReadonlyArray.empty() - : ReadonlyArray.of(`${multiple}${optional}${self.name}${description}${possibleValues}`) + ? Array.empty() + : Array.of(`${multiple}${optional}${self.name}${description}${possibleValues}`) } case "Map": { return getZshCompletions(self.args as Instruction, state) @@ -1076,7 +1076,7 @@ export const getZshCompletions = ( case "Both": { const left = getZshCompletions(self.left as Instruction, state) const right = getZshCompletions(self.right as Instruction, state) - return ReadonlyArray.appendAll(left, right) + return Array.appendAll(left, right) } case "Variadic": { return Option.isSome(self.max) && self.max.value > 1 diff --git a/packages/cli/src/internal/cliApp.ts b/packages/cli/src/internal/cliApp.ts index 53d901ffdb..535f3723a4 100644 --- a/packages/cli/src/internal/cliApp.ts +++ b/packages/cli/src/internal/cliApp.ts @@ -1,5 +1,6 @@ import type * as Terminal from "@effect/platform/Terminal" import * as Color from "@effect/printer-ansi/Color" +import * as Array from "effect/Array" import * as Console from "effect/Console" import * as Context from "effect/Context" import * as Effect from "effect/Effect" @@ -7,7 +8,6 @@ import { dual, pipe } from "effect/Function" import * as HashMap from "effect/HashMap" import * as Option from "effect/Option" import { pipeArguments } from "effect/Pipeable" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Unify from "effect/Unify" import type * as BuiltInOptions from "../BuiltInOptions.js" import type * as CliApp from "../CliApp.js" @@ -77,14 +77,14 @@ export const run = dual< // Remove the executable from the command line arguments const [executable, filteredArgs] = splitExecutable(self, args) // Prefix the command name to the command line arguments - const prefixedArgs = ReadonlyArray.appendAll(prefixCommand(self.command), filteredArgs) + const prefixedArgs = Array.appendAll(prefixCommand(self.command), filteredArgs) // Handle the command return Effect.matchEffect(InternalCommand.parse(self.command, prefixedArgs, config), { onFailure: (e) => Effect.zipRight(printDocs(e.error), Effect.fail(e)), onSuccess: Unify.unify((directive) => { switch (directive._tag) { case "UserDefined": { - return ReadonlyArray.matchLeft(directive.leftover, { + return Array.matchLeft(directive.leftover, { onEmpty: () => execute(directive.value).pipe( Effect.catchSome((e) => @@ -123,9 +123,9 @@ const splitExecutable = (self: CliApp.CliApp, args: ReadonlyArray) args: ReadonlyArray ] => { if (self.executable !== undefined) { - return [self.executable, ReadonlyArray.drop(args, 2)] + return [self.executable, Array.drop(args, 2)] } - const [[runtime, script], optionsAndArgs] = ReadonlyArray.splitAt(args, 2) + const [[runtime, script], optionsAndArgs] = Array.splitAt(args, 2) return [`${runtime} ${script}`, optionsAndArgs] } @@ -165,8 +165,8 @@ const handleBuiltInOption = ( InternalHelpDoc.h1("USAGE"), pipe( InternalUsage.enumerate(builtIn.usage, config), - ReadonlyArray.map((span) => InternalHelpDoc.p(InternalSpan.concat(InternalSpan.text("$ "), span))), - ReadonlyArray.reduceRight( + Array.map((span) => InternalHelpDoc.p(InternalSpan.concat(InternalSpan.text("$ "), span))), + Array.reduceRight( InternalHelpDoc.empty, (left, right) => InternalHelpDoc.sequence(left, right) ) @@ -182,21 +182,21 @@ const handleBuiltInOption = ( return Console.log(InternalHelpDoc.toAnsiText(helpDoc)) } case "ShowCompletions": { - const command = Array.from(InternalCommand.getNames(self.command))[0]! + const command = Array.fromIterable(InternalCommand.getNames(self.command))[0]! switch (builtIn.shellType) { case "bash": { return InternalCommand.getBashCompletions(self.command, command).pipe( - Effect.flatMap((completions) => Console.log(ReadonlyArray.join(completions, "\n"))) + Effect.flatMap((completions) => Console.log(Array.join(completions, "\n"))) ) } case "fish": { return InternalCommand.getFishCompletions(self.command, command).pipe( - Effect.flatMap((completions) => Console.log(ReadonlyArray.join(completions, "\n"))) + Effect.flatMap((completions) => Console.log(Array.join(completions, "\n"))) ) } case "zsh": return InternalCommand.getZshCompletions(self.command, command).pipe( - Effect.flatMap((completions) => Console.log(ReadonlyArray.join(completions, "\n"))) + Effect.flatMap((completions) => Console.log(Array.join(completions, "\n"))) ) } } @@ -234,7 +234,7 @@ const handleBuiltInOption = ( ) const help = InternalHelpDoc.sequence(header, description) const text = InternalHelpDoc.toAnsiText(help) - const command = Array.from(InternalCommand.getNames(self.command))[0]! + const command = Array.fromIterable(InternalCommand.getNames(self.command))[0]! const wizardPrefix = getWizardPrefix(builtIn, command, args) return Console.log(text).pipe( Effect.zipRight(InternalCommand.wizard(builtIn.command, wizardPrefix, config)), @@ -247,8 +247,8 @@ const handleBuiltInOption = ( inactive: "no" }).pipe(Effect.flatMap((shouldRunCommand) => { const finalArgs = pipe( - ReadonlyArray.drop(args, 1), - ReadonlyArray.prependAll(executable.split(/\s+/)) + Array.drop(args, 1), + Array.prependAll(executable.split(/\s+/)) ) return shouldRunCommand ? Console.log().pipe(Effect.zipRight(run(self, finalArgs, execute))) @@ -273,16 +273,16 @@ const handleBuiltInOption = ( const prefixCommand = (self: Command.Command): ReadonlyArray => { let command: InternalCommand.Instruction | undefined = self as InternalCommand.Instruction - let prefix: ReadonlyArray = ReadonlyArray.empty() + let prefix: ReadonlyArray = Array.empty() while (command !== undefined) { switch (command._tag) { case "Standard": { - prefix = ReadonlyArray.of(command.name) + prefix = Array.of(command.name) command = undefined break } case "GetUserInput": { - prefix = ReadonlyArray.of(command.name) + prefix = Array.of(command.name) command = undefined break } @@ -305,21 +305,21 @@ const getWizardPrefix = ( commandLineArgs: ReadonlyArray ): ReadonlyArray => { const subcommands = InternalCommand.getSubcommands(builtIn.command) - const [parentArgs, childArgs] = ReadonlyArray.span( + const [parentArgs, childArgs] = Array.span( commandLineArgs, (name) => !HashMap.has(subcommands, name) ) - const args = ReadonlyArray.matchLeft(childArgs, { - onEmpty: () => ReadonlyArray.filter(parentArgs, (arg) => arg !== "--wizard"), - onNonEmpty: (head) => ReadonlyArray.append(parentArgs, head) + const args = Array.matchLeft(childArgs, { + onEmpty: () => Array.filter(parentArgs, (arg) => arg !== "--wizard"), + onNonEmpty: (head) => Array.append(parentArgs, head) }) - return ReadonlyArray.appendAll(rootCommand.split(/\s+/), args) + return Array.appendAll(rootCommand.split(/\s+/), args) } const renderWizardArgs = (args: ReadonlyArray) => { const params = pipe( - ReadonlyArray.filter(args, (param) => param.length > 0), - ReadonlyArray.join(" ") + Array.filter(args, (param) => param.length > 0), + Array.join(" ") ) const executeMsg = InternalSpan.text( "You may now execute your command directly with the following options and arguments:" diff --git a/packages/cli/src/internal/command.ts b/packages/cli/src/internal/command.ts index 3c6fef970b..da03581b11 100644 --- a/packages/cli/src/internal/command.ts +++ b/packages/cli/src/internal/command.ts @@ -1,6 +1,7 @@ import type * as FileSystem from "@effect/platform/FileSystem" import type * as Path from "@effect/platform/Path" import type * as Terminal from "@effect/platform/Terminal" +import * as Array from "effect/Array" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as Effectable from "effect/Effectable" @@ -11,7 +12,6 @@ import type * as HashSet from "effect/HashSet" import type * as Layer from "effect/Layer" import type * as Option from "effect/Option" import { pipeArguments } from "effect/Pipeable" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as Types from "effect/Types" import type * as Args from "../Args.js" import type * as CliApp from "../CliApp.js" @@ -59,7 +59,7 @@ const parseConfig = (config: Command.Command.Config): Command.Command.ParsedConf if (Array.isArray(value)) { return { _tag: "Array", - children: ReadonlyArray.map(value, parseValue) + children: Array.map(value as Array, parseValue) } } else if (InternalArgs.isArgs(value)) { args.push(value) @@ -107,7 +107,7 @@ const reconstructConfigTree = ( } else if (node._tag === "Options") { return options[node.index] } else if (node._tag === "Array") { - return ReadonlyArray.map(node.children, nodeValue) + return Array.map(node.children, nodeValue) } else { return reconstructConfigTree(node.tree, args, options) } @@ -191,7 +191,9 @@ export const fromDescriptor = dual< descriptor, handler ?? ((_) => Effect.failSync(() => ValidationError.helpRequested(getDescriptor(self)))), - Context.GenericTag(`@effect/cli/Command/(${Array.from(InternalDescriptor.getNames(descriptor)).join("|")})`) + Context.GenericTag( + `@effect/cli/Command/(${Array.fromIterable(InternalDescriptor.getNames(descriptor)).join("|")})` + ) ) return self as any } @@ -425,7 +427,7 @@ export const withDescription = dual< /** @internal */ export const withSubcommands = dual< - >>( + >>( subcommands: Subcommand ) => (self: Command.Command) => Command.Command< Name, @@ -451,7 +453,7 @@ export const withSubcommands = dual< R, E, A, - Subcommand extends ReadonlyArray.NonEmptyReadonlyArray> + Subcommand extends Array.NonEmptyReadonlyArray> >( self: Command.Command, subcommands: Subcommand @@ -477,9 +479,9 @@ export const withSubcommands = dual< >(2, (self, subcommands) => { const command = InternalDescriptor.withSubcommands( self.descriptor, - ReadonlyArray.map(subcommands, (_) => [_.tag, _.descriptor]) + Array.map(subcommands, (_) => [_.tag, _.descriptor]) ) - const subcommandMap = ReadonlyArray.reduce( + const subcommandMap = Array.reduce( subcommands, new Map, Command.Command>(), (handlers, subcommand) => { diff --git a/packages/cli/src/internal/commandDescriptor.ts b/packages/cli/src/internal/commandDescriptor.ts index 4df3407c92..1b4fbcc560 100644 --- a/packages/cli/src/internal/commandDescriptor.ts +++ b/packages/cli/src/internal/commandDescriptor.ts @@ -2,6 +2,7 @@ import type * as FileSystem from "@effect/platform/FileSystem" import type * as Path from "@effect/platform/Path" import type * as Terminal from "@effect/platform/Terminal" import * as Color from "@effect/printer-ansi/Color" +import * as Array from "effect/Array" import * as Console from "effect/Console" import * as Effect from "effect/Effect" import * as Either from "effect/Either" @@ -11,7 +12,6 @@ import * as HashSet from "effect/HashSet" import * as Option from "effect/Option" import * as Order from "effect/Order" import { pipeArguments } from "effect/Pipeable" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import * as SynchronizedRef from "effect/SynchronizedRef" import type * as Args from "../Args.js" @@ -99,7 +99,7 @@ export interface Map extends export interface Subcommands extends Op<"Subcommands", { readonly parent: Instruction - readonly children: ReadonlyArray.NonEmptyReadonlyArray + readonly children: Array.NonEmptyReadonlyArray }> {} @@ -264,7 +264,7 @@ export const withDescription = dual< /** @internal */ export const withSubcommands = dual< < - const Subcommands extends ReadonlyArray.NonEmptyReadonlyArray< + const Subcommands extends Array.NonEmptyReadonlyArray< readonly [id: unknown, command: Descriptor.Command] > >( @@ -279,7 +279,7 @@ export const withSubcommands = dual< >, < A, - const Subcommands extends ReadonlyArray.NonEmptyReadonlyArray< + const Subcommands extends Array.NonEmptyReadonlyArray< readonly [id: unknown, command: Descriptor.Command] > >( @@ -295,7 +295,7 @@ export const withSubcommands = dual< const op = Object.create(proto) op._tag = "Subcommands" op.parent = self - op.children = ReadonlyArray.map(subcommands, ([id, command]) => map(command, (a) => [id, a])) + op.children = Array.map(subcommands, ([id, command]) => map(command, (a) => [id, a])) return op }) @@ -360,8 +360,8 @@ const getHelpInternal = (self: Instruction, config: CliConfig.CliConfig): HelpDo case "Standard": case "GetUserInput": { const usage = InternalHelpDoc.getSpan(InternalUsage.getHelp(getUsageInternal(command))) - const usages = ReadonlyArray.append(preceding, usage) - const finalUsage = ReadonlyArray.reduce( + const usages = Array.append(preceding, usage) + const finalUsage = Array.reduce( usages, InternalSpan.empty, (acc, next) => @@ -372,25 +372,25 @@ const getHelpInternal = (self: Instruction, config: CliConfig.CliConfig): HelpDo : InternalSpan.spans([acc, InternalSpan.space, next]) ) const description = InternalHelpDoc.getSpan(command.description) - return ReadonlyArray.of([finalUsage, description]) + return Array.of([finalUsage, description]) } case "Map": { return getUsage(command.command, preceding) } case "Subcommands": { const parentUsage = getUsage(command.parent, preceding) - return Option.match(ReadonlyArray.head(parentUsage), { + return Option.match(Array.head(parentUsage), { onNone: () => - ReadonlyArray.flatMap( + Array.flatMap( command.children, (child) => getUsage(child, preceding) ), onSome: ([usage]) => { - const childrenUsage = ReadonlyArray.flatMap( + const childrenUsage = Array.flatMap( command.children, - (child) => getUsage(child, ReadonlyArray.append(preceding, usage)) + (child) => getUsage(child, Array.append(preceding, usage)) ) - return ReadonlyArray.appendAll(parentUsage, childrenUsage) + return Array.appendAll(parentUsage, childrenUsage) } }) } @@ -399,12 +399,12 @@ const getHelpInternal = (self: Instruction, config: CliConfig.CliConfig): HelpDo const printSubcommands = ( subcommands: ReadonlyArray<[Span.Span, Span.Span]> ): HelpDoc.HelpDoc => { - const maxUsageLength = ReadonlyArray.reduceRight( + const maxUsageLength = Array.reduceRight( subcommands, 0, (max, [usage]) => Math.max(InternalSpan.size(usage), max) ) - const documents = ReadonlyArray.map(subcommands, ([usage, desc]) => + const documents = Array.map(subcommands, ([usage, desc]) => InternalHelpDoc.p( InternalSpan.spans([ usage, @@ -412,7 +412,7 @@ const getHelpInternal = (self: Instruction, config: CliConfig.CliConfig): HelpDo desc ]) )) - if (ReadonlyArray.isNonEmptyReadonlyArray(documents)) { + if (Array.isNonEmptyReadonlyArray(documents)) { return InternalHelpDoc.enumeration(documents) } throw new Error("[BUG]: Subcommands.usage - received empty list of subcommands to print") @@ -421,9 +421,9 @@ const getHelpInternal = (self: Instruction, config: CliConfig.CliConfig): HelpDo getHelpInternal(self.parent, config), InternalHelpDoc.sequence( InternalHelpDoc.h1("COMMANDS"), - printSubcommands(ReadonlyArray.flatMap( + printSubcommands(Array.flatMap( self.children, - (child) => getUsage(child, ReadonlyArray.empty()) + (child) => getUsage(child, Array.empty()) )) ) ) @@ -435,7 +435,7 @@ const getNamesInternal = (self: Instruction): Array => { switch (self._tag) { case "Standard": case "GetUserInput": { - return ReadonlyArray.of(self.name) + return Array.of(self.name) } case "Map": { return getNamesInternal(self.command) @@ -456,7 +456,7 @@ const getSubcommandsInternal = ( switch (self._tag) { case "Standard": case "GetUserInput": { - return ReadonlyArray.of([self.name, self]) + return Array.of([self.name, self]) } case "Map": { return loop(self.command, isSubcommand) @@ -466,7 +466,7 @@ const getSubcommandsInternal = ( // parent command return isSubcommand ? loop(self.parent, false) - : ReadonlyArray.flatMap(self.children, (child) => loop(child, true)) + : Array.flatMap(self.children, (child) => loop(child, true)) } } } @@ -477,7 +477,7 @@ const getUsageInternal = (self: Instruction): Usage.Usage => { switch (self._tag) { case "Standard": { return InternalUsage.concat( - InternalUsage.named(ReadonlyArray.of(self.name), Option.none()), + InternalUsage.named(Array.of(self.name), Option.none()), InternalUsage.concat( InternalOptions.getUsage(self.options), InternalArgs.getUsage(self.args) @@ -485,7 +485,7 @@ const getUsageInternal = (self: Instruction): Usage.Usage => { ) } case "GetUserInput": { - return InternalUsage.named(ReadonlyArray.of(self.name), Option.none()) + return InternalUsage.named(Array.of(self.name), Option.none()) } case "Map": { return getUsageInternal(self.command) @@ -513,7 +513,7 @@ const parseInternal = ( const parseCommandLine = ( args: ReadonlyArray ): Effect.Effect, ValidationError.ValidationError> => - ReadonlyArray.matchLeft(args, { + Array.matchLeft(args, { onEmpty: () => { const error = InternalHelpDoc.p(`Missing command name: '${self.name}'`) return Effect.fail(InternalValidationError.commandMismatch(error)) @@ -538,7 +538,7 @@ const parseInternal = ( ValidationError.ValidationError, FileSystem.FileSystem | Path.Path | Terminal.Terminal > => - ReadonlyArray.matchLeft(args, { + Array.matchLeft(args, { onEmpty: () => { const error = InternalHelpDoc.p(`Missing command name: '${self.name}'`) return Effect.fail(InternalValidationError.commandMismatch(error)) @@ -550,7 +550,7 @@ const parseInternal = ( const help = getHelpInternal(self, config) const usage = getUsageInternal(self) const options = InternalBuiltInOptions.builtInOptions(self, usage, help) - const argsWithoutCommand = ReadonlyArray.drop(args, 1) + const argsWithoutCommand = Array.drop(args, 1) return InternalOptions.processCommandLine(options, argsWithoutCommand, config) .pipe( Effect.flatMap((tuple) => tuple[2]), @@ -578,7 +578,7 @@ const parseInternal = ( Effect.flatMap(([error, commandArgs, optionsType]) => InternalArgs.validate( self.args, - ReadonlyArray.appendAll(commandArgs, forcedCommandArgs), + Array.appendAll(commandArgs, forcedCommandArgs), config ).pipe( Effect.catchAll((e) => @@ -605,14 +605,14 @@ const parseInternal = ( ValidationError.ValidationError, FileSystem.FileSystem | Path.Path | Terminal.Terminal > => { - if (ReadonlyArray.contains(args, "--help") || ReadonlyArray.contains(args, "-h")) { - return parseBuiltInArgs(ReadonlyArray.make(self.name, "--help")) + if (Array.contains(args, "--help") || Array.contains(args, "-h")) { + return parseBuiltInArgs(Array.make(self.name, "--help")) } - if (ReadonlyArray.contains(args, "--wizard")) { - return parseBuiltInArgs(ReadonlyArray.make(self.name, "--wizard")) + if (Array.contains(args, "--wizard")) { + return parseBuiltInArgs(Array.make(self.name, "--wizard")) } - if (ReadonlyArray.contains(args, "--version")) { - return parseBuiltInArgs(ReadonlyArray.make(self.name, "--version")) + if (Array.contains(args, "--version")) { + return parseBuiltInArgs(Array.make(self.name, "--version")) } const error = InternalHelpDoc.p(`Missing command name: '${self.name}'`) return Effect.fail(InternalValidationError.commandMismatch(error)) @@ -642,7 +642,7 @@ const parseInternal = ( return InternalPrompt.run(self.prompt).pipe( Effect.catchTag("QuitException", (e) => Effect.die(e)), Effect.map((value) => - InternalCommandDirective.userDefined(ReadonlyArray.drop(args, 1), { + InternalCommandDirective.userDefined(Array.drop(args, 1), { name: self.name, value }) @@ -667,9 +667,9 @@ const parseInternal = ( case "Subcommands": { const names = getNamesInternal(self) const subcommands = getSubcommandsInternal(self) - const [parentArgs, childArgs] = ReadonlyArray.span( + const [parentArgs, childArgs] = Array.span( args, - (arg) => !ReadonlyArray.some(subcommands, ([name]) => name === arg) + (arg) => !Array.some(subcommands, ([name]) => name === arg) ) const parseChildren = Effect.suspend(() => { const iterator = self.children[Symbol.iterator]() @@ -701,10 +701,10 @@ const parseInternal = ( InternalCommandDirective.isBuiltIn(directive) && InternalBuiltInOptions.isShowHelp(directive.option) ) { - const parentName = Option.getOrElse(ReadonlyArray.head(names), () => "") + const parentName = Option.getOrElse(Array.head(names), () => "") const newDirective = InternalCommandDirective.builtIn(InternalBuiltInOptions.showHelp( InternalUsage.concat( - InternalUsage.named(ReadonlyArray.of(parentName), Option.none()), + InternalUsage.named(Array.of(parentName), Option.none()), directive.option.usage ), directive.option.helpDoc @@ -736,7 +736,7 @@ const parseInternal = ( if (InternalBuiltInOptions.isShowHelp(directive.option)) { // We do not want to display the child help docs if there are // no arguments indicating the CLI command was for the child - return ReadonlyArray.isNonEmptyReadonlyArray(childArgs) + return Array.isNonEmptyReadonlyArray(childArgs) ? Effect.orElse(helpDirectiveForChild, () => helpDirectiveForParent) : helpDirectiveForParent } @@ -746,16 +746,16 @@ const parseInternal = ( return Effect.succeed(directive) } case "UserDefined": { - const args = ReadonlyArray.appendAll(directive.leftover, childArgs) - if (ReadonlyArray.isNonEmptyReadonlyArray(args)) { + const args = Array.appendAll(directive.leftover, childArgs) + if (Array.isNonEmptyReadonlyArray(args)) { return parseChildren.pipe(Effect.mapBoth({ onFailure: (err) => { if (InternalValidationError.isCommandMismatch(err)) { - const parentName = Option.getOrElse(ReadonlyArray.head(names), () => "") - const childNames = ReadonlyArray.map(subcommands, ([name]) => `'${name}'`) + const parentName = Option.getOrElse(Array.head(names), () => "") + const childNames = Array.map(subcommands, ([name]) => `'${name}'`) const oneOf = childNames.length === 1 ? "" : " one of" const error = InternalHelpDoc.p( - `Invalid subcommand for ${parentName} - use${oneOf} ${ReadonlyArray.join(childNames, ", ")}` + `Invalid subcommand for ${parentName} - use${oneOf} ${Array.join(childNames, ", ")}` ) return InternalValidationError.commandMismatch(error) } @@ -775,7 +775,7 @@ const parseInternal = ( } }), Effect.catchSome(() => - ReadonlyArray.isEmptyReadonlyArray(args) + Array.isEmptyReadonlyArray(args) ? Option.some(helpDirectiveForParent) : Option.none() ) @@ -788,8 +788,8 @@ const parseInternal = ( const splitForcedArgs = ( args: ReadonlyArray ): [Array, Array] => { - const [remainingArgs, forcedArgs] = ReadonlyArray.span(args, (str) => str !== "--") - return [remainingArgs, ReadonlyArray.drop(forcedArgs, 1)] + const [remainingArgs, forcedArgs] = Array.span(args, (str) => str !== "--") + return [remainingArgs, Array.drop(forcedArgs, 1)] } const withDescriptionInternal = ( @@ -858,7 +858,7 @@ const wizardInternal = ( InternalSpan.strong(InternalSpan.highlight("COMMAND:", Color.cyan)), InternalSpan.concat(InternalSpan.space), InternalSpan.concat(InternalSpan.highlight( - ReadonlyArray.join(commandLine, " "), + Array.join(commandLine, " "), Color.magenta )) )) @@ -875,7 +875,7 @@ const wizardInternal = ( ) yield* _(Console.log(InternalHelpDoc.toAnsiText(message))) const options = yield* _(InternalOptions.wizard(self.options, config)) - yield* _(Ref.updateAndGet(commandLineRef, ReadonlyArray.appendAll(options))) + yield* _(Ref.updateAndGet(commandLineRef, Array.appendAll(options))) yield* _(logCurrentCommand) } // If the command has args, run the wizard for them @@ -885,7 +885,7 @@ const wizardInternal = ( ) yield* _(Console.log(InternalHelpDoc.toAnsiText(message))) const options = yield* _(InternalArgs.wizard(self.args, config)) - yield* _(Ref.updateAndGet(commandLineRef, ReadonlyArray.appendAll(options))) + yield* _(Ref.updateAndGet(commandLineRef, Array.appendAll(options))) yield* _(logCurrentCommand) } } @@ -903,13 +903,13 @@ const wizardInternal = ( value: [title, index] as const }) const choices = pipe( - Array.from(getSubcommandsInternal(self)), - ReadonlyArray.map(([name], index) => makeChoice(name, index)) + getSubcommandsInternal(self), + Array.map(([name], index) => makeChoice(name, index)) ) return loop(self.parent, commandLineRef).pipe( Effect.zipRight( InternalSelectPrompt.select({ message, choices }).pipe( - Effect.tap(([name]) => Ref.update(commandLineRef, ReadonlyArray.append(name))), + Effect.tap(([name]) => Ref.update(commandLineRef, Array.append(name))), Effect.zipLeft(Console.log()), Effect.flatMap(([, nextIndex]) => loop(self.children[nextIndex], commandLineRef)) ) @@ -994,9 +994,9 @@ const traverseCommand = ( return loop(self.command, parentCommands, subcommands, level) } case "Subcommands": { - const parentNames = Array.from(getNamesInternal(self.parent)) - const nextSubcommands = Array.from(getSubcommandsInternal(self)) - const nextParentCommands = ReadonlyArray.appendAll(parentCommands, parentNames) + const parentNames = getNamesInternal(self.parent) + const nextSubcommands = getSubcommandsInternal(self) + const nextParentCommands = Array.appendAll(parentCommands, parentNames) // Traverse the parent command using old parent names and next subcommands return loop(self.parent, parentCommands, nextSubcommands, level).pipe( Effect.zipRight(Effect.forEach(self.children, (child) => @@ -1006,7 +1006,7 @@ const traverseCommand = ( } } } - return Effect.suspend(() => loop(self, ReadonlyArray.empty(), ReadonlyArray.empty(), 0)).pipe( + return Effect.suspend(() => loop(self, Array.empty(), Array.empty(), 0)).pipe( Effect.zipRight(SynchronizedRef.get(ref)) ) })) @@ -1015,8 +1015,8 @@ const indentAll = dual< (indent: number) => (self: ReadonlyArray) => Array, (self: ReadonlyArray, indent: number) => Array >(2, (self: ReadonlyArray, indent: number): Array => { - const indentation = new Array(indent + 1).join(" ") - return ReadonlyArray.map(self, (line) => `${indentation}${line}`) + const indentation = Array.allocate(indent + 1).join(" ") + return Array.map(self, (line) => `${indentation}${line}`) }) const getBashCompletionsInternal = ( @@ -1025,7 +1025,7 @@ const getBashCompletionsInternal = ( ): Effect.Effect> => traverseCommand( self, - ReadonlyArray.empty<[ReadonlyArray, ReadonlyArray]>(), + Array.empty<[ReadonlyArray, ReadonlyArray]>(), (state, info) => { const options = isStandard(info.command) ? Options.all([info.command.options, InternalBuiltInOptions.builtIns]) @@ -1033,24 +1033,24 @@ const getBashCompletionsInternal = ( const optionNames = InternalOptions.getNames(options as InternalOptions.Instruction) const optionCases = isStandard(info.command) ? InternalOptions.getBashCompletions(info.command.options as InternalOptions.Instruction) - : ReadonlyArray.empty() + : Array.empty() const subcommandNames = pipe( info.subcommands, - ReadonlyArray.map(([name]) => name), - ReadonlyArray.sort(Order.string) + Array.map(([name]) => name), + Array.sort(Order.string) ) - const wordList = ReadonlyArray.appendAll(optionNames, subcommandNames) - const preformatted = ReadonlyArray.isEmptyReadonlyArray(info.parentCommands) - ? ReadonlyArray.of(info.command.name) + const wordList = Array.appendAll(optionNames, subcommandNames) + const preformatted = Array.isEmptyReadonlyArray(info.parentCommands) + ? Array.of(info.command.name) : pipe( info.parentCommands, - ReadonlyArray.append(info.command.name), - ReadonlyArray.map((command) => command.replace("-", "__")) + Array.append(info.command.name), + Array.map((command) => command.replace("-", "__")) ) - const caseName = ReadonlyArray.join(preformatted, ",") - const funcName = ReadonlyArray.join(preformatted, "__") - const funcLines = ReadonlyArray.isEmptyReadonlyArray(info.parentCommands) - ? ReadonlyArray.empty() + const caseName = Array.join(preformatted, ",") + const funcName = Array.join(preformatted, "__") + const funcLines = Array.isEmptyReadonlyArray(info.parentCommands) + ? Array.empty() : [ `${caseName})`, ` cmd="${funcName}"`, @@ -1058,7 +1058,7 @@ const getBashCompletionsInternal = ( ] const cmdLines = [ `${funcName})`, - ` opts="${ReadonlyArray.join(wordList, " ")}"`, + ` opts="${Array.join(wordList, " ")}"`, ` if [[ \${cur} == -* || \${COMP_CWORD} -eq ${info.level + 1} ]] ; then`, " COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )", " return 0", @@ -1073,17 +1073,17 @@ const getBashCompletionsInternal = ( " return 0", " ;;" ] - const lines = ReadonlyArray.append( + const lines = Array.append( state, [funcLines, cmdLines] as [ReadonlyArray, ReadonlyArray] ) return Effect.succeed(lines) } ).pipe(Effect.map((lines) => { - const rootCommand = ReadonlyArray.unsafeGet(getNamesInternal(self), 0) + const rootCommand = Array.unsafeGet(getNamesInternal(self), 0) const scriptName = `_${rootCommand}_bash_completions` - const funcCases = ReadonlyArray.flatMap(lines, ([funcLines]) => funcLines) - const cmdCases = ReadonlyArray.flatMap(lines, ([, cmdLines]) => cmdLines) + const funcCases = Array.flatMap(lines, ([funcLines]) => funcLines) + const cmdCases = Array.flatMap(lines, ([, cmdLines]) => cmdLines) return [ `function ${scriptName}() {`, " local i cur prev opts cmd", @@ -1114,8 +1114,8 @@ const getFishCompletionsInternal = ( self: Instruction, executable: string ): Effect.Effect> => - traverseCommand(self, ReadonlyArray.empty(), (state, info) => { - const baseTemplate = ReadonlyArray.make("complete", "-c", executable) + traverseCommand(self, Array.empty(), (state, info) => { + const baseTemplate = Array.make("complete", "-c", executable) const options = isStandard(info.command) ? InternalOptions.all([InternalBuiltInOptions.builtIns, info.command.options]) : InternalBuiltInOptions.builtIns @@ -1124,71 +1124,71 @@ const getFishCompletionsInternal = ( ) const argsCompletions = isStandard(info.command) ? InternalArgs.getFishCompletions(info.command.args as InternalArgs.Instruction) - : ReadonlyArray.empty() + : Array.empty() const rootCompletions = (conditionals: ReadonlyArray) => pipe( - ReadonlyArray.map(optionsCompletions, (option) => + Array.map(optionsCompletions, (option) => pipe( baseTemplate, - ReadonlyArray.appendAll(conditionals), - ReadonlyArray.append(option), - ReadonlyArray.join(" ") + Array.appendAll(conditionals), + Array.append(option), + Array.join(" ") )), - ReadonlyArray.appendAll( - ReadonlyArray.map(argsCompletions, (option) => + Array.appendAll( + Array.map(argsCompletions, (option) => pipe( baseTemplate, - ReadonlyArray.appendAll(conditionals), - ReadonlyArray.append(option), - ReadonlyArray.join(" ") + Array.appendAll(conditionals), + Array.append(option), + Array.join(" ") )) ) ) const subcommandCompletions = (conditionals: ReadonlyArray) => - ReadonlyArray.map(info.subcommands, ([name, subcommand]) => { + Array.map(info.subcommands, ([name, subcommand]) => { const description = getShortDescription(subcommand) return pipe( baseTemplate, - ReadonlyArray.appendAll(conditionals), - ReadonlyArray.appendAll(ReadonlyArray.make("-f", "-a", `"${name}"`)), - ReadonlyArray.appendAll( + Array.appendAll(conditionals), + Array.appendAll(Array.make("-f", "-a", `"${name}"`)), + Array.appendAll( description.length === 0 - ? ReadonlyArray.empty() - : ReadonlyArray.make("-d", `'${description}'`) + ? Array.empty() + : Array.make("-d", `'${description}'`) ), - ReadonlyArray.join(" ") + Array.join(" ") ) }) // If parent commands are empty, then the info is for the root command - if (ReadonlyArray.isEmptyReadonlyArray(info.parentCommands)) { - const conditionals = ReadonlyArray.make("-n", "\"__fish_use_subcommand\"") + if (Array.isEmptyReadonlyArray(info.parentCommands)) { + const conditionals = Array.make("-n", "\"__fish_use_subcommand\"") return Effect.succeed(pipe( state, - ReadonlyArray.appendAll(rootCompletions(conditionals)), - ReadonlyArray.appendAll(subcommandCompletions(conditionals)) + Array.appendAll(rootCompletions(conditionals)), + Array.appendAll(subcommandCompletions(conditionals)) )) } // Otherwise the info is for a subcommand const parentConditionals = pipe( info.parentCommands, // Drop the root command name from the subcommand conditionals - ReadonlyArray.drop(1), - ReadonlyArray.append(info.command.name), - ReadonlyArray.map((command) => `__fish_seen_subcommand_from ${command}`) + Array.drop(1), + Array.append(info.command.name), + Array.map((command) => `__fish_seen_subcommand_from ${command}`) ) - const subcommandConditionals = ReadonlyArray.map( + const subcommandConditionals = Array.map( info.subcommands, ([name]) => `not __fish_seen_subcommand_from ${name}` ) const baseConditionals = pipe( - ReadonlyArray.appendAll(parentConditionals, subcommandConditionals), - ReadonlyArray.join("; and ") + Array.appendAll(parentConditionals, subcommandConditionals), + Array.join("; and ") ) - const conditionals = ReadonlyArray.make("-n", `"${baseConditionals}"`) + const conditionals = Array.make("-n", `"${baseConditionals}"`) return Effect.succeed(pipe( state, - ReadonlyArray.appendAll(rootCompletions(conditionals)), - ReadonlyArray.appendAll(subcommandCompletions(conditionals)) + Array.appendAll(rootCompletions(conditionals)), + Array.appendAll(subcommandCompletions(conditionals)) )) }) @@ -1196,26 +1196,26 @@ const getZshCompletionsInternal = ( self: Instruction, executable: string ): Effect.Effect> => - traverseCommand(self, ReadonlyArray.empty(), (state, info) => { - const preformatted = ReadonlyArray.isEmptyReadonlyArray(info.parentCommands) - ? ReadonlyArray.of(info.command.name) + traverseCommand(self, Array.empty(), (state, info) => { + const preformatted = Array.isEmptyReadonlyArray(info.parentCommands) + ? Array.of(info.command.name) : pipe( info.parentCommands, - ReadonlyArray.append(info.command.name), - ReadonlyArray.map((command) => command.replace("-", "__")) + Array.append(info.command.name), + Array.map((command) => command.replace("-", "__")) ) - const underscoreName = ReadonlyArray.join(preformatted, "__") - const spaceName = ReadonlyArray.join(preformatted, " ") + const underscoreName = Array.join(preformatted, "__") + const spaceName = Array.join(preformatted, " ") const subcommands = pipe( info.subcommands, - ReadonlyArray.map(([name, subcommand]) => { + Array.map(([name, subcommand]) => { const desc = getShortDescription(subcommand) return `'${name}:${desc}' \\` }) ) - const commands = ReadonlyArray.isEmptyReadonlyArray(subcommands) + const commands = Array.isEmptyReadonlyArray(subcommands) ? `commands=()` - : `commands=(\n${ReadonlyArray.join(indentAll(subcommands, 8), "\n")}\n )` + : `commands=(\n${Array.join(indentAll(subcommands, 8), "\n")}\n )` const handlerLines = [ `(( $+functions[_${underscoreName}_commands] )) ||`, `_${underscoreName}_commands() {`, @@ -1223,10 +1223,10 @@ const getZshCompletionsInternal = ( ` _describe -t commands '${spaceName} commands' commands "$@"`, "}" ] - return Effect.succeed(ReadonlyArray.appendAll(state, handlerLines)) + return Effect.succeed(Array.appendAll(state, handlerLines)) }).pipe(Effect.map((handlers) => { - const rootCommand = ReadonlyArray.unsafeGet(getNamesInternal(self), 0) - const cases = getZshSubcommandCases(self, ReadonlyArray.empty(), ReadonlyArray.empty()) + const rootCommand = Array.unsafeGet(getNamesInternal(self), 0) + const cases = getZshSubcommandCases(self, Array.empty(), Array.empty()) const scriptName = `_${rootCommand}_zsh_completions` return [ `#compdef ${executable}`, @@ -1272,13 +1272,13 @@ const getZshSubcommandCases = ( const args = isStandard(self) ? self.args : InternalArgs.none const optionCompletions = pipe( InternalOptions.getZshCompletions(options as InternalOptions.Instruction), - ReadonlyArray.map((completion) => `'${completion}' \\`) + Array.map((completion) => `'${completion}' \\`) ) const argCompletions = pipe( InternalArgs.getZshCompletions(args as InternalArgs.Instruction), - ReadonlyArray.map((completion) => `'${completion}' \\`) + Array.map((completion) => `'${completion}' \\`) ) - if (ReadonlyArray.isEmptyReadonlyArray(parentCommands)) { + if (Array.isEmptyReadonlyArray(parentCommands)) { return [ "_arguments \"${_arguments_options[@]}\" \\", ...indentAll(optionCompletions, 4), @@ -1288,7 +1288,7 @@ const getZshSubcommandCases = ( " && ret=0" ] } - if (ReadonlyArray.isEmptyReadonlyArray(subcommands)) { + if (Array.isEmptyReadonlyArray(subcommands)) { return [ `(${self.name})`, "_arguments \"${_arguments_options[@]}\" \\", @@ -1303,7 +1303,7 @@ const getZshSubcommandCases = ( "_arguments \"${_arguments_options[@]}\" \\", ...indentAll(optionCompletions, 4), ...indentAll(argCompletions, 4), - ` ":: :_${ReadonlyArray.append(parentCommands, self.name).join("__")}_commands" \\`, + ` ":: :_${Array.append(parentCommands, self.name).join("__")}_commands" \\`, ` "*::: :->${self.name}" \\`, " && ret=0" ] @@ -1312,30 +1312,30 @@ const getZshSubcommandCases = ( return getZshSubcommandCases(self.command, parentCommands, subcommands) } case "Subcommands": { - const nextSubcommands = Array.from(getSubcommandsInternal(self)) - const parentNames = Array.from(getNamesInternal(self.parent)) + const nextSubcommands = getSubcommandsInternal(self) + const parentNames = getNamesInternal(self.parent) const parentLines = getZshSubcommandCases( self.parent, parentCommands, - ReadonlyArray.appendAll(subcommands, nextSubcommands) + Array.appendAll(subcommands, nextSubcommands) ) const childCases = pipe( self.children, - ReadonlyArray.flatMap((child) => + Array.flatMap((child) => getZshSubcommandCases( child, - ReadonlyArray.appendAll(parentCommands, parentNames), + Array.appendAll(parentCommands, parentNames), subcommands ) ) ) const hyphenName = pipe( - ReadonlyArray.appendAll(parentCommands, parentNames), - ReadonlyArray.join("-") + Array.appendAll(parentCommands, parentNames), + Array.join("-") ) const childLines = pipe( parentNames, - ReadonlyArray.flatMap((parentName) => [ + Array.flatMap((parentName) => [ "case $state in", ` (${parentName})`, ` words=($line[1] "\${words[@]}")`, @@ -1347,13 +1347,13 @@ const getZshSubcommandCases = ( " ;;", "esac" ]), - ReadonlyArray.appendAll( - ReadonlyArray.isEmptyReadonlyArray(parentCommands) - ? ReadonlyArray.empty() - : ReadonlyArray.of(";;") + Array.appendAll( + Array.isEmptyReadonlyArray(parentCommands) + ? Array.empty() + : Array.of(";;") ) ) - return ReadonlyArray.appendAll(parentLines, childLines) + return Array.appendAll(parentLines, childLines) } } } diff --git a/packages/cli/src/internal/helpDoc.ts b/packages/cli/src/internal/helpDoc.ts index 9ea4cfaace..1545e47e42 100644 --- a/packages/cli/src/internal/helpDoc.ts +++ b/packages/cli/src/internal/helpDoc.ts @@ -1,8 +1,8 @@ import * as Ansi from "@effect/printer-ansi/Ansi" import * as Doc from "@effect/printer-ansi/AnsiDoc" import * as Optimize from "@effect/printer/Optimize" +import * as Array from "effect/Array" import { dual, pipe } from "effect/Function" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as HelpDoc from "../HelpDoc.js" import type * as Span from "../HelpDoc/Span.js" import * as InternalSpan from "./helpDoc/span.js" @@ -58,8 +58,8 @@ export const orElse = dual< /** @internal */ export const blocks = (helpDocs: Iterable): HelpDoc.HelpDoc => { - const elements = ReadonlyArray.fromIterable(helpDocs) - if (ReadonlyArray.isNonEmptyReadonlyArray(elements)) { + const elements = Array.fromIterable(helpDocs) + if (Array.isNonEmptyReadonlyArray(elements)) { return elements.slice(1).reduce(sequence, elements[0]) } return empty @@ -71,7 +71,7 @@ export const getSpan = (self: HelpDoc.HelpDoc): Span.Span => /** @internal */ export const descriptionList = ( - definitions: ReadonlyArray.NonEmptyReadonlyArray<[Span.Span, HelpDoc.HelpDoc]> + definitions: Array.NonEmptyReadonlyArray<[Span.Span, HelpDoc.HelpDoc]> ): HelpDoc.HelpDoc => ({ _tag: "DescriptionList", definitions @@ -79,7 +79,7 @@ export const descriptionList = ( /** @internal */ export const enumeration = ( - elements: ReadonlyArray.NonEmptyReadonlyArray + elements: Array.NonEmptyReadonlyArray ): HelpDoc.HelpDoc => ({ _tag: "Enumeration", elements @@ -123,7 +123,7 @@ export const mapDescriptionList = dual< ) => HelpDoc.HelpDoc >(2, (self, f) => isDescriptionList(self) - ? descriptionList(ReadonlyArray.map(self.definitions, ([span, helpDoc]) => f(span, helpDoc))) + ? descriptionList(Array.map(self.definitions, ([span, helpDoc]) => f(span, helpDoc))) : self) /** @internal */ diff --git a/packages/cli/src/internal/helpDoc/span.ts b/packages/cli/src/internal/helpDoc/span.ts index 3a30ebcca0..65929e7594 100644 --- a/packages/cli/src/internal/helpDoc/span.ts +++ b/packages/cli/src/internal/helpDoc/span.ts @@ -1,8 +1,8 @@ import * as Ansi from "@effect/printer-ansi/Ansi" import * as Doc from "@effect/printer-ansi/AnsiDoc" import * as Color from "@effect/printer-ansi/Color" +import * as Array from "effect/Array" import { dual } from "effect/Function" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as Span from "../../HelpDoc/Span.js" /** @internal */ @@ -92,8 +92,8 @@ export const getText = (self: Span.Span): string => { /** @internal */ export const spans = (spans: Iterable): Span.Span => { - const elements = ReadonlyArray.fromIterable(spans) - if (ReadonlyArray.isNonEmptyReadonlyArray(elements)) { + const elements = Array.fromIterable(spans) + if (Array.isNonEmptyReadonlyArray(elements)) { return elements.slice(1).reduce(concat, elements[0]) } return empty diff --git a/packages/cli/src/internal/options.ts b/packages/cli/src/internal/options.ts index f6756fbd83..1510f9c214 100644 --- a/packages/cli/src/internal/options.ts +++ b/packages/cli/src/internal/options.ts @@ -3,6 +3,7 @@ import type * as Path from "@effect/platform/Path" import type * as Terminal from "@effect/platform/Terminal" import * as Schema from "@effect/schema/Schema" import * as TreeFormatter from "@effect/schema/TreeFormatter" +import * as Array from "effect/Array" import type * as Config from "effect/Config" import * as Console from "effect/Console" import * as Effect from "effect/Effect" @@ -12,7 +13,6 @@ import * as HashMap from "effect/HashMap" import * as Option from "effect/Option" import * as Order from "effect/Order" import { pipeArguments } from "effect/Pipeable" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import type * as Secret from "effect/Secret" import type * as CliConfig from "../CliConfig.js" @@ -193,7 +193,7 @@ export const all: < if (isOptions(arguments[0])) { return map(arguments[0], (x) => [x]) as any } else if (Array.isArray(arguments[0])) { - return allTupled(arguments[0]) as any + return allTupled(arguments[0] as Array) as any } else { const entries = Object.entries( arguments[0] as Readonly<{ [K: string]: Options.Options }> @@ -232,9 +232,9 @@ export const boolean = ( aliases, InternalPrimitive.boolean(Option.some(ifPresent)) ) - if (ReadonlyArray.isNonEmptyReadonlyArray(negationNames)) { - const head = ReadonlyArray.headNonEmpty(negationNames) - const tail = ReadonlyArray.tailNonEmpty(negationNames) + if (Array.isNonEmptyReadonlyArray(negationNames)) { + const head = Array.headNonEmpty(negationNames) + const tail = Array.tailNonEmpty(negationNames) const negationOption = makeSingle( head, tail, @@ -254,20 +254,19 @@ export const choice = >( choices: C ): Options.Options => { const primitive = InternalPrimitive.choice( - ReadonlyArray.map(choices, (choice) => [choice, choice]) + Array.map(choices, (choice) => [choice, choice]) ) - return makeSingle(name, ReadonlyArray.empty(), primitive) + return makeSingle(name, Array.empty(), primitive) } /** @internal */ export const choiceWithValue = >( name: string, choices: C -): Options.Options => makeSingle(name, ReadonlyArray.empty(), InternalPrimitive.choice(choices)) +): Options.Options => makeSingle(name, Array.empty(), InternalPrimitive.choice(choices)) /** @internal */ -export const date = (name: string): Options.Options => - makeSingle(name, ReadonlyArray.empty(), InternalPrimitive.date) +export const date = (name: string): Options.Options => makeSingle(name, Array.empty(), InternalPrimitive.date) /** @internal */ export const directory = ( @@ -276,7 +275,7 @@ export const directory = ( ): Options.Options => makeSingle( name, - ReadonlyArray.empty(), + Array.empty(), InternalPrimitive.path("directory", config?.exists ?? "either") ) @@ -287,7 +286,7 @@ export const file = ( ): Options.Options => makeSingle( name, - ReadonlyArray.empty(), + Array.empty(), InternalPrimitive.path("file", config?.exists ?? "either") ) @@ -348,19 +347,18 @@ export const filterMap = dual< }))) /** @internal */ -export const float = (name: string): Options.Options => - makeSingle(name, ReadonlyArray.empty(), InternalPrimitive.float) +export const float = (name: string): Options.Options => makeSingle(name, Array.empty(), InternalPrimitive.float) /** @internal */ export const integer = (name: string): Options.Options => - makeSingle(name, ReadonlyArray.empty(), InternalPrimitive.integer) + makeSingle(name, Array.empty(), InternalPrimitive.integer) /** @internal */ export const keyValueMap = ( option: string | Options.Options ): Options.Options> => { if (typeof option === "string") { - const single = makeSingle(option, ReadonlyArray.empty(), InternalPrimitive.text) + const single = makeSingle(option, Array.empty(), InternalPrimitive.text) return makeKeyValueMap(single as Single) } if (!isSingle(option as Instruction)) { @@ -379,11 +377,10 @@ export const none: Options.Options = (() => { /** @internal */ export const secret = (name: string): Options.Options => - makeSingle(name, ReadonlyArray.empty(), InternalPrimitive.secret) + makeSingle(name, Array.empty(), InternalPrimitive.secret) /** @internal */ -export const text = (name: string): Options.Options => - makeSingle(name, ReadonlyArray.empty(), InternalPrimitive.text) +export const text = (name: string): Options.Options => makeSingle(name, Array.empty(), InternalPrimitive.text) // ============================================================================= // Combinators @@ -395,14 +392,14 @@ export const atLeast = dual< (times: 0): (self: Options.Options) => Options.Options> ( times: number - ): (self: Options.Options) => Options.Options> + ): (self: Options.Options) => Options.Options> }, { (self: Options.Options, times: 0): Options.Options> ( self: Options.Options, times: number - ): Options.Options> + ): Options.Options> } >(2, (self, times) => makeVariadic(self, Option.some(times), Option.none()) as any) @@ -419,7 +416,7 @@ export const between = dual< ( min: number, max: number - ): (self: Options.Options) => Options.Options> + ): (self: Options.Options) => Options.Options> }, { (self: Options.Options, min: 0, max: number): Options.Options> @@ -427,7 +424,7 @@ export const between = dual< self: Options.Options, min: number, max: number - ): Options.Options> + ): Options.Options> } >(3, (self, min, max) => makeVariadic(self, Option.some(min), Option.some(max)) as any) @@ -573,7 +570,7 @@ export const withAlias = dual< (self: Options.Options, alias: string) => Options.Options >(2, (self, alias) => modifySingle(self as Instruction, (single) => { - const aliases = ReadonlyArray.append(single.aliases, alias) + const aliases = Array.append(single.aliases, alias) return makeSingle( single.name, aliases, @@ -697,7 +694,7 @@ const getHelpInternal = (self: Instruction): HelpDoc.HelpDoc => { return InternalHelpDoc.empty } case "Single": { - return InternalHelpDoc.descriptionList(ReadonlyArray.of([ + return InternalHelpDoc.descriptionList(Array.of([ InternalHelpDoc.getSpan(InternalUsage.getHelp(getUsageInternal(self))), InternalHelpDoc.sequence( InternalHelpDoc.p(InternalPrimitive.getHelp(self.primitiveType)), @@ -798,13 +795,13 @@ const getIdentifierInternal = (self: Instruction): Option.Option => { } case "Both": case "OrElse": { - const ids = ReadonlyArray.getSomes([ + const ids = Array.getSomes([ getIdentifierInternal(self.left as Instruction), getIdentifierInternal(self.right as Instruction) ]) - return ReadonlyArray.match(ids, { + return Array.match(ids, { onEmpty: () => Option.none(), - onNonEmpty: (ids) => Option.some(ReadonlyArray.join(ids, ", ")) + onNonEmpty: (ids) => Option.some(Array.join(ids, ", ")) }) } case "KeyValueMap": @@ -1088,10 +1085,10 @@ export const getNames = (self: Instruction): Array => { const loop = (self: Instruction): ReadonlyArray => { switch (self._tag) { case "Empty": { - return ReadonlyArray.empty() + return Array.empty() } case "Single": { - return ReadonlyArray.prepend(self.aliases, self.name) + return Array.prepend(self.aliases, self.name) } case "KeyValueMap": case "Variadic": { @@ -1106,7 +1103,7 @@ export const getNames = (self: Instruction): Array => { case "OrElse": { const left = loop(self.left as Instruction) const right = loop(self.right as Instruction) - return ReadonlyArray.appendAll(left, right) + return Array.appendAll(left, right) } } } @@ -1116,21 +1113,21 @@ export const getNames = (self: Instruction): Array => { ) return pipe( loop(self), - ReadonlyArray.map((str) => makeFullName(str)), - ReadonlyArray.sort(order), - ReadonlyArray.map((tuple) => tuple[1]) + Array.map((str) => makeFullName(str)), + Array.sort(order), + Array.map((tuple) => tuple[1]) ) } const toParseableInstruction = (self: Instruction): Array => { switch (self._tag) { case "Empty": { - return ReadonlyArray.empty() + return Array.empty() } case "Single": case "KeyValueMap": case "Variadic": { - return ReadonlyArray.of(self) + return Array.of(self) } case "Map": case "WithDefault": @@ -1139,7 +1136,7 @@ const toParseableInstruction = (self: Instruction): Array } case "Both": case "OrElse": { - return ReadonlyArray.appendAll( + return Array.appendAll( toParseableInstruction(self.left as Instruction), toParseableInstruction(self.right as Instruction) ) @@ -1161,21 +1158,21 @@ const parseInternal = ( return Effect.void } case "Single": { - const singleNames = ReadonlyArray.filterMap(getNames(self), (name) => HashMap.get(args, name)) - if (ReadonlyArray.isNonEmptyReadonlyArray(singleNames)) { - const head = ReadonlyArray.headNonEmpty(singleNames) - const tail = ReadonlyArray.tailNonEmpty(singleNames) - if (ReadonlyArray.isEmptyReadonlyArray(tail)) { - if (ReadonlyArray.isEmptyReadonlyArray(head)) { + const singleNames = Array.filterMap(getNames(self), (name) => HashMap.get(args, name)) + if (Array.isNonEmptyReadonlyArray(singleNames)) { + const head = Array.headNonEmpty(singleNames) + const tail = Array.tailNonEmpty(singleNames) + if (Array.isEmptyReadonlyArray(tail)) { + if (Array.isEmptyReadonlyArray(head)) { return InternalPrimitive.validate(self.primitiveType, Option.none(), config).pipe( Effect.mapError((e) => InternalValidationError.invalidValue(InternalHelpDoc.p(e))) ) } if ( - ReadonlyArray.isNonEmptyReadonlyArray(head) && - ReadonlyArray.isEmptyReadonlyArray(ReadonlyArray.tailNonEmpty(head)) + Array.isNonEmptyReadonlyArray(head) && + Array.isEmptyReadonlyArray(Array.tailNonEmpty(head)) ) { - const value = ReadonlyArray.headNonEmpty(head) + const value = Array.headNonEmpty(head) return InternalPrimitive.validate(self.primitiveType, Option.some(value), config).pipe( Effect.mapError((e) => InternalValidationError.invalidValue(InternalHelpDoc.p(e))) ) @@ -1197,7 +1194,7 @@ const parseInternal = ( value: string ): Effect.Effect<[string, string], ValidationError.ValidationError> => { const split = value.trim().split("=") - if (ReadonlyArray.isNonEmptyReadonlyArray(split) && split.length === 2 && split[1] !== "") { + if (Array.isNonEmptyReadonlyArray(split) && split.length === 2 && split[1] !== "") { return Effect.succeed(split as unknown as [string, string]) } const error = InternalHelpDoc.p(`Expected a key/value pair but received '${value}'`) @@ -1279,7 +1276,7 @@ const parseInternal = ( case "Variadic": { const min = Option.getOrElse(self.min, () => 0) const max = Option.getOrElse(self.max, () => Number.MAX_SAFE_INTEGER) - const matchedArgument = ReadonlyArray.filterMap(getNames(self), (name) => HashMap.get(args, name)) + const matchedArgument = Array.filterMap(getNames(self), (name) => HashMap.get(args, name)) const validateMinMax = (values: ReadonlyArray) => { if (values.length < min) { const name = self.argumentOption.fullName @@ -1300,15 +1297,15 @@ const parseInternal = ( } // If we did not receive any variadic arguments then perform the bounds // checks with an empty array - if (ReadonlyArray.every(matchedArgument, ReadonlyArray.isEmptyReadonlyArray)) { - return validateMinMax(ReadonlyArray.empty()) + if (Array.every(matchedArgument, Array.isEmptyReadonlyArray)) { + return validateMinMax(Array.empty()) } return parseInternal(self.argumentOption, args, config).pipe(Effect.matchEffect({ onFailure: (error) => InternalValidationError.isMultipleValuesDetected(error) ? validateMinMax(error.values) : Effect.fail(error), - onSuccess: (value) => validateMinMax(ReadonlyArray.of(value as string)) + onSuccess: (value) => validateMinMax(Array.of(value as string)) })) } case "WithDefault": { @@ -1334,14 +1331,14 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. > => { switch (self._tag) { case "Empty": { - return Effect.succeed(ReadonlyArray.empty()) + return Effect.succeed(Array.empty()) } case "Single": { const help = getHelpInternal(self) return InternalPrimitive.wizard(self.primitiveType, help).pipe( Effect.flatMap((input) => { // There will always be at least one name in names - const args = ReadonlyArray.make(getNames(self)[0]!, input as string) + const args = Array.make(getNames(self)[0]!, input as string) return parseCommandLine(self, args, config).pipe(Effect.as(args)) }), Effect.zipLeft(Console.log()) @@ -1356,7 +1353,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. Effect.flatMap((args) => { const identifier = Option.getOrElse(getIdentifierInternal(self), () => "") return parseInternal(self, HashMap.make([identifier, args]), config).pipe( - Effect.as(ReadonlyArray.prepend(args, identifier)) + Effect.as(Array.prepend(args, identifier)) ) }), Effect.zipLeft(Console.log()) @@ -1369,7 +1366,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. return Effect.zipWith( wizardInternal(self.left as Instruction, config), wizardInternal(self.right as Instruction, config), - (left, right) => ReadonlyArray.appendAll(left, right) + (left, right) => Array.appendAll(left, right) ) } case "OrElse": { @@ -1379,7 +1376,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. InternalHelpDoc.sequence(alternativeHelp) ) const makeChoice = (title: string, value: Instruction) => ({ title, value }) - const choices = ReadonlyArray.getSomes([ + const choices = Array.getSomes([ Option.map( getIdentifierInternal(self.left as Instruction), (title) => makeChoice(title, self.left as Instruction) @@ -1409,11 +1406,11 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. }).pipe( Effect.flatMap((n) => n <= 0 - ? Effect.succeed(ReadonlyArray.empty()) - : Ref.make(ReadonlyArray.empty()).pipe( + ? Effect.succeed(Array.empty()) + : Ref.make(Array.empty()).pipe( Effect.flatMap((ref) => wizardInternal(self.argumentOption as Instruction, config).pipe( - Effect.flatMap((args) => Ref.update(ref, ReadonlyArray.appendAll(args))), + Effect.flatMap((args) => Ref.update(ref, Array.appendAll(args))), Effect.repeatN(n - 1), Effect.zipRight(Ref.get(ref)) ) @@ -1441,7 +1438,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. Effect.zipLeft(Console.log()), Effect.flatMap((useFallback) => useFallback - ? Effect.succeed(ReadonlyArray.empty()) + ? Effect.succeed(Array.empty()) : wizardInternal(self.options as Instruction, config) ) ) @@ -1465,7 +1462,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. Effect.zipLeft(Console.log()), Effect.flatMap((useFallback) => useFallback - ? Effect.succeed(ReadonlyArray.empty()) + ? Effect.succeed(Array.empty()) : wizardInternal(self.options as Instruction, config) ) ) @@ -1492,7 +1489,7 @@ const matchOptions = ( HashMap.HashMap> ] > => { - if (ReadonlyArray.isNonEmptyReadonlyArray(options)) { + if (Array.isNonEmptyReadonlyArray(options)) { return findOptions(input, options, config).pipe( Effect.flatMap(([otherArgs, otherOptions, map1]) => { if (HashMap.isEmpty(map1)) { @@ -1504,7 +1501,7 @@ const matchOptions = ( } return matchOptions(otherArgs, otherOptions, config).pipe( Effect.map(([error, otherArgs, map2]) => - [error, otherArgs, merge(map1, ReadonlyArray.fromIterable(map2))] as [ + [error, otherArgs, merge(map1, Array.fromIterable(map2))] as [ Option.Option, ReadonlyArray, HashMap.HashMap> @@ -1521,8 +1518,8 @@ const matchOptions = ( ) ) } - return ReadonlyArray.isEmptyReadonlyArray(input) - ? Effect.succeed([Option.none(), ReadonlyArray.empty(), HashMap.empty()] as [ + return Array.isEmptyReadonlyArray(input) + ? Effect.succeed([Option.none(), Array.empty(), HashMap.empty()] as [ Option.Option, ReadonlyArray, HashMap.HashMap> @@ -1550,15 +1547,15 @@ const findOptions = ( ], ValidationError.ValidationError > => - ReadonlyArray.matchLeft(options, { - onEmpty: () => Effect.succeed([input, ReadonlyArray.empty(), HashMap.empty()]), + Array.matchLeft(options, { + onEmpty: () => Effect.succeed([input, Array.empty(), HashMap.empty()]), onNonEmpty: (head, tail) => parseCommandLine(head, input, config).pipe( Effect.flatMap(({ leftover, parsed }) => Option.match(parsed, { onNone: () => findOptions(leftover, tail, config).pipe(Effect.map(([nextArgs, nextOptions, map]) => - [nextArgs, ReadonlyArray.prepend(nextOptions, head), map] as [ + [nextArgs, Array.prepend(nextOptions, head), map] as [ ReadonlyArray, ReadonlyArray, HashMap.HashMap> @@ -1579,7 +1576,7 @@ const findOptions = ( Effect.flatMap(([otherArgs, otherOptions, map]) => Effect.fail(e).pipe( Effect.when(() => HashMap.isEmpty(map)), - Effect.as([otherArgs, ReadonlyArray.prepend(otherOptions, head), map] as [ + Effect.as([otherArgs, Array.prepend(otherOptions, head), map] as [ ReadonlyArray, ReadonlyArray, HashMap.HashMap> @@ -1590,7 +1587,7 @@ const findOptions = ( MissingFlag: () => findOptions(input, tail, config).pipe( Effect.map(([otherArgs, otherOptions, map]) => - [otherArgs, ReadonlyArray.prepend(otherOptions, head), map] as [ + [otherArgs, Array.prepend(otherOptions, head), map] as [ ReadonlyArray, ReadonlyArray, HashMap.HashMap> @@ -1628,8 +1625,8 @@ const FLAG_REGEX = /^(--[^=]+)(?:=(.+))?$/ const processArgs = ( args: ReadonlyArray ): Effect.Effect, ValidationError.ValidationError> => - ReadonlyArray.matchLeft(args, { - onEmpty: () => Effect.succeed(ReadonlyArray.empty()), + Array.matchLeft(args, { + onEmpty: () => Effect.succeed(Array.empty()), onNonEmpty: (head, tail) => { const value = head.trim() // Attempt to match clustered short command-line arguments (i.e. `-abc`) @@ -1647,7 +1644,7 @@ const processArgs = ( const result = FLAG_REGEX.exec(value) if (result !== null && result[2] !== undefined) { return Effect.succeed>( - ReadonlyArray.appendAll([result[1], result[2]], tail) + Array.appendAll([result[1], result[2]], tail) ) } } @@ -1670,7 +1667,7 @@ const parseCommandLine = ( switch (self._tag) { case "Single": { return processArgs(args).pipe(Effect.flatMap((args) => - ReadonlyArray.matchLeft(args, { + Array.matchLeft(args, { onEmpty: () => { const error = InternalHelpDoc.p(`Expected to find option: '${self.fullName}'`) return Effect.fail(InternalValidationError.missingFlag(error)) @@ -1678,29 +1675,29 @@ const parseCommandLine = ( onNonEmpty: (head, tail) => { const normalize = (value: string) => InternalCliConfig.normalizeCase(config, value) const normalizedHead = normalize(head) - const normalizedNames = ReadonlyArray.map(getNames(self), (name) => normalize(name)) - if (ReadonlyArray.contains(normalizedNames, normalizedHead)) { + const normalizedNames = Array.map(getNames(self), (name) => normalize(name)) + if (Array.contains(normalizedNames, normalizedHead)) { if (InternalPrimitive.isBool(self.primitiveType)) { - return ReadonlyArray.matchLeft(tail, { + return Array.matchLeft(tail, { onEmpty: () => { - const parsed = Option.some({ name: head, values: ReadonlyArray.empty() }) + const parsed = Option.some({ name: head, values: Array.empty() }) return Effect.succeed({ parsed, leftover: tail }) }, onNonEmpty: (value, leftover) => { if (InternalPrimitive.isTrueValue(value)) { - const parsed = Option.some({ name: head, values: ReadonlyArray.of("true") }) + const parsed = Option.some({ name: head, values: Array.of("true") }) return Effect.succeed({ parsed, leftover }) } if (InternalPrimitive.isFalseValue(value)) { - const parsed = Option.some({ name: head, values: ReadonlyArray.of("false") }) + const parsed = Option.some({ name: head, values: Array.of("false") }) return Effect.succeed({ parsed, leftover }) } - const parsed = Option.some({ name: head, values: ReadonlyArray.empty() }) + const parsed = Option.some({ name: head, values: Array.empty() }) return Effect.succeed({ parsed, leftover: tail }) } }) } - return ReadonlyArray.matchLeft(tail, { + return Array.matchLeft(tail, { onEmpty: () => { const error = InternalHelpDoc.p( `Expected a value following option: '${self.fullName}'` @@ -1708,7 +1705,7 @@ const parseCommandLine = ( return Effect.fail(InternalValidationError.missingValue(error)) }, onNonEmpty: (value, leftover) => { - const parsed = Option.some({ name: head, values: ReadonlyArray.of(value) }) + const parsed = Option.some({ name: head, values: Array.of(value) }) return Effect.succeed({ parsed, leftover }) } }) @@ -1730,27 +1727,27 @@ const parseCommandLine = ( )) } case "KeyValueMap": { - const normalizedNames = ReadonlyArray.map( + const normalizedNames = Array.map( getNames(self.argumentOption), (name) => InternalCliConfig.normalizeCase(config, name) ) - return ReadonlyArray.matchLeft(args, { + return Array.matchLeft(args, { onEmpty: () => Effect.succeed({ parsed: Option.none(), leftover: args }), onNonEmpty: (head, tail) => { const loop = ( args: ReadonlyArray ): [ReadonlyArray, ReadonlyArray] => { - let keyValues = ReadonlyArray.empty() + let keyValues = Array.empty() let leftover = args as ReadonlyArray - while (ReadonlyArray.isNonEmptyReadonlyArray(leftover)) { - const name = ReadonlyArray.headNonEmpty(leftover).trim() + while (Array.isNonEmptyReadonlyArray(leftover)) { + const name = Array.headNonEmpty(leftover).trim() const normalizedName = InternalCliConfig.normalizeCase(config, name) // Can be in the form of "--flag key1=value1 --flag key2=value2" - if (leftover.length >= 2 && ReadonlyArray.contains(normalizedNames, normalizedName)) { + if (leftover.length >= 2 && Array.contains(normalizedNames, normalizedName)) { const keyValue = leftover[1].trim() const [key, value] = keyValue.split("=") if (key !== undefined && value !== undefined && value.length > 0) { - keyValues = ReadonlyArray.append(keyValues, keyValue) + keyValues = Array.append(keyValues, keyValue) leftover = leftover.slice(2) continue } @@ -1759,7 +1756,7 @@ const parseCommandLine = ( if (name.includes("=")) { const [key, value] = name.split("=") if (key !== undefined && value !== undefined && value.length > 0) { - keyValues = ReadonlyArray.append(keyValues, name) + keyValues = Array.append(keyValues, name) leftover = leftover.slice(1) continue } @@ -1769,7 +1766,7 @@ const parseCommandLine = ( return [keyValues, leftover] } const normalizedName = InternalCliConfig.normalizeCase(config, head) - if (ReadonlyArray.contains(normalizedNames, normalizedName)) { + if (Array.contains(normalizedNames, normalizedName)) { const [values, leftover] = loop(tail) return Effect.succeed({ parsed: Option.some({ name: head, values }), leftover }) } @@ -1778,23 +1775,23 @@ const parseCommandLine = ( }) } case "Variadic": { - const normalizedNames = ReadonlyArray.map( + const normalizedNames = Array.map( getNames(self.argumentOption), (name) => InternalCliConfig.normalizeCase(config, name) ) let optionName: string | undefined = undefined - let values = ReadonlyArray.empty() + let values = Array.empty() let leftover = args as ReadonlyArray - while (ReadonlyArray.isNonEmptyReadonlyArray(leftover)) { - const name = ReadonlyArray.headNonEmpty(leftover) + while (Array.isNonEmptyReadonlyArray(leftover)) { + const name = Array.headNonEmpty(leftover) const normalizedName = InternalCliConfig.normalizeCase(config, name) - if (leftover.length >= 2 && ReadonlyArray.contains(normalizedNames, normalizedName)) { + if (leftover.length >= 2 && Array.contains(normalizedNames, normalizedName)) { if (optionName === undefined) { optionName = name } const value = leftover[1] if (value !== undefined && value.length > 0) { - values = ReadonlyArray.append(values, value.trim()) + values = Array.append(values, value.trim()) leftover = leftover.slice(2) continue } @@ -1825,16 +1822,16 @@ const matchUnclustered = ( ], ValidationError.ValidationError > => { - if (ReadonlyArray.isNonEmptyReadonlyArray(input)) { - const flag = ReadonlyArray.headNonEmpty(input) - const otherFlags = ReadonlyArray.tailNonEmpty(input) - return findOptions(ReadonlyArray.of(flag), options, config).pipe( + if (Array.isNonEmptyReadonlyArray(input)) { + const flag = Array.headNonEmpty(input) + const otherFlags = Array.tailNonEmpty(input) + return findOptions(Array.of(flag), options, config).pipe( Effect.flatMap(([_, opts1, map1]) => { if (HashMap.isEmpty(map1)) { return Effect.fail( InternalValidationError.unclusteredFlag( InternalHelpDoc.empty, - ReadonlyArray.empty(), + Array.empty(), tail ) ) @@ -1842,7 +1839,7 @@ const matchUnclustered = ( return matchUnclustered(otherFlags, tail, opts1, config).pipe( Effect.map(( [_, opts2, map2] - ) => [tail, opts2, merge(map1, ReadonlyArray.fromIterable(map2))]) + ) => [tail, opts2, merge(map1, Array.fromIterable(map2))]) ) }) ) @@ -1857,12 +1854,12 @@ const merge = ( map1: HashMap.HashMap>, map2: ReadonlyArray<[string, ReadonlyArray]> ): HashMap.HashMap> => { - if (ReadonlyArray.isNonEmptyReadonlyArray(map2)) { - const head = ReadonlyArray.headNonEmpty(map2) - const tail = ReadonlyArray.tailNonEmpty(map2) + if (Array.isNonEmptyReadonlyArray(map2)) { + const head = Array.headNonEmpty(map2) + const tail = Array.tailNonEmpty(map2) const newMap = Option.match(HashMap.get(map1, head[0]), { onNone: () => HashMap.set(map1, head[0], head[1]), - onSome: (elems) => HashMap.set(map1, head[0], ReadonlyArray.appendAll(elems, head[1])) + onSome: (elems) => HashMap.set(map1, head[0], Array.appendAll(elems, head[1])) }) return merge(newMap, tail) } @@ -1911,15 +1908,15 @@ const getShortDescription = (self: Instruction): string => { export const getBashCompletions = (self: Instruction): ReadonlyArray => { switch (self._tag) { case "Empty": { - return ReadonlyArray.empty() + return Array.empty() } case "Single": { const names = getNames(self) - const cases = ReadonlyArray.join(names, "|") + const cases = Array.join(names, "|") const compgen = InternalPrimitive.getBashCompletions( self.primitiveType as InternalPrimitive.Instruction ) - return ReadonlyArray.make( + return Array.make( `${cases})`, ` COMPREPLY=( ${compgen} )`, ` return 0`, @@ -1939,7 +1936,7 @@ export const getBashCompletions = (self: Instruction): ReadonlyArray => case "OrElse": { const left = getBashCompletions(self.left as Instruction) const right = getBashCompletions(self.right as Instruction) - return ReadonlyArray.appendAll(left, right) + return Array.appendAll(left, right) } } } @@ -1948,26 +1945,26 @@ export const getBashCompletions = (self: Instruction): ReadonlyArray => export const getFishCompletions = (self: Instruction): Array => { switch (self._tag) { case "Empty": { - return ReadonlyArray.empty() + return Array.empty() } case "Single": { const description = getShortDescription(self) const order = Order.mapInput(Order.boolean, (tuple: readonly [boolean, string]) => !tuple[0]) return pipe( - ReadonlyArray.prepend(self.aliases, self.name), - ReadonlyArray.map((name) => [name.length === 1, name] as const), - ReadonlyArray.sort(order), - ReadonlyArray.flatMap(([isShort, name]) => ReadonlyArray.make(isShort ? "-s" : "-l", name)), - ReadonlyArray.appendAll(InternalPrimitive.getFishCompletions( + Array.prepend(self.aliases, self.name), + Array.map((name) => [name.length === 1, name] as const), + Array.sort(order), + Array.flatMap(([isShort, name]) => Array.make(isShort ? "-s" : "-l", name)), + Array.appendAll(InternalPrimitive.getFishCompletions( self.primitiveType as InternalPrimitive.Instruction )), - ReadonlyArray.appendAll( + Array.appendAll( description.length === 0 - ? ReadonlyArray.empty() - : ReadonlyArray.of(`-d '${description}'`) + ? Array.empty() + : Array.of(`-d '${description}'`) ), - ReadonlyArray.join(" "), - ReadonlyArray.of + Array.join(" "), + Array.of ) } case "KeyValueMap": @@ -1983,7 +1980,7 @@ export const getFishCompletions = (self: Instruction): Array => { case "OrElse": { return pipe( getFishCompletions(self.left as Instruction), - ReadonlyArray.appendAll(getFishCompletions(self.right as Instruction)) + Array.appendAll(getFishCompletions(self.right as Instruction)) ) } } @@ -1997,11 +1994,11 @@ interface ZshCompletionState { /** @internal */ export const getZshCompletions = ( self: Instruction, - state: ZshCompletionState = { conflicts: ReadonlyArray.empty(), multiple: false } + state: ZshCompletionState = { conflicts: Array.empty(), multiple: false } ): Array => { switch (self._tag) { case "Empty": { - return ReadonlyArray.empty() + return Array.empty() } case "Single": { const names = getNames(self) @@ -2010,10 +2007,10 @@ export const getZshCompletions = ( self.primitiveType as InternalPrimitive.Instruction ) const multiple = state.multiple ? "*" : "" - const conflicts = ReadonlyArray.isNonEmptyReadonlyArray(state.conflicts) - ? `(${ReadonlyArray.join(state.conflicts, " ")})` + const conflicts = Array.isNonEmptyReadonlyArray(state.conflicts) + ? `(${Array.join(state.conflicts, " ")})` : "" - return ReadonlyArray.map( + return Array.map( names, (name) => `${conflicts}${multiple}${name}[${escape(description)}]${possibleValues}` ) @@ -2029,20 +2026,20 @@ export const getZshCompletions = ( case "Both": { const left = getZshCompletions(self.left as Instruction, state) const right = getZshCompletions(self.right as Instruction, state) - return ReadonlyArray.appendAll(left, right) + return Array.appendAll(left, right) } case "OrElse": { const leftNames = getNames(self.left as Instruction) const rightNames = getNames(self.right as Instruction) const left = getZshCompletions( self.left as Instruction, - { ...state, conflicts: ReadonlyArray.appendAll(state.conflicts, rightNames) } + { ...state, conflicts: Array.appendAll(state.conflicts, rightNames) } ) const right = getZshCompletions( self.right as Instruction, - { ...state, conflicts: ReadonlyArray.appendAll(state.conflicts, leftNames) } + { ...state, conflicts: Array.appendAll(state.conflicts, leftNames) } ) - return ReadonlyArray.appendAll(left, right) + return Array.appendAll(left, right) } case "Variadic": { return Option.isSome(self.max) && self.max.value > 1 diff --git a/packages/cli/src/internal/primitive.ts b/packages/cli/src/internal/primitive.ts index 2599734634..72a0286ada 100644 --- a/packages/cli/src/internal/primitive.ts +++ b/packages/cli/src/internal/primitive.ts @@ -1,10 +1,10 @@ import * as FileSystem from "@effect/platform/FileSystem" import * as Schema from "@effect/schema/Schema" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { dual, pipe } from "effect/Function" import * as Option from "effect/Option" import { pipeArguments } from "effect/Pipeable" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as EffectSecret from "effect/Secret" import type * as CliConfig from "../CliConfig.js" import type * as HelpDoc from "../HelpDoc.js" @@ -258,8 +258,8 @@ const getChoicesInternal = (self: Instruction): Option.Option => { } case "Choice": { const choices = pipe( - ReadonlyArray.map(self.alternatives, ([choice]) => choice), - ReadonlyArray.join(" | ") + Array.map(self.alternatives, ([choice]) => choice), + Array.join(" | ") ) return Option.some(choices) } @@ -283,8 +283,8 @@ const getHelpInternal = (self: Instruction): Span.Span => { } case "Choice": { const choices = pipe( - ReadonlyArray.map(self.alternatives, ([choice]) => choice), - ReadonlyArray.join(", ") + Array.map(self.alternatives, ([choice]) => choice), + Array.join(", ") ) return InternalSpan.text(`One of the following: ${choices}`) } @@ -401,12 +401,12 @@ const validateInternal = ( value, () => `Choice options to not have a default value` ).pipe( - Effect.flatMap((value) => ReadonlyArray.findFirst(self.alternatives, ([choice]) => choice === value)), + Effect.flatMap((value) => Array.findFirst(self.alternatives, ([choice]) => choice === value)), Effect.mapBoth({ onFailure: () => { const choices = pipe( - ReadonlyArray.map(self.alternatives, ([choice]) => choice), - ReadonlyArray.join(", ") + Array.map(self.alternatives, ([choice]) => choice), + Array.join(", ") ) return `Expected one of the following cases: ${choices}` }, @@ -536,7 +536,7 @@ const wizardInternal = (self: Instruction, help: HelpDoc.HelpDoc): Prompt.Prompt const message = InternalHelpDoc.sequence(help, primitiveHelp) return InternalSelectPrompt.select({ message: InternalHelpDoc.toAnsiText(message).trimEnd(), - choices: ReadonlyArray.map( + choices: Array.map( self.alternatives, ([title]) => ({ title, value: title }) ) @@ -625,8 +625,8 @@ export const getBashCompletions = (self: Instruction): string => { } case "Choice": { const choices = pipe( - ReadonlyArray.map(self.alternatives, ([choice]) => choice), - ReadonlyArray.join(",") + Array.map(self.alternatives, ([choice]) => choice), + Array.join(",") ) return `$(compgen -W "${choices}" -- "\${cur}")` } @@ -637,45 +637,45 @@ export const getBashCompletions = (self: Instruction): string => { export const getFishCompletions = (self: Instruction): Array => { switch (self._tag) { case "Bool": { - return ReadonlyArray.empty() + return Array.empty() } case "DateTime": case "Float": case "Integer": case "Secret": case "Text": { - return ReadonlyArray.make("-r", "-f") + return Array.make("-r", "-f") } case "Path": { switch (self.pathType) { case "file": { return self.pathExists === "yes" || self.pathExists === "either" - ? ReadonlyArray.make("-r", "-F") - : ReadonlyArray.make("-r") + ? Array.make("-r", "-F") + : Array.make("-r") } case "directory": { return self.pathExists === "yes" || self.pathExists === "either" - ? ReadonlyArray.make( + ? Array.make( "-r", "-f", "-a", `"(__fish_complete_directories (commandline -ct))"` ) - : ReadonlyArray.make("-r") + : Array.make("-r") } case "either": { return self.pathExists === "yes" || self.pathExists === "either" - ? ReadonlyArray.make("-r", "-F") - : ReadonlyArray.make("-r") + ? Array.make("-r", "-F") + : Array.make("-r") } } } case "Choice": { const choices = pipe( - ReadonlyArray.map(self.alternatives, ([choice]) => `${choice}''`), - ReadonlyArray.join(",") + Array.map(self.alternatives, ([choice]) => `${choice}''`), + Array.join(",") ) - return ReadonlyArray.make("-r", "-f", "-a", `"{${choices}}"`) + return Array.make("-r", "-f", "-a", `"{${choices}}"`) } } } @@ -688,8 +688,8 @@ export const getZshCompletions = (self: Instruction): string => { } case "Choice": { const choices = pipe( - ReadonlyArray.map(self.alternatives, ([name]) => name), - ReadonlyArray.join(" ") + Array.map(self.alternatives, ([name]) => name), + Array.join(" ") ) return `:CHOICE:(${choices})` } diff --git a/packages/cli/src/internal/prompt/ansi-utils.ts b/packages/cli/src/internal/prompt/ansi-utils.ts index 24186e3003..0f7a9af0af 100644 --- a/packages/cli/src/internal/prompt/ansi-utils.ts +++ b/packages/cli/src/internal/prompt/ansi-utils.ts @@ -1,7 +1,7 @@ import * as Doc from "@effect/printer-ansi/AnsiDoc" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" -import * as ReadonlyArray from "effect/ReadonlyArray" const defaultFigures = { arrowUp: Doc.text("↑"), @@ -62,7 +62,7 @@ export const lines = (prompt: string, columns: number): number => { return columns === 0 ? lines.length : pipe( - ReadonlyArray.map(lines, (line) => Math.ceil(line.length / columns)), - ReadonlyArray.reduce(0, (left, right) => left + right) + Array.map(lines, (line) => Math.ceil(line.length / columns)), + Array.reduce(0, (left, right) => left + right) ) } diff --git a/packages/cli/src/internal/prompt/confirm.ts b/packages/cli/src/internal/prompt/confirm.ts index d95ee29390..08fa5bee68 100644 --- a/packages/cli/src/internal/prompt/confirm.ts +++ b/packages/cli/src/internal/prompt/confirm.ts @@ -2,10 +2,10 @@ import * as Terminal from "@effect/platform/Terminal" import * as Ansi from "@effect/printer-ansi/Ansi" import * as Doc from "@effect/printer-ansi/AnsiDoc" import * as Optimize from "@effect/printer/Optimize" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as Prompt from "../../Prompt.js" import type * as PromptAction from "../../Prompt/Action.js" import * as InternalPrompt from "../prompt.js" @@ -39,10 +39,10 @@ const renderOutput = ( ): Doc.AnsiDoc => { const annotateLine = (line: string): Doc.AnsiDoc => pipe(Doc.text(line), Doc.annotate(Ansi.bold)) const prefix = Doc.cat(leadingSymbol, Doc.space) - return ReadonlyArray.match(options.message.split(/\r?\n/), { + return Array.match(options.message.split(/\r?\n/), { onEmpty: () => Doc.hsep([prefix, trailingSymbol, confirm]), onNonEmpty: (promptLines) => { - const lines = ReadonlyArray.map(promptLines, (line) => annotateLine(line)) + const lines = Array.map(promptLines, (line) => annotateLine(line)) return pipe( prefix, Doc.cat(Doc.nest(Doc.vsep(lines), 2)), diff --git a/packages/cli/src/internal/prompt/date.ts b/packages/cli/src/internal/prompt/date.ts index 9c770776a1..34baa3bd3b 100644 --- a/packages/cli/src/internal/prompt/date.ts +++ b/packages/cli/src/internal/prompt/date.ts @@ -2,11 +2,11 @@ import * as Terminal from "@effect/platform/Terminal" import * as Ansi from "@effect/printer-ansi/Ansi" import * as Doc from "@effect/printer-ansi/AnsiDoc" import * as Optimize from "@effect/printer/Optimize" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Match from "effect/Match" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as Prompt from "../../Prompt.js" import * as InternalPrompt from "../prompt.js" import * as InternalPromptAction from "./action.js" @@ -48,11 +48,11 @@ const renderError = (nextState: State, pointer: Doc.AnsiDoc): Doc.AnsiDoc => onNone: () => Doc.empty, onSome: (error) => { const errorLines = error.split(/\r?\n/) - if (ReadonlyArray.isNonEmptyReadonlyArray(errorLines)) { + if (Array.isNonEmptyReadonlyArray(errorLines)) { const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.combine(Ansi.italicized, Ansi.red)) const prefix = Doc.cat(Doc.annotate(pointer, Ansi.red), Doc.space) - const lines = ReadonlyArray.map(errorLines, (str) => annotateLine(str)) + const lines = Array.map(errorLines, (str) => annotateLine(str)) return pipe( Doc.cursorSavePosition, Doc.cat(Doc.hardLine), @@ -66,7 +66,7 @@ const renderError = (nextState: State, pointer: Doc.AnsiDoc): Doc.AnsiDoc => }) const renderParts = (nextState: State, submitted: boolean = false) => - ReadonlyArray.reduce( + Array.reduce( nextState.dateParts, Doc.empty as Doc.AnsiDoc, (doc, part, currentIndex) => { @@ -87,10 +87,10 @@ const renderOutput = ( ): Doc.AnsiDoc => { const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold) const prefix = Doc.cat(leadingSymbol, Doc.space) - return ReadonlyArray.match(options.message.split(/\r?\n/), { + return Array.match(options.message.split(/\r?\n/), { onEmpty: () => Doc.hsep([prefix, trailingSymbol, parts]), onNonEmpty: (promptLines) => { - const lines = ReadonlyArray.map(promptLines, (line) => annotateLine(line)) + const lines = Array.map(promptLines, (line) => annotateLine(line)) return pipe( prefix, Doc.cat(Doc.nest(Doc.vsep(lines), 2)), @@ -348,7 +348,7 @@ const makeDateParts = ( array.push(element) } return array - }, ReadonlyArray.empty()) + }, Array.empty()) parts.splice(0, parts.length, ...orderedParts) return parts } @@ -400,9 +400,9 @@ abstract class DatePart { */ nextPart(): Option.Option { return pipe( - ReadonlyArray.findFirstIndex(this.parts, (part) => part === this), + Array.findFirstIndex(this.parts, (part) => part === this), Option.flatMap((currentPartIndex) => - ReadonlyArray.findFirst(this.parts.slice(currentPartIndex + 1), (part) => !part.isToken()) + Array.findFirst(this.parts.slice(currentPartIndex + 1), (part) => !part.isToken()) ) ) } @@ -412,9 +412,9 @@ abstract class DatePart { */ previousPart(): Option.Option { return pipe( - ReadonlyArray.findFirstIndex(this.parts, (part) => part === this), + Array.findFirstIndex(this.parts, (part) => part === this), Option.flatMap((currentPartIndex) => - ReadonlyArray.findLast(this.parts.slice(0, currentPartIndex), (part) => !part.isToken()) + Array.findLast(this.parts.slice(0, currentPartIndex), (part) => !part.isToken()) ) ) } diff --git a/packages/cli/src/internal/prompt/number.ts b/packages/cli/src/internal/prompt/number.ts index 6aa31bec1b..24aa08bf2c 100644 --- a/packages/cli/src/internal/prompt/number.ts +++ b/packages/cli/src/internal/prompt/number.ts @@ -3,10 +3,10 @@ import * as Ansi from "@effect/printer-ansi/Ansi" import * as Doc from "@effect/printer-ansi/AnsiDoc" import * as Optimize from "@effect/printer/Optimize" import * as Schema from "@effect/schema/Schema" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as Prompt from "../../Prompt.js" import type * as PromptAction from "../../Prompt/Action.js" import * as InternalPrompt from "../prompt.js" @@ -67,13 +67,13 @@ const renderError = (nextState: State, pointer: Doc.AnsiDoc): Doc.AnsiDoc => Option.match(nextState.error, { onNone: () => Doc.empty, onSome: (error) => - ReadonlyArray.match(error.split(/\r?\n/), { + Array.match(error.split(/\r?\n/), { onEmpty: () => Doc.empty, onNonEmpty: (errorLines) => { const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.combine(Ansi.italicized, Ansi.red)) const prefix = Doc.cat(Doc.annotate(pointer, Ansi.red), Doc.space) - const lines = ReadonlyArray.map(errorLines, (str) => annotateLine(str)) + const lines = Array.map(errorLines, (str) => annotateLine(str)) return pipe( Doc.cursorSavePosition, Doc.cat(Doc.hardLine), @@ -94,10 +94,10 @@ const renderOutput = ( ): Doc.AnsiDoc => { const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold) const prefix = Doc.cat(leadingSymbol, Doc.space) - return ReadonlyArray.match(options.message.split(/\r?\n/), { + return Array.match(options.message.split(/\r?\n/), { onEmpty: () => Doc.hsep([prefix, trailingSymbol, renderInput(nextState, submitted)]), onNonEmpty: (promptLines) => { - const lines = ReadonlyArray.map(promptLines, (line) => annotateLine(line)) + const lines = Array.map(promptLines, (line) => annotateLine(line)) return pipe( prefix, Doc.cat(Doc.nest(Doc.vsep(lines), 2)), diff --git a/packages/cli/src/internal/prompt/select.ts b/packages/cli/src/internal/prompt/select.ts index 23a570b882..9120c2c0ab 100644 --- a/packages/cli/src/internal/prompt/select.ts +++ b/packages/cli/src/internal/prompt/select.ts @@ -1,10 +1,10 @@ import * as Terminal from "@effect/platform/Terminal" import * as Ansi from "@effect/printer-ansi/Ansi" import * as Doc from "@effect/printer-ansi/AnsiDoc" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as Prompt from "../../Prompt.js" import * as InternalPrompt from "../prompt.js" import * as InternalPromptAction from "./action.js" @@ -93,7 +93,7 @@ const renderChoices = ( const choices = options.choices const toDisplay = entriesToDisplay(nextState.cursor, choices.length, options.maxPerPage) const choicesToRender = choices.slice(toDisplay.startIndex, toDisplay.endIndex) - const docs = ReadonlyArray.map(choicesToRender, (choice, currentIndex) => { + const docs = Array.map(choicesToRender, (choice, currentIndex) => { const prefix = renderChoicePrefix(nextState, choicesToRender, toDisplay, currentIndex, figures) const title = renderChoiceTitle(choice, nextState.cursor === currentIndex) const description = renderChoiceDescription(choice, nextState.cursor === currentIndex) @@ -109,10 +109,10 @@ const renderOutput = ( ): Doc.AnsiDoc => { const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold) const prefix = Doc.cat(leadingSymbol, Doc.space) - return ReadonlyArray.match(options.message.split(/\r?\n/), { + return Array.match(options.message.split(/\r?\n/), { onEmpty: () => Doc.hsep([prefix, trailingSymbol]), onNonEmpty: (promptLines) => { - const lines = ReadonlyArray.map(promptLines, (line) => annotateLine(line)) + const lines = Array.map(promptLines, (line) => annotateLine(line)) return pipe( prefix, Doc.cat(Doc.nest(Doc.vsep(lines), 2)), diff --git a/packages/cli/src/internal/prompt/text.ts b/packages/cli/src/internal/prompt/text.ts index e632f0dac8..f2fad7a793 100644 --- a/packages/cli/src/internal/prompt/text.ts +++ b/packages/cli/src/internal/prompt/text.ts @@ -2,10 +2,10 @@ import * as Terminal from "@effect/platform/Terminal" import * as Ansi from "@effect/printer-ansi/Ansi" import * as Doc from "@effect/printer-ansi/AnsiDoc" import * as Optimize from "@effect/printer/Optimize" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Secret from "effect/Secret" import type * as Prompt from "../../Prompt.js" import * as InternalPrompt from "../prompt.js" @@ -86,7 +86,7 @@ const renderError = (nextState: State, pointer: Doc.AnsiDoc): Doc.AnsiDoc => Option.match(nextState.error, { onNone: () => Doc.empty, onSome: (error) => - ReadonlyArray.match(error.split(/\r?\n/), { + Array.match(error.split(/\r?\n/), { onEmpty: () => Doc.empty, onNonEmpty: (errorLines) => { const annotateLine = (line: string): Doc.AnsiDoc => @@ -95,7 +95,7 @@ const renderError = (nextState: State, pointer: Doc.AnsiDoc): Doc.AnsiDoc => Doc.annotate(Ansi.combine(Ansi.italicized, Ansi.red)) ) const prefix = Doc.cat(Doc.annotate(pointer, Ansi.red), Doc.space) - const lines = ReadonlyArray.map(errorLines, (str) => annotateLine(str)) + const lines = Array.map(errorLines, (str) => annotateLine(str)) return pipe( Doc.cursorSavePosition, Doc.cat(Doc.hardLine), @@ -117,8 +117,8 @@ const renderOutput = ( const annotateLine = (line: string): Doc.AnsiDoc => pipe(Doc.text(line), Doc.annotate(Ansi.bold)) const promptLines = options.message.split(/\r?\n/) const prefix = Doc.cat(leadingSymbol, Doc.space) - if (ReadonlyArray.isNonEmptyReadonlyArray(promptLines)) { - const lines = ReadonlyArray.map(promptLines, (line) => annotateLine(line)) + if (Array.isNonEmptyReadonlyArray(promptLines)) { + const lines = Array.map(promptLines, (line) => annotateLine(line)) return pipe( prefix, Doc.cat(Doc.nest(Doc.vsep(lines), 2)), diff --git a/packages/cli/src/internal/prompt/toggle.ts b/packages/cli/src/internal/prompt/toggle.ts index 8062ce323b..c514386cee 100644 --- a/packages/cli/src/internal/prompt/toggle.ts +++ b/packages/cli/src/internal/prompt/toggle.ts @@ -2,10 +2,10 @@ import * as Terminal from "@effect/platform/Terminal" import * as Ansi from "@effect/printer-ansi/Ansi" import * as Doc from "@effect/printer-ansi/AnsiDoc" import * as Optimize from "@effect/printer/Optimize" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as Prompt from "../../Prompt.js" import * as InternalPrompt from "../prompt.js" import * as InternalPromptAction from "./action.js" @@ -55,8 +55,8 @@ const renderOutput = ( const annotateLine = (line: string): Doc.AnsiDoc => pipe(Doc.text(line), Doc.annotate(Ansi.bold)) const promptLines = options.message.split(/\r?\n/) const prefix = Doc.cat(leadingSymbol, Doc.space) - if (ReadonlyArray.isNonEmptyReadonlyArray(promptLines)) { - const lines = ReadonlyArray.map(promptLines, (line) => annotateLine(line)) + if (Array.isNonEmptyReadonlyArray(promptLines)) { + const lines = Array.map(promptLines, (line) => annotateLine(line)) return pipe( prefix, Doc.cat(Doc.nest(Doc.vsep(lines), 2)), diff --git a/packages/cli/src/internal/usage.ts b/packages/cli/src/internal/usage.ts index ef7111a8e1..86050940c8 100644 --- a/packages/cli/src/internal/usage.ts +++ b/packages/cli/src/internal/usage.ts @@ -1,6 +1,6 @@ +import * as Array from "effect/Array" import { dual, pipe } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as CliConfig from "../CliConfig.js" import type * as HelpDoc from "../HelpDoc.js" import type * as Span from "../HelpDoc/Span.js" @@ -71,13 +71,13 @@ export const concat = dual< /** @internal */ export const getHelp = (self: Usage.Usage): HelpDoc.HelpDoc => { const spans = enumerate(self, InternalCliConfig.defaultConfig) - if (ReadonlyArray.isNonEmptyReadonlyArray(spans)) { - const head = ReadonlyArray.headNonEmpty(spans) - const tail = ReadonlyArray.tailNonEmpty(spans) - if (ReadonlyArray.isNonEmptyReadonlyArray(tail)) { + if (Array.isNonEmptyReadonlyArray(spans)) { + const head = Array.headNonEmpty(spans) + const tail = Array.tailNonEmpty(spans) + if (Array.isNonEmptyReadonlyArray(tail)) { return pipe( - ReadonlyArray.map(spans, (span) => InternalHelpDoc.p(span)), - ReadonlyArray.reduceRight( + Array.map(spans, (span) => InternalHelpDoc.p(span)), + Array.reduceRight( InternalHelpDoc.empty, (left, right) => InternalHelpDoc.sequence(left, right) ) @@ -107,7 +107,7 @@ const simplify = (self: Usage.Usage, config: CliConfig.CliConfig): Usage.Usage = return mixed } case "Named": { - if (Option.isNone(ReadonlyArray.head(render(self, config)))) { + if (Option.isNone(Array.head(render(self, config)))) { return empty } return self @@ -153,10 +153,10 @@ const simplify = (self: Usage.Usage, config: CliConfig.CliConfig): Usage.Usage = const render = (self: Usage.Usage, config: CliConfig.CliConfig): Array => { switch (self._tag) { case "Empty": { - return ReadonlyArray.of(InternalSpan.text("")) + return Array.of(InternalSpan.text("")) } case "Mixed": { - return ReadonlyArray.of(InternalSpan.text("")) + return Array.of(InternalSpan.text("")) } case "Named": { const typeInfo = config.showTypes @@ -169,24 +169,24 @@ const render = (self: Usage.Usage, config: CliConfig.CliConfig): Array 1 ? pipe( - ReadonlyArray.filter(self.names, (name) => name.startsWith("--")), - ReadonlyArray.head, - Option.map(ReadonlyArray.of), + Array.filter(self.names, (name) => name.startsWith("--")), + Array.head, + Option.map(Array.of), Option.getOrElse(() => self.names) ) : self.names - const nameInfo = InternalSpan.text(ReadonlyArray.join(namesToShow, ", ")) + const nameInfo = InternalSpan.text(Array.join(namesToShow, ", ")) return config.showAllNames && self.names.length > 1 - ? ReadonlyArray.of(InternalSpan.spans([ + ? Array.of(InternalSpan.spans([ InternalSpan.text("("), nameInfo, typeInfo, InternalSpan.text(")") ])) - : ReadonlyArray.of(InternalSpan.concat(nameInfo, typeInfo)) + : Array.of(InternalSpan.concat(nameInfo, typeInfo)) } case "Optional": { - return ReadonlyArray.map(render(self.usage, config), (span) => + return Array.map(render(self.usage, config), (span) => InternalSpan.spans([ InternalSpan.text("["), span, @@ -194,7 +194,7 @@ const render = (self: Usage.Usage, config: CliConfig.CliConfig): Array InternalSpan.concat(span, InternalSpan.text("...")) ) @@ -206,15 +206,15 @@ const render = (self: Usage.Usage, config: CliConfig.CliConfig): Array - ReadonlyArray.map( + Array.map( render(self.right, config), (right) => InternalSpan.spans([left, InternalSpan.text("|"), right]) ) @@ -223,13 +223,13 @@ const render = (self: Usage.Usage, config: CliConfig.CliConfig): Array ReadonlyArray.map(rightSpan, (right) => InternalSpan.spans([left, separator, right])) + (left) => Array.map(rightSpan, (right) => InternalSpan.spans([left, separator, right])) ) } } diff --git a/packages/cli/test/Args.test.ts b/packages/cli/test/Args.test.ts index 61640aaaa0..05cb07efd3 100644 --- a/packages/cli/test/Args.test.ts +++ b/packages/cli/test/Args.test.ts @@ -5,9 +5,9 @@ import * as ValidationError from "@effect/cli/ValidationError" import { FileSystem, Path } from "@effect/platform" import { NodeContext } from "@effect/platform-node" import * as Schema from "@effect/schema/Schema" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import { describe, expect, it } from "vitest" const runEffect = ( @@ -19,30 +19,30 @@ describe("Args", () => { Effect.gen(function*(_) { const args = Args.integer().pipe(Args.withDefault(0)) const result = yield* _( - Args.validate(args, ReadonlyArray.empty(), CliConfig.defaultConfig) + Args.validate(args, Array.empty(), CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), 0]) + expect(result).toEqual([Array.empty(), 0]) }).pipe(runEffect)) it("validates an valid optional argument", () => Effect.gen(function*(_) { const args = Args.integer().pipe(Args.optional) let result = yield* _( - Args.validate(args, ReadonlyArray.empty(), CliConfig.defaultConfig) + Args.validate(args, Array.empty(), CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), Option.none()]) + expect(result).toEqual([Array.empty(), Option.none()]) result = yield* _( Args.validate(args, ["123"], CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), Option.some(123)]) + expect(result).toEqual([Array.empty(), Option.some(123)]) }).pipe(runEffect)) it("does not validate an invalid argument even when there is a default", () => Effect.gen(function*(_) { const args = Args.integer().pipe(Args.withDefault(0)) const result = yield* _(Effect.flip( - Args.validate(args, ReadonlyArray.of("abc"), CliConfig.defaultConfig) + Args.validate(args, Array.of("abc"), CliConfig.defaultConfig) )) expect(result).toEqual(ValidationError.invalidArgument(HelpDoc.p("'abc' is not a integer"))) }).pipe(runEffect)) @@ -53,9 +53,9 @@ describe("Args", () => { const filePath = path.join(__dirname, "Args.test.ts") const args = Args.file({ name: "files", exists: "yes" }).pipe(Args.repeated) const result = yield* _( - Args.validate(args, ReadonlyArray.of(filePath), CliConfig.defaultConfig) + Args.validate(args, Array.of(filePath), CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), ReadonlyArray.of(filePath)]) + expect(result).toEqual([Array.empty(), Array.of(filePath)]) }).pipe(runEffect)) it("should return an error when a file that is expected to exist is not found", () => @@ -64,7 +64,7 @@ describe("Args", () => { const filePath = path.join(__dirname, "NotExist.test.ts") const args = Args.file({ name: "files", exists: "yes" }).pipe(Args.repeated) const result = yield* _( - Effect.flip(Args.validate(args, ReadonlyArray.of(filePath), CliConfig.defaultConfig)) + Effect.flip(Args.validate(args, Array.of(filePath), CliConfig.defaultConfig)) ) expect(result).toEqual(ValidationError.invalidArgument(HelpDoc.p( `Path '${filePath}' must exist` @@ -77,9 +77,9 @@ describe("Args", () => { const filePath = path.join(__dirname, "NotExist.test.ts") const args = Args.file({ name: "files", exists: "no" }).pipe(Args.repeated) const result = yield* _( - Args.validate(args, ReadonlyArray.of(filePath), CliConfig.defaultConfig) + Args.validate(args, Array.of(filePath), CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), ReadonlyArray.of(filePath)]) + expect(result).toEqual([Array.empty(), Array.of(filePath)]) }).pipe(runEffect)) it("should validate a series of files", () => @@ -88,9 +88,9 @@ describe("Args", () => { const filePath = path.join(__dirname, "NotExist.test.ts") const args = Args.file({ name: "files", exists: "no" }).pipe(Args.repeated) const result = yield* _( - Args.validate(args, ReadonlyArray.make(filePath, filePath), CliConfig.defaultConfig) + Args.validate(args, Array.make(filePath, filePath), CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), ReadonlyArray.make(filePath, filePath)]) + expect(result).toEqual([Array.empty(), Array.make(filePath, filePath)]) }).pipe(runEffect)) it("validates an valid argument with a Schema", () => @@ -99,14 +99,14 @@ describe("Args", () => { const result = yield* _( Args.validate(args, ["123"], CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), 123]) + expect(result).toEqual([Array.empty(), 123]) }).pipe(runEffect)) it("does not validate an invalid argument with a Schema", () => Effect.gen(function*(_) { const args = Args.integer().pipe(Args.withSchema(Schema.Positive)) const result = yield* _(Effect.flip( - Args.validate(args, ReadonlyArray.of("-123"), CliConfig.defaultConfig) + Args.validate(args, Array.of("-123"), CliConfig.defaultConfig) )) expect(result).toEqual(ValidationError.invalidArgument(HelpDoc.p( "Positive\n" + @@ -123,9 +123,9 @@ describe("Args", () => { const content = yield* _(fs.readFile(filePath)) const args = Args.fileContent({ name: "files" }).pipe(Args.repeated) const result = yield* _( - Args.validate(args, ReadonlyArray.of(filePath), CliConfig.defaultConfig) + Args.validate(args, Array.of(filePath), CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), ReadonlyArray.of([filePath, content])]) + expect(result).toEqual([Array.empty(), Array.of([filePath, content])]) }).pipe(runEffect)) it("fileText", () => @@ -136,9 +136,9 @@ describe("Args", () => { const content = yield* _(fs.readFileString(filePath)) const args = Args.fileText({ name: "files" }).pipe(Args.repeated) const result = yield* _( - Args.validate(args, ReadonlyArray.of(filePath), CliConfig.defaultConfig) + Args.validate(args, Array.of(filePath), CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), ReadonlyArray.of([filePath, content])]) + expect(result).toEqual([Array.empty(), Array.of([filePath, content])]) }).pipe(runEffect)) it("fileParse", () => @@ -149,9 +149,9 @@ describe("Args", () => { const content = yield* _(fs.readFileString(filePath), Effect.map(JSON.parse)) const args = Args.fileParse({ name: "files" }).pipe(Args.repeated) const result = yield* _( - Args.validate(args, ReadonlyArray.of(filePath), CliConfig.defaultConfig) + Args.validate(args, Array.of(filePath), CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), ReadonlyArray.of(content)]) + expect(result).toEqual([Array.empty(), Array.of(content)]) }).pipe(runEffect)) it("fileSchema", () => @@ -168,8 +168,8 @@ describe("Args", () => { { name: "files" } ).pipe(Args.repeated) const result = yield* _( - Args.validate(args, ReadonlyArray.of(filePath), CliConfig.defaultConfig) + Args.validate(args, Array.of(filePath), CliConfig.defaultConfig) ) - expect(result).toEqual([ReadonlyArray.empty(), ReadonlyArray.of(content)]) + expect(result).toEqual([Array.empty(), Array.of(content)]) }).pipe(runEffect)) }) diff --git a/packages/cli/test/CliApp.test.ts b/packages/cli/test/CliApp.test.ts index c6663ef236..c034ce88ba 100644 --- a/packages/cli/test/CliApp.test.ts +++ b/packages/cli/test/CliApp.test.ts @@ -3,7 +3,7 @@ import * as Command from "@effect/cli/Command" import * as HelpDoc from "@effect/cli/HelpDoc" import * as ValidationError from "@effect/cli/ValidationError" import { NodeContext } from "@effect/platform-node" -import { Effect, ReadonlyArray } from "effect" +import { Array, Effect } from "effect" import { describe, expect, it } from "vitest" const runEffect = ( @@ -20,7 +20,7 @@ describe("CliApp", () => { name: "Test", version: "1.0.0" }) - const args = ReadonlyArray.make("node", "test.js", "--bar") + const args = Array.make("node", "test.js", "--bar") const result = yield* _(Effect.flip(cli(args))) expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p( "Received unknown argument: '--bar'" diff --git a/packages/cli/test/CommandDescriptor.test.ts b/packages/cli/test/CommandDescriptor.test.ts index b727c41063..000fb44a17 100644 --- a/packages/cli/test/CommandDescriptor.test.ts +++ b/packages/cli/test/CommandDescriptor.test.ts @@ -11,7 +11,7 @@ import * as WordCount from "@effect/cli/test/utils/wc" import * as ValidationError from "@effect/cli/ValidationError" import * as NodeContext from "@effect/platform-node/NodeContext" import * as Doc from "@effect/printer/Doc" -import { Effect, Option, ReadonlyArray, String } from "effect" +import { Array, Effect, Option, String } from "effect" import { describe, expect, it } from "vitest" const runEffect = ( @@ -25,21 +25,21 @@ describe("Command", () => { describe("Standard Commands", () => { it("should validate a command with options followed by arguments", () => Effect.gen(function*(_) { - const args1 = ReadonlyArray.make("tail", "-n", "100", "foo.log") - const args2 = ReadonlyArray.make("grep", "--after", "2", "--before", "3", "fooBar") + const args1 = Array.make("tail", "-n", "100", "foo.log") + const args2 = Array.make("grep", "--after", "2", "--before", "3", "fooBar") const result1 = yield* _(Descriptor.parse(Tail.command, args1, CliConfig.defaultConfig)) const result2 = yield* _(Descriptor.parse(Grep.command, args2, CliConfig.defaultConfig)) const expected1 = { name: "tail", options: 100, args: "foo.log" } const expected2 = { name: "grep", options: [2, 3], args: "fooBar" } - expect(result1).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected1)) - expect(result2).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected2)) + expect(result1).toEqual(CommandDirective.userDefined(Array.empty(), expected1)) + expect(result2).toEqual(CommandDirective.userDefined(Array.empty(), expected2)) }).pipe(runEffect)) it("should provide auto-correct suggestions for misspelled options", () => Effect.gen(function*(_) { - const args1 = ReadonlyArray.make("grep", "--afte", "2", "--before", "3", "fooBar") - const args2 = ReadonlyArray.make("grep", "--after", "2", "--efore", "3", "fooBar") - const args3 = ReadonlyArray.make("grep", "--afte", "2", "--efore", "3", "fooBar") + const args1 = Array.make("grep", "--afte", "2", "--before", "3", "fooBar") + const args2 = Array.make("grep", "--after", "2", "--efore", "3", "fooBar") + const args3 = Array.make("grep", "--afte", "2", "--efore", "3", "fooBar") const result1 = yield* _( Effect.flip(Descriptor.parse(Grep.command, args1, CliConfig.defaultConfig)) ) @@ -62,7 +62,7 @@ describe("Command", () => { it("should return an error if an option is missing", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("grep", "--a", "2", "--before", "3", "fooBar") + const args = Array.make("grep", "--a", "2", "--before", "3", "fooBar") const result = yield* _( Effect.flip(Descriptor.parse(Grep.command, args, CliConfig.defaultConfig)) ) @@ -76,8 +76,8 @@ describe("Command", () => { describe("Commands with Clustered Options", () => { it("should treat clustered boolean options as un-clustered options", () => Effect.gen(function*(_) { - const args1 = ReadonlyArray.make("wc", "-clw", "filename") - const args2 = ReadonlyArray.make("wc", "-c", "-l", "-w", "filename") + const args1 = Array.make("wc", "-clw", "filename") + const args2 = Array.make("wc", "-c", "-l", "-w", "filename") const result1 = yield* _( Descriptor.parse(WordCount.command, args1, CliConfig.defaultConfig) ) @@ -85,24 +85,24 @@ describe("Command", () => { Descriptor.parse(WordCount.command, args2, CliConfig.defaultConfig) ) const expected = { name: "wc", options: [true, true, true, true], args: ["filename"] } - expect(result1).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected)) - expect(result2).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected)) + expect(result1).toEqual(CommandDirective.userDefined(Array.empty(), expected)) + expect(result2).toEqual(CommandDirective.userDefined(Array.empty(), expected)) }).pipe(runEffect)) it("should not uncluster wrong clusters", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("wc", "-clk") + const args = Array.make("wc", "-clk") const result = yield* _(Descriptor.parse(WordCount.command, args, CliConfig.defaultConfig)) const expected = { name: "wc", options: [false, false, false, true], args: ["-clk"] } - expect(result).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected)) + expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected)) }).pipe(runEffect)) it("should not alter '-'", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("wc", "-") + const args = Array.make("wc", "-") const result = yield* _(Descriptor.parse(WordCount.command, args, CliConfig.defaultConfig)) const expected = { name: "wc", options: [false, false, false, true], args: ["-"] } - expect(result).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected)) + expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected)) }).pipe(runEffect)) }) @@ -116,7 +116,7 @@ describe("Command", () => { it("should match the top-level command if no subcommands are specified", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("git", "-v") + const args = Array.make("git", "-v") const result = yield* _(Descriptor.parse(git, args, CliConfig.defaultConfig)) const expected = { name: "git", options: true, args: void 0, subcommand: Option.none() } expect(result).toEqual(CommandDirective.userDefined([], expected)) @@ -124,7 +124,7 @@ describe("Command", () => { it("should match the first subcommand without any surplus arguments", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("git", "remote") + const args = Array.make("git", "remote") const result = yield* _(Descriptor.parse(git, args, CliConfig.defaultConfig)) const expected = { name: "git", @@ -132,12 +132,12 @@ describe("Command", () => { args: void 0, subcommand: Option.some(["remote", { name: "remote", options: void 0, args: void 0 }]) } - expect(result).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected)) + expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected)) }).pipe(runEffect)) it("matches the first subcommand with a surplus option", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("git", "remote", "-v") + const args = Array.make("git", "remote", "-v") const result = yield* _(Descriptor.parse(git, args, CliConfig.defaultConfig)) const expected = { name: "git", @@ -145,12 +145,12 @@ describe("Command", () => { args: void 0, subcommand: Option.some(["remote", { name: "remote", options: void 0, args: void 0 }]) } - expect(result).toEqual(CommandDirective.userDefined(ReadonlyArray.of("-v"), expected)) + expect(result).toEqual(CommandDirective.userDefined(Array.of("-v"), expected)) }).pipe(runEffect)) it("matches the second subcommand without any surplus arguments", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("git", "log") + const args = Array.make("git", "log") const result = yield* _(Descriptor.parse(git, args, CliConfig.defaultConfig)) const expected = { name: "git", @@ -158,12 +158,12 @@ describe("Command", () => { args: void 0, subcommand: Option.some(["log", { name: "log", options: void 0, args: void 0 }]) } - expect(result).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected)) + expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected)) }).pipe(runEffect)) it("should return an error message for an unknown subcommand", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("git", "abc") + const args = Array.make("git", "abc") const result = yield* _(Effect.flip(Descriptor.parse(git, args, CliConfig.defaultConfig))) expect(result).toEqual(ValidationError.commandMismatch(HelpDoc.p( "Invalid subcommand for git - use one of 'remote', 'log'" @@ -185,7 +185,7 @@ describe("Command", () => { it("should parse a subcommand with required options and arguments", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("git", "rebase", "-i", "upstream", "branch") + const args = Array.make("git", "rebase", "-i", "upstream", "branch") const result = yield* _(Descriptor.parse(git, args, CliConfig.defaultConfig)) const expected = { name: "git", @@ -197,12 +197,12 @@ describe("Command", () => { args: ["upstream", "branch"] }]) } - expect(result).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected)) + expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected)) }).pipe(runEffect)) it("should parse a subcommand with required and optional options and arguments", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make( + const args = Array.make( "git", "rebase", "-i", @@ -222,7 +222,7 @@ describe("Command", () => { args: ["upstream", "branch"] }]) } - expect(result).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected)) + expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected)) }).pipe(runEffect)) }) @@ -238,7 +238,7 @@ describe("Command", () => { it("should properly parse deeply nested subcommands with options and arguments", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("command", "sub", "subsub", "-i", "text") + const args = Array.make("command", "sub", "subsub", "-i", "text") const result = yield* _(Descriptor.parse(command, args, CliConfig.defaultConfig)) const expected = { name: "command", @@ -255,7 +255,7 @@ describe("Command", () => { }]) }]) } - expect(result).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected)) + expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected)) }).pipe(runEffect)) }) @@ -264,14 +264,14 @@ describe("Command", () => { Effect.gen(function*(_) { const config = CliConfig.make({ showBuiltIns: false }) const cmd = Descriptor.make("tldr").pipe(Descriptor.withDescription("this is some help")) - const args = ReadonlyArray.of("tldr") + const args = Array.of("tldr") const result = yield* _(Descriptor.parse(cmd, args, CliConfig.defaultConfig)) const expectedValue = { name: "tldr", options: void 0, args: void 0 } const expectedDoc = HelpDoc.sequence( HelpDoc.h1("DESCRIPTION"), HelpDoc.p("this is some help") ) - expect(result).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expectedValue)) + expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expectedValue)) expect(Descriptor.getHelp(cmd, config)).toEqual(expectedDoc) }).pipe(runEffect)) @@ -313,14 +313,14 @@ describe("Command", () => { describe("Built-In Options Processing", () => { const command = Descriptor.make("command", Options.text("a")) - const params1 = ReadonlyArray.make("command", "--help") - const params2 = ReadonlyArray.make("command", "-h") - const params3 = ReadonlyArray.make("command", "--wizard") - const params4 = ReadonlyArray.make("command", "--completions", "sh") - const params5 = ReadonlyArray.make("command", "-a", "--help") - const params6 = ReadonlyArray.make("command", "--help", "--wizard", "-b") - const params7 = ReadonlyArray.make("command", "-hdf", "--help") - const params8 = ReadonlyArray.make("command", "-af", "asdgf", "--wizard") + const params1 = Array.make("command", "--help") + const params2 = Array.make("command", "-h") + const params3 = Array.make("command", "--wizard") + const params4 = Array.make("command", "--completions", "sh") + const params5 = Array.make("command", "-a", "--help") + const params6 = Array.make("command", "--help", "--wizard", "-b") + const params7 = Array.make("command", "-hdf", "--help") + const params8 = Array.make("command", "-af", "asdgf", "--wizard") const directiveType = (directive: CommandDirective.CommandDirective): string => { if (CommandDirective.isBuiltIn(directive)) { @@ -408,30 +408,30 @@ describe("Command", () => { it("should properly handle the end of command options symbol", () => Effect.gen(function*(_) { - const args1 = ReadonlyArray.make("cmd", "-v", "--something", "abc", "something") - const args2 = ReadonlyArray.make("cmd", "-v", "--", "--something", "abc", "something") - const args3 = ReadonlyArray.make("cmd", "--", "-v", "--something", "abc", "something") + const args1 = Array.make("cmd", "-v", "--something", "abc", "something") + const args2 = Array.make("cmd", "-v", "--", "--something", "abc", "something") + const args3 = Array.make("cmd", "--", "-v", "--something", "abc", "something") const result1 = yield* _(Descriptor.parse(command, args1, CliConfig.defaultConfig)) const result2 = yield* _(Descriptor.parse(command, args2, CliConfig.defaultConfig)) const result3 = yield* _(Descriptor.parse(command, args3, CliConfig.defaultConfig)) const expected1 = { name: "cmd", options: [Option.some("abc"), true], - args: ReadonlyArray.of("something") + args: Array.of("something") } const expected2 = { name: "cmd", options: [Option.none(), true], - args: ReadonlyArray.make("--something", "abc", "something") + args: Array.make("--something", "abc", "something") } const expected3 = { name: "cmd", options: [Option.none(), false], - args: ReadonlyArray.make("-v", "--something", "abc", "something") + args: Array.make("-v", "--something", "abc", "something") } - expect(result1).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected1)) - expect(result2).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected2)) - expect(result3).toEqual(CommandDirective.userDefined(ReadonlyArray.empty(), expected3)) + expect(result1).toEqual(CommandDirective.userDefined(Array.empty(), expected1)) + expect(result2).toEqual(CommandDirective.userDefined(Array.empty(), expected2)) + expect(result3).toEqual(CommandDirective.userDefined(Array.empty(), expected3)) }).pipe(runEffect)) }) diff --git a/packages/cli/test/Options.test.ts b/packages/cli/test/Options.test.ts index 1d10e20a9a..96cfb955fa 100644 --- a/packages/cli/test/Options.test.ts +++ b/packages/cli/test/Options.test.ts @@ -7,13 +7,13 @@ import * as FileSystem from "@effect/platform/FileSystem" import * as Path from "@effect/platform/Path" import * as Schema from "@effect/schema/Schema" import { BigDecimal } from "effect" +import * as Array from "effect/Array" import * as Data from "effect/Data" import * as Effect from "effect/Effect" import * as Either from "effect/Either" import { identity } from "effect/Function" import * as HashMap from "effect/HashMap" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import { assert, describe, expect, it } from "vitest" const firstName = Options.text("firstName").pipe(Options.withAlias("f")) @@ -49,30 +49,30 @@ const process = ( describe("Options", () => { it("should validate without ambiguity", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--firstName", "--lastName", "--lastName", "--firstName") + const args = Array.make("--firstName", "--lastName", "--lastName", "--firstName") const result1 = yield* _( process(Options.all([firstName, lastName]), args, CliConfig.defaultConfig) ) const result2 = yield* _( process(Options.all([lastName, firstName]), args, CliConfig.defaultConfig) ) - const expected1 = [ReadonlyArray.empty(), ReadonlyArray.make("--lastName", "--firstName")] - const expected2 = [ReadonlyArray.empty(), ReadonlyArray.make("--firstName", "--lastName")] + const expected1 = [Array.empty(), Array.make("--lastName", "--firstName")] + const expected2 = [Array.empty(), Array.make("--firstName", "--lastName")] expect(result1).toEqual(expected1) expect(result2).toEqual(expected2) }).pipe(runEffect)) it("should not uncluster values", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--firstName", "-ab") + const args = Array.make("--firstName", "-ab") const result = yield* _(process(firstName, args, CliConfig.defaultConfig)) - const expected = [ReadonlyArray.empty(), "-ab"] + const expected = [Array.empty(), "-ab"] expect(result).toEqual(expected) }).pipe(runEffect)) it("should return a HelpDoc if an option is not an exact match and it's a short option", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--ag", "20") + const args = Array.make("--ag", "20") const result = yield* _(Effect.flip(process(age, args, CliConfig.defaultConfig))) expect(result).toEqual(ValidationError.missingValue(HelpDoc.p( "Expected to find option: '--age'" @@ -85,7 +85,7 @@ describe("Options", () => { Options.text("a").pipe(Options.map(identity)), Options.text("b").pipe(Options.map(identity)) ) - const args = ReadonlyArray.make("-a", "a", "-b", "b") + const args = Array.make("-a", "a", "-b", "b") const result = yield* _(Effect.flip(process(options, args, CliConfig.defaultConfig))) expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p( "Collision between two options detected - you can only " + @@ -95,24 +95,24 @@ describe("Options", () => { it("validates a boolean option without a value", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--verbose") + const args = Array.make("--verbose") const result = yield* _(process(verbose, args, CliConfig.defaultConfig)) - const expected = [ReadonlyArray.empty(), true] + const expected = [Array.empty(), true] expect(result).toEqual(expected) }).pipe(runEffect)) it("validates a boolean option with a followup option", () => Effect.gen(function*(_) { const options = Options.all([Options.boolean("help"), Options.boolean("v")]) - const args1 = ReadonlyArray.empty() - const args2 = ReadonlyArray.make("--help") - const args3 = ReadonlyArray.make("--help", "-v") + const args1 = Array.empty() + const args2 = Array.make("--help") + const args3 = Array.make("--help", "-v") const result1 = yield* _(process(options, args1, CliConfig.defaultConfig)) const result2 = yield* _(process(options, args2, CliConfig.defaultConfig)) const result3 = yield* _(process(options, args3, CliConfig.defaultConfig)) - const expected1 = [ReadonlyArray.empty(), [false, false]] - const expected2 = [ReadonlyArray.empty(), [true, false]] - const expected3 = [ReadonlyArray.empty(), [true, true]] + const expected1 = [Array.empty(), [false, false]] + const expected2 = [Array.empty(), [true, false]] + const expected3 = [Array.empty(), [true, true]] expect(result1).toEqual(expected1) expect(result2).toEqual(expected2) expect(result3).toEqual(expected3) @@ -150,7 +150,7 @@ describe("Options", () => { it("does not validate collision of boolean options with negation", () => Effect.gen(function*(_) { const option = Options.boolean("v", { negationNames: ["s"] }) - const args = ReadonlyArray.make("-v", "-s") + const args = Array.make("-v", "-s") const result = yield* _(Effect.flip(process(option, args, CliConfig.defaultConfig))) expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p( "Collision between two options detected - " + @@ -161,8 +161,8 @@ describe("Options", () => { it("validates a option with choices", () => Effect.gen(function*($) { const option = Options.choice("animal", ["cat", "dog"]) - const args1 = ReadonlyArray.make("--animal", "cat") - const args2 = ReadonlyArray.make("--animal", "dog") + const args1 = Array.make("--animal", "cat") + const args2 = Array.make("--animal", "dog") const result1 = yield* $(process(option, args1, CliConfig.defaultConfig)) const result2 = yield* $(process(option, args2, CliConfig.defaultConfig)) expect(result1).toEqual([[], "cat"]) @@ -180,8 +180,8 @@ describe("Options", () => { ["dog", dog], ["cat", cat] ]) - const args1 = ReadonlyArray.make("--animal", "cat") - const args2 = ReadonlyArray.make("--animal", "dog") + const args1 = Array.make("--animal", "cat") + const args2 = Array.make("--animal", "dog") const result1 = yield* $(process(option, args1, CliConfig.defaultConfig)) const result2 = yield* $(process(option, args2, CliConfig.defaultConfig)) expect(result1).toEqual([[], cat]) @@ -216,14 +216,14 @@ describe("Options", () => { it("validates an option and returns the remainder", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--firstName", "John", "--lastName", "Doe") + const args = Array.make("--firstName", "John", "--lastName", "Doe") const result = yield* _(process(firstName, args, CliConfig.defaultConfig)) expect(result).toEqual([["--lastName", "Doe"], "John"]) }).pipe(runEffect)) it("does not validate when no valid values are passed", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--lastName", "Doe") + const args = Array.make("--lastName", "Doe") const result = yield* _(Effect.either(process(firstName, args, CliConfig.defaultConfig))) expect(result).toEqual(Either.left(ValidationError.missingValue(HelpDoc.p( "Expected to find option: '--firstName'" @@ -232,7 +232,7 @@ describe("Options", () => { it("does not validate when an option is passed without a corresponding value", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--firstName") + const args = Array.make("--firstName") const result = yield* _(Effect.either(process(firstName, args, CliConfig.defaultConfig))) expect(result).toEqual(Either.left(ValidationError.missingValue(HelpDoc.p( "Expected a value following option: '--firstName'" @@ -242,7 +242,7 @@ describe("Options", () => { it("does not validate an invalid option value", () => Effect.gen(function*(_) { const option = Options.integer("t") - const args = ReadonlyArray.make("-t", "abc") + const args = Array.make("-t", "abc") const result = yield* _(Effect.flip(process(option, args, CliConfig.defaultConfig))) expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p("'abc' is not a integer"))) }).pipe(runEffect)) @@ -250,7 +250,7 @@ describe("Options", () => { it("does not validate an invalid option value even when there is a default", () => Effect.gen(function*(_) { const option = Options.withDefault(Options.integer("t"), 0) - const args = ReadonlyArray.make("-t", "abc") + const args = Array.make("-t", "abc") const result = yield* _(Effect.flip(process(option, args, CliConfig.defaultConfig))) expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p("'abc' is not a integer"))) }).pipe(runEffect)) @@ -259,10 +259,10 @@ describe("Options", () => { Effect.gen(function*(_) { const config = CliConfig.make({ isCaseSensitive: true, autoCorrectLimit: 2 }) const option = Options.text("Firstname").pipe(Options.withAlias("F")) - const args1 = ReadonlyArray.make("--Firstname", "John") - const args2 = ReadonlyArray.make("-F", "John") - const args3 = ReadonlyArray.make("--firstname", "John") - const args4 = ReadonlyArray.make("-f", "John") + const args1 = Array.make("--Firstname", "John") + const args2 = Array.make("-F", "John") + const args3 = Array.make("--firstname", "John") + const args4 = Array.make("-f", "John") const result1 = yield* _(process(option, args1, config)) const result2 = yield* _(process(option, args2, config)) const result3 = yield* _(Effect.flip(process(option, args3, config))) @@ -285,14 +285,14 @@ describe("Options", () => { it("validates an unsupplied optional option with remainder", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--bar", "baz") + const args = Array.make("--bar", "baz") const result = yield* _(process(ageOptional, args, CliConfig.defaultConfig)) expect(result).toEqual([args, Option.none()]) }).pipe(runEffect)) it("validates a supplied optional option", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--age", "20") + const args = Array.make("--age", "20") const result = yield* _(process(ageOptional, args, CliConfig.defaultConfig)) expect(result).toEqual([[], Option.some(20)]) }).pipe(runEffect)) @@ -304,7 +304,7 @@ describe("Options", () => { lastName: Options.text("lastName") }) const option2 = Options.all([Options.text("firstName"), Options.text("lastName")]) - const args = ReadonlyArray.make("--firstName", "John", "--lastName", "Doe") + const args = Array.make("--firstName", "John", "--lastName", "Doe") const result1 = yield* _(process(option1, args, CliConfig.defaultConfig)) const result2 = yield* _(process(option2, args, CliConfig.defaultConfig)) expect(result1).toEqual([[], { firstName: "John", lastName: "Doe" }]) @@ -313,7 +313,7 @@ describe("Options", () => { it("validate provides a suggestion if a provided option is close to a specified option", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--firstme", "Alice") + const args = Array.make("--firstme", "Alice") const result = yield* _(Effect.flip(process(firstName, args, CliConfig.defaultConfig))) expect(result).toEqual(ValidationError.correctedFlag(HelpDoc.p( "The flag '--firstme' is not recognized. Did you mean '--firstName'?" @@ -323,7 +323,7 @@ describe("Options", () => { it("validate provides a suggestion if a provided option with a default is close to a specified option", () => Effect.gen(function*(_) { const option = firstName.pipe(Options.withDefault("Jack")) - const args = ReadonlyArray.make("--firstme", "Alice") + const args = Array.make("--firstme", "Alice") const result = yield* _(Effect.flip(process(option, args, CliConfig.defaultConfig))) expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p( "The flag '--firstme' is not recognized. Did you mean '--firstName'?" @@ -340,8 +340,8 @@ describe("Options", () => { ) ) ) - const args1 = ReadonlyArray.make("--integer", "2") - const args2 = ReadonlyArray.make("--string", "two") + const args1 = Array.make("--integer", "2") + const args2 = Array.make("--string", "two") const result1 = yield* _(process(option, args1, CliConfig.defaultConfig)) const result2 = yield* _(process(option, args2, CliConfig.defaultConfig)) expect(result1).toEqual([[], Either.right(2)]) @@ -351,7 +351,7 @@ describe("Options", () => { it("orElse - option collision", () => Effect.gen(function*(_) { const option = Options.orElse(Options.text("string"), Options.integer("integer")) - const args = ReadonlyArray.make("--integer", "2", "--string", "two") + const args = Array.make("--integer", "2", "--string", "two") const result = yield* _(Effect.flip(process(option, args, CliConfig.defaultConfig))) expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p( "Collision between two options detected - " + @@ -376,7 +376,7 @@ describe("Options", () => { Options.orElse(Options.integer("max")), Options.withDefault(0) ) - const args = ReadonlyArray.make("--min", "abc") + const args = Array.make("--min", "abc") const result = yield* _(Effect.flip(process(option, args, CliConfig.defaultConfig))) const error = ValidationError.invalidValue(HelpDoc.sequence( HelpDoc.p("'abc' is not a integer"), @@ -395,28 +395,28 @@ describe("Options", () => { it("keyValueMap - validates repeated values", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("-d", "key1=v1", "-d", "key2=v2", "--verbose") + const args = Array.make("-d", "key1=v1", "-d", "key2=v2", "--verbose") const result = yield* _(process(defs, args, CliConfig.defaultConfig)) expect(result).toEqual([["--verbose"], HashMap.make(["key1", "v1"], ["key2", "v2"])]) }).pipe(runEffect)) it("keyValueMap - validates different key/values", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("--defs", "key1=v1", "key2=v2", "--verbose") + const args = Array.make("--defs", "key1=v1", "key2=v2", "--verbose") const result = yield* _(process(defs, args, CliConfig.defaultConfig)) expect(result).toEqual([["--verbose"], HashMap.make(["key1", "v1"], ["key2", "v2"])]) }).pipe(runEffect)) it("keyValueMap - validates different key/values with alias", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make("-d", "key1=v1", "key2=v2", "--verbose") + const args = Array.make("-d", "key1=v1", "key2=v2", "--verbose") const result = yield* _(process(defs, args, CliConfig.defaultConfig)) expect(result).toEqual([["--verbose"], HashMap.make(["key1", "v1"], ["key2", "v2"])]) }).pipe(runEffect)) it("keyValueMap - validate should keep non-key-value parameters that follow the key-value pairs (each preceded by alias -d)", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make( + const args = Array.make( "-d", "key1=val1", "-d", @@ -436,7 +436,7 @@ describe("Options", () => { it("keyValueMap - validate should keep non-key-value parameters that follow the key-value pairs (only the first key/value pair is preceded by alias)", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make( + const args = Array.make( "-d", "key1=val1", "key2=val2", @@ -454,7 +454,7 @@ describe("Options", () => { it("keyValueMap - validate should return an error for invalid key/value pairs", () => Effect.gen(function*(_) { - const args = ReadonlyArray.make( + const args = Array.make( "-d", "key1=val1", "key2=val2", @@ -482,8 +482,8 @@ describe("Options", () => { const result2 = yield* _(process(option, args2, CliConfig.defaultConfig)) const result3 = yield* _(Effect.flip(process(option, args3, CliConfig.defaultConfig))) const result4 = yield* _(Effect.flip(process(option, args4, CliConfig.defaultConfig))) - expect(result1).toEqual([ReadonlyArray.empty(), []]) - expect(result2).toEqual([ReadonlyArray.empty(), [1, 2, 3]]) + expect(result1).toEqual([Array.empty(), []]) + expect(result2).toEqual([Array.empty(), [1, 2, 3]]) expect(result3).toEqual(ValidationError.invalidValue(HelpDoc.p("'v2' is not a integer"))) expect(result4).toEqual(ValidationError.invalidValue(HelpDoc.p("'v2' is not a integer"))) }).pipe(runEffect)) @@ -495,7 +495,7 @@ describe("Options", () => { const args2 = ["--foo", "1"] const result1 = yield* _(process(option, args1, CliConfig.defaultConfig)) const result2 = yield* _(Effect.flip(process(option, args2, CliConfig.defaultConfig))) - expect(result1).toEqual([ReadonlyArray.empty(), [1, 2]]) + expect(result1).toEqual([Array.empty(), [1, 2]]) expect(result2).toEqual(ValidationError.invalidValue(HelpDoc.p( "Expected at least 2 value(s) for option: '--foo'" ))) @@ -508,7 +508,7 @@ describe("Options", () => { const args2 = ["--foo", "1", "--foo", "2", "--foo", "3"] const result1 = yield* _(process(option, args1, CliConfig.defaultConfig)) const result2 = yield* _(Effect.flip(process(option, args2, CliConfig.defaultConfig))) - expect(result1).toEqual([ReadonlyArray.empty(), [1, 2]]) + expect(result1).toEqual([Array.empty(), [1, 2]]) expect(result2).toEqual(ValidationError.invalidValue(HelpDoc.p( "Expected at most 2 value(s) for option: '--foo'" ))) @@ -528,8 +528,8 @@ describe("Options", () => { expect(result1).toEqual(ValidationError.invalidValue(HelpDoc.p( "Expected at least 2 value(s) for option: '--foo'" ))) - expect(result2).toEqual([ReadonlyArray.empty(), [1, 2]]) - expect(result3).toEqual([ReadonlyArray.empty(), [1, 2, 3]]) + expect(result2).toEqual([Array.empty(), [1, 2]]) + expect(result3).toEqual([Array.empty(), [1, 2, 3]]) expect(result4).toEqual(ValidationError.invalidValue(HelpDoc.p( "Expected at most 3 value(s) for option: '--foo'" ))) diff --git a/packages/cli/test/Primitive.test.ts b/packages/cli/test/Primitive.test.ts index 531be7f3d8..73f070b420 100644 --- a/packages/cli/test/Primitive.test.ts +++ b/packages/cli/test/Primitive.test.ts @@ -2,7 +2,7 @@ import * as CliConfig from "@effect/cli/CliConfig" import * as Primitive from "@effect/cli/Primitive" import type { FileSystem } from "@effect/platform" import { NodeFileSystem } from "@effect/platform-node" -import { Effect, Equal, Function, Option, ReadonlyArray } from "effect" +import { Array, Effect, Equal, Function, Option } from "effect" import fc from "fast-check" import { describe, expect, it } from "vitest" @@ -60,7 +60,7 @@ describe("Primitive", () => { Effect.gen(function*(_) { const alternatives = Function.unsafeCoerce< ReadonlyArray<[string, number]>, - ReadonlyArray.NonEmptyReadonlyArray<[string, number]> + Array.NonEmptyReadonlyArray<[string, number]> >(pairs) const choice = Primitive.choice(alternatives) const result = yield* _(Primitive.validate( @@ -78,8 +78,8 @@ describe("Primitive", () => { const selectedName = tuple[0] const alternatives = Function.unsafeCoerce< ReadonlyArray<[string, number]>, - ReadonlyArray.NonEmptyReadonlyArray<[string, number]> - >(ReadonlyArray.filter(pairs, (pair) => !Equal.equals(tuple, pair))) + Array.NonEmptyReadonlyArray<[string, number]> + >(Array.filter(pairs, (pair) => !Equal.equals(tuple, pair))) const choice = Primitive.choice(alternatives) const result = yield* _(Effect.flip(Primitive.validate( choice, @@ -153,5 +153,5 @@ const trueValuesArb = fc.constantFrom("true", "1", "y", "yes", "on").map(randomi const falseValuesArb = fc.constantFrom("false", "0", "n", "no", "off").map(randomizeCharacterCases) const pairsArb = fc.array(fc.tuple(fc.string(), fc.float()), { minLength: 2, maxLength: 100 }) - .map((pairs) => ReadonlyArray.dedupeWith(pairs, ([str1], [str2]) => str1 === str2)) + .map((pairs) => Array.dedupeWith(pairs, ([str1], [str2]) => str1 === str2)) .chain((pairs) => fc.tuple(fc.constantFrom(...pairs), fc.constant(pairs))) diff --git a/packages/cli/test/Wizard.test.ts b/packages/cli/test/Wizard.test.ts index 09107170d1..877bd4a2b1 100644 --- a/packages/cli/test/Wizard.test.ts +++ b/packages/cli/test/Wizard.test.ts @@ -5,7 +5,7 @@ import * as MockConsole from "@effect/cli/test/services/MockConsole" import * as MockTerminal from "@effect/cli/test/services/MockTerminal" import {} from "@effect/platform" import { NodeFileSystem, NodePath } from "@effect/platform-node" -import { Effect, ReadonlyArray } from "effect" +import { Array, Effect } from "effect" import * as Console from "effect/Console" import * as Fiber from "effect/Fiber" import * as Layer from "effect/Layer" @@ -34,12 +34,12 @@ describe("Wizard", () => { version: "1.0.0" }) ) - const args = ReadonlyArray.make("node", "test", "--wizard") + const args = Array.make("node", "test", "--wizard") const fiber = yield* _(Effect.fork(cli(args))) yield* _(MockTerminal.inputKey("c", { ctrl: true })) yield* _(Fiber.join(fiber)) const lines = yield* _(MockConsole.getLines({ stripAnsi: true })) - const result = ReadonlyArray.some(lines, (line) => line.includes("Quitting wizard mode...")) + const result = Array.some(lines, (line) => line.includes("Quitting wizard mode...")) expect(result).toBe(true) }).pipe(runEffect)) }) diff --git a/packages/cli/test/services/MockConsole.ts b/packages/cli/test/services/MockConsole.ts index 37b7d874e4..6c866b7c9d 100644 --- a/packages/cli/test/services/MockConsole.ts +++ b/packages/cli/test/services/MockConsole.ts @@ -1,7 +1,7 @@ +import * as Array from "effect/Array" import * as Console from "effect/Console" import * as Context from "effect/Context" import * as Effect from "effect/Effect" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" export interface MockConsole extends Console.Console { @@ -26,16 +26,16 @@ const pattern = new RegExp( const stripAnsi = (str: string) => str.replace(pattern, "") export const make = Effect.gen(function*(_) { - const lines = yield* _(Ref.make(ReadonlyArray.empty())) + const lines = yield* _(Ref.make(Array.empty())) const getLines: MockConsole["getLines"] = (params = {}) => Ref.get(lines).pipe(Effect.map((lines) => params.stripAnsi || false - ? ReadonlyArray.map(lines, stripAnsi) + ? Array.map(lines, stripAnsi) : lines )) - const log: MockConsole["log"] = (...args) => Ref.update(lines, ReadonlyArray.appendAll(args)) + const log: MockConsole["log"] = (...args) => Ref.update(lines, Array.appendAll(args)) return MockConsole.of({ [Console.TypeId]: Console.TypeId, diff --git a/packages/cli/test/services/MockTerminal.ts b/packages/cli/test/services/MockTerminal.ts index 3a162bb6e1..72f753a3d8 100644 --- a/packages/cli/test/services/MockTerminal.ts +++ b/packages/cli/test/services/MockTerminal.ts @@ -1,11 +1,11 @@ import * as Terminal from "@effect/platform/Terminal" +import * as Array from "effect/Array" import * as Console from "effect/Console" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" import * as Option from "effect/Option" import * as Queue from "effect/Queue" -import * as ReadonlyArray from "effect/ReadonlyArray" // ============================================================================= // Models @@ -46,7 +46,7 @@ export const make = Effect.gen(function*(_) { )) const inputText: MockTerminal["inputText"] = (text: string) => { - const inputs = ReadonlyArray.map(text.split(""), (key) => toUserInput(key)) + const inputs = Array.map(text.split(""), (key) => toUserInput(key)) return Queue.offerAll(queue, inputs).pipe(Effect.asVoid) } diff --git a/packages/effect/dtslint/ReadonlyArray.ts b/packages/effect/dtslint/Array.ts similarity index 64% rename from packages/effect/dtslint/ReadonlyArray.ts rename to packages/effect/dtslint/Array.ts index 62cfd532bf..6605fcf616 100644 --- a/packages/effect/dtslint/ReadonlyArray.ts +++ b/packages/effect/dtslint/Array.ts @@ -1,15 +1,15 @@ +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import * as Equal from "effect/Equal" import { hole, identity, pipe } from "effect/Function" import * as Option from "effect/Option" import * as Order from "effect/Order" import * as Predicate from "effect/Predicate" -import * as ReadonlyArray from "effect/ReadonlyArray" -declare const nonEmptyReadonlyNumbers: ReadonlyArray.NonEmptyReadonlyArray -declare const nonEmptyReadonlyStrings: ReadonlyArray.NonEmptyReadonlyArray -declare const nonEmptyNumbers: ReadonlyArray.NonEmptyArray -declare const nonEmptyStrings: ReadonlyArray.NonEmptyArray +declare const nonEmptyReadonlyNumbers: Array.NonEmptyReadonlyArray +declare const nonEmptyReadonlyStrings: Array.NonEmptyReadonlyArray +declare const nonEmptyNumbers: Array.NonEmptyArray +declare const nonEmptyStrings: Array.NonEmptyArray declare const readonlyNumbers: ReadonlyArray declare const numbers: Array declare const strings: Array @@ -27,105 +27,105 @@ const symC = Symbol.for("c") // isEmptyReadonlyArray // ------------------------------------------------------------------------------------- -if (ReadonlyArray.isEmptyReadonlyArray(readonlyNumbers)) { +if (Array.isEmptyReadonlyArray(readonlyNumbers)) { // $ExpectType readonly [] readonlyNumbers } // $ExpectType (a: readonly A[]) => Option -Option.liftPredicate(ReadonlyArray.isEmptyReadonlyArray) +Option.liftPredicate(Array.isEmptyReadonlyArray) // ------------------------------------------------------------------------------------- // isEmptyArray // ------------------------------------------------------------------------------------- -if (ReadonlyArray.isEmptyArray(numbers)) { +if (Array.isEmptyArray(numbers)) { // $ExpectType [] numbers } // $ExpectType (a: A[]) => Option<[]> -Option.liftPredicate(ReadonlyArray.isEmptyArray) +Option.liftPredicate(Array.isEmptyArray) // ------------------------------------------------------------------------------------- // isNonEmptyReadonlyArray // ------------------------------------------------------------------------------------- -if (ReadonlyArray.isNonEmptyReadonlyArray(readonlyNumbers)) { +if (Array.isNonEmptyReadonlyArray(readonlyNumbers)) { // $ExpectType readonly [number, ...number[]] readonlyNumbers } // $ExpectType (a: readonly A[]) => Option -Option.liftPredicate(ReadonlyArray.isNonEmptyReadonlyArray) +Option.liftPredicate(Array.isNonEmptyReadonlyArray) // ------------------------------------------------------------------------------------- // isNonEmptyArray // ------------------------------------------------------------------------------------- -if (ReadonlyArray.isNonEmptyArray(numbers)) { +if (Array.isNonEmptyArray(numbers)) { // $ExpectType [number, ...number[]] numbers } // $ExpectType (a: A[]) => Option<[A, ...A[]]> -Option.liftPredicate(ReadonlyArray.isNonEmptyArray) +Option.liftPredicate(Array.isNonEmptyArray) // ------------------------------------------------------------------------------------- // map // ------------------------------------------------------------------------------------- // $ExpectType number[] -ReadonlyArray.map(readonlyNumbers, (n) => n + 1) +Array.map(readonlyNumbers, (n) => n + 1) // $ExpectType number[] -pipe(readonlyNumbers, ReadonlyArray.map((n) => n + 1)) +pipe(readonlyNumbers, Array.map((n) => n + 1)) // $ExpectType number[] -ReadonlyArray.map(numbers, (n) => n + 1) +Array.map(numbers, (n) => n + 1) // $ExpectType number[] -pipe(numbers, ReadonlyArray.map((n) => n + 1)) +pipe(numbers, Array.map((n) => n + 1)) // $ExpectType [number, ...number[]] -ReadonlyArray.map(nonEmptyReadonlyNumbers, (n) => n + 1) +Array.map(nonEmptyReadonlyNumbers, (n) => n + 1) // $ExpectType [number, ...number[]] -pipe(nonEmptyReadonlyNumbers, ReadonlyArray.map((n) => n + 1)) +pipe(nonEmptyReadonlyNumbers, Array.map((n) => n + 1)) // $ExpectType [number, ...number[]] -ReadonlyArray.map(nonEmptyNumbers, (n) => n + 1) +Array.map(nonEmptyNumbers, (n) => n + 1) // $ExpectType [number, ...number[]] -pipe(nonEmptyNumbers, ReadonlyArray.map((n) => n + 1)) +pipe(nonEmptyNumbers, Array.map((n) => n + 1)) // ------------------------------------------------------------------------------------- // groupBy // ------------------------------------------------------------------------------------- // $ExpectType Record -ReadonlyArray.groupBy([1, 2, 3], String) +Array.groupBy([1, 2, 3], String) // $ExpectType Record -ReadonlyArray.groupBy([1, 2, 3], (n) => n > 0 ? "positive" as const : "negative" as const) +Array.groupBy([1, 2, 3], (n) => n > 0 ? "positive" as const : "negative" as const) // $ExpectType Record -ReadonlyArray.groupBy(["a", "b"], Symbol.for) +Array.groupBy(["a", "b"], Symbol.for) // $ExpectType Record -ReadonlyArray.groupBy(["a", "b"], (s) => s === "a" ? symA : s === "b" ? symB : symC) +Array.groupBy(["a", "b"], (s) => s === "a" ? symA : s === "b" ? symB : symC) // ------------------------------------------------------------------------------------- // some // ------------------------------------------------------------------------------------- -if (ReadonlyArray.some(numbersOrStrings, Predicate.isString)) { +if (Array.some(numbersOrStrings, Predicate.isString)) { numbersOrStrings // $ExpectType (string | number)[] & readonly [string | number, ...(string | number)[]] } pipe( numbersOrStrings, - ReadonlyArray.some(( + Array.some(( _item // $ExpectType string | number ) => true) ) @@ -134,33 +134,33 @@ pipe( // every // ------------------------------------------------------------------------------------- -if (ReadonlyArray.every(numbersOrStrings, Predicate.isString)) { +if (Array.every(numbersOrStrings, Predicate.isString)) { numbersOrStrings // $ExpectType (string | number)[] & readonly string[] } -if (ReadonlyArray.every(Predicate.isString)(numbersOrStrings)) { +if (Array.every(Predicate.isString)(numbersOrStrings)) { numbersOrStrings // $ExpectType (string | number)[] & readonly string[] } -ReadonlyArray.every(numbersOrStrings, ( +Array.every(numbersOrStrings, ( _item // $ExpectType string | number ) => true) -ReadonlyArray.every(numbersOrStrings, ( +Array.every(numbersOrStrings, ( _item, // $ExpectType string | number _i // $ExpectType number ) => true) pipe( numbersOrStrings, - ReadonlyArray.every(( + Array.every(( _item // $ExpectType string | number ) => true) ) pipe( numbersOrStrings, - ReadonlyArray.every(( + Array.every(( _item, // $ExpectType string | number _i // $ExpectType number ) => true) @@ -171,20 +171,20 @@ pipe( // ------------------------------------------------------------------------------------- // $ExpectType [string | number | boolean, ...(string | number | boolean)[]] -ReadonlyArray.append(numbersOrStrings, true) +Array.append(numbersOrStrings, true) // $ExpectType [string | number | boolean, ...(string | number | boolean)[]] -ReadonlyArray.append(true)(numbersOrStrings) +Array.append(true)(numbersOrStrings) // ------------------------------------------------------------------------------------- // prepend // ------------------------------------------------------------------------------------- // $ExpectType [string | number | boolean, ...(string | number | boolean)[]] -ReadonlyArray.prepend(numbersOrStrings, true) +Array.prepend(numbersOrStrings, true) // $ExpectType [string | number | boolean, ...(string | number | boolean)[]] -ReadonlyArray.prepend(true)(numbersOrStrings) +Array.prepend(true)(numbersOrStrings) // ------------------------------------------------------------------------------------- // sort @@ -196,94 +196,94 @@ interface AB { readonly b: number } declare const abs: ReadonlyArray -declare const nonEmptyabs: ReadonlyArray.NonEmptyReadonlyArray +declare const nonEmptyabs: Array.NonEmptyReadonlyArray // $ExpectType AB[] -ReadonlyArray.sort(abs, ordera) +Array.sort(abs, ordera) // $ExpectType AB[] -pipe(abs, ReadonlyArray.sort(ordera)) +pipe(abs, Array.sort(ordera)) // $ExpectType AB[] -ReadonlyArray.sort(ordera)(abs) +Array.sort(ordera)(abs) // $ExpectType [AB, ...AB[]] -ReadonlyArray.sort(nonEmptyabs, ordera) +Array.sort(nonEmptyabs, ordera) // $ExpectType [AB, ...AB[]] -pipe(nonEmptyabs, ReadonlyArray.sort(ordera)) +pipe(nonEmptyabs, Array.sort(ordera)) // $ExpectType [AB, ...AB[]] -ReadonlyArray.sort(ordera)(nonEmptyabs) +Array.sort(ordera)(nonEmptyabs) // @ts-expect-error -pipe([1], ReadonlyArray.sort(Order.string)) +pipe([1], Array.sort(Order.string)) // @ts-expect-error -ReadonlyArray.sort([1], Order.string) +Array.sort([1], Order.string) // @ts-expect-error -ReadonlyArray.sort(Order.string)([1]) +Array.sort(Order.string)([1]) // ------------------------------------------------------------------------------------- // sortWith // ------------------------------------------------------------------------------------- // $ExpectType AB[] -pipe(abs, ReadonlyArray.sortWith(identity, ordera)) +pipe(abs, Array.sortWith(identity, ordera)) // $ExpectType AB[] -ReadonlyArray.sortWith(abs, identity, ordera) +Array.sortWith(abs, identity, ordera) // $ExpectType [AB, ...AB[]] -pipe(nonEmptyabs, ReadonlyArray.sortWith(identity, ordera)) +pipe(nonEmptyabs, Array.sortWith(identity, ordera)) // $ExpectType [AB, ...AB[]] -ReadonlyArray.sortWith(nonEmptyabs, identity, ordera) +Array.sortWith(nonEmptyabs, identity, ordera) // ------------------------------------------------------------------------------------- // partition // ------------------------------------------------------------------------------------- -ReadonlyArray.partition(numbersOrStrings, ( +Array.partition(numbersOrStrings, ( _item // $ExpectType string | number ) => true) pipe( numbersOrStrings, - ReadonlyArray.partition(( + Array.partition(( _item // $ExpectType string | number ) => true) ) // $ExpectType [excluded: (string | number)[], satisfying: (string | number)[]] -ReadonlyArray.partition(numbersOrStrings, predicateNumbersOrStrings) +Array.partition(numbersOrStrings, predicateNumbersOrStrings) // $ExpectType [excluded: (string | number)[], satisfying: (string | number)[]] -pipe(numbersOrStrings, ReadonlyArray.partition(predicateNumbersOrStrings)) +pipe(numbersOrStrings, Array.partition(predicateNumbersOrStrings)) // $ExpectType [excluded: string[], satisfying: number[]] -ReadonlyArray.partition(numbersOrStrings, Predicate.isNumber) +Array.partition(numbersOrStrings, Predicate.isNumber) // $ExpectType [excluded: string[], satisfying: number[]] -pipe(numbersOrStrings, ReadonlyArray.partition(Predicate.isNumber)) +pipe(numbersOrStrings, Array.partition(Predicate.isNumber)) // ------------------------------------------------------------------------------------- // filter // ------------------------------------------------------------------------------------- -ReadonlyArray.filter(numbersOrStrings, ( +Array.filter(numbersOrStrings, ( _item // $ExpectType string | number ) => true) // @ts-expect-error -ReadonlyArray.filter(numbersOrStrings, ( +Array.filter(numbersOrStrings, ( _item: string ) => true) pipe( numbersOrStrings, - ReadonlyArray.filter(( + Array.filter(( _item // $ExpectType string | number ) => true) ) @@ -291,110 +291,110 @@ pipe( pipe( numbersOrStrings, // @ts-expect-error - ReadonlyArray.filter(( + Array.filter(( _item: string ) => true) ) // $ExpectType (string | number)[] -ReadonlyArray.filter(numbersOrStrings, predicateNumbersOrStrings) +Array.filter(numbersOrStrings, predicateNumbersOrStrings) // $ExpectType number[] -ReadonlyArray.filter(numbers, predicateNumbersOrStrings) +Array.filter(numbers, predicateNumbersOrStrings) // $ExpectType (string | number)[] -pipe(numbersOrStrings, ReadonlyArray.filter(predicateNumbersOrStrings)) +pipe(numbersOrStrings, Array.filter(predicateNumbersOrStrings)) // $ExpectType number[] -pipe(numbers, ReadonlyArray.filter(predicateNumbersOrStrings)) +pipe(numbers, Array.filter(predicateNumbersOrStrings)) // $ExpectType number[] -ReadonlyArray.filter(numbersOrStrings, Predicate.isNumber) +Array.filter(numbersOrStrings, Predicate.isNumber) // $ExpectType number[] -pipe(numbersOrStrings, ReadonlyArray.filter(Predicate.isNumber)) +pipe(numbersOrStrings, Array.filter(Predicate.isNumber)) // ------------------------------------------------------------------------------------- // takeWhile // ------------------------------------------------------------------------------------- -ReadonlyArray.takeWhile(numbersOrStrings, ( +Array.takeWhile(numbersOrStrings, ( _item // $ExpectType string | number ) => true) -ReadonlyArray.takeWhile(numbersOrStrings, ( +Array.takeWhile(numbersOrStrings, ( _item, // $ExpectType string | number _i // $ExpectType number ) => true) pipe( numbersOrStrings, - ReadonlyArray.takeWhile(( + Array.takeWhile(( _item // $ExpectType string | number ) => true) ) pipe( numbersOrStrings, - ReadonlyArray.takeWhile(( + Array.takeWhile(( _item, // $ExpectType string | number _i // $ExpectType number ) => true) ) // $ExpectType (string | number)[] -ReadonlyArray.takeWhile(numbersOrStrings, predicateNumbersOrStrings) +Array.takeWhile(numbersOrStrings, predicateNumbersOrStrings) // $ExpectType number[] -ReadonlyArray.takeWhile(numbers, predicateNumbersOrStrings) +Array.takeWhile(numbers, predicateNumbersOrStrings) // $ExpectType (string | number)[] -pipe(numbersOrStrings, ReadonlyArray.takeWhile(predicateNumbersOrStrings)) +pipe(numbersOrStrings, Array.takeWhile(predicateNumbersOrStrings)) // $ExpectType number[] -pipe(numbers, ReadonlyArray.takeWhile(predicateNumbersOrStrings)) +pipe(numbers, Array.takeWhile(predicateNumbersOrStrings)) // $ExpectType number[] -ReadonlyArray.takeWhile(numbersOrStrings, Predicate.isNumber) +Array.takeWhile(numbersOrStrings, Predicate.isNumber) // $ExpectType number[] -pipe(numbersOrStrings, ReadonlyArray.takeWhile(Predicate.isNumber)) +pipe(numbersOrStrings, Array.takeWhile(Predicate.isNumber)) // ------------------------------------------------------------------------------------- // findFirst // ------------------------------------------------------------------------------------- -ReadonlyArray.findFirst(numbersOrStrings, ( +Array.findFirst(numbersOrStrings, ( _item // $ExpectType string | number ) => true) -ReadonlyArray.findFirst(numbersOrStrings, ( +Array.findFirst(numbersOrStrings, ( _item, // $ExpectType string | number _i // $ExpectType number ) => true) // $ExpectType Option -ReadonlyArray.findFirst(numbersOrStrings, ( +Array.findFirst(numbersOrStrings, ( _item, // $ExpectType string | number _i // $ExpectType number ): _item is number => true) // $ExpectType Option -ReadonlyArray.findFirst(numbersOrStrings, ( +Array.findFirst(numbersOrStrings, ( _item, // $ExpectType string | number _i // $ExpectType number ) => Option.some(true)) pipe( numbersOrStrings, - ReadonlyArray.findFirst(( + Array.findFirst(( _item // $ExpectType string | number ) => true) ) pipe( numbersOrStrings, - ReadonlyArray.findFirst(( + Array.findFirst(( _item, // $ExpectType string | number _i // $ExpectType number ) => true) @@ -403,7 +403,7 @@ pipe( // $ExpectType Option pipe( numbersOrStrings, - ReadonlyArray.findFirst(( + Array.findFirst(( _item, // $ExpectType string | number _i // $ExpectType number ): _item is number => true) @@ -412,59 +412,59 @@ pipe( // $ExpectType Option pipe( numbersOrStrings, - ReadonlyArray.findFirst(( + Array.findFirst(( _item, // $ExpectType string | number _i // $ExpectType number ) => Option.some(true)) ) // $ExpectType Option -ReadonlyArray.findFirst(numbersOrStrings, predicateNumbersOrStrings) +Array.findFirst(numbersOrStrings, predicateNumbersOrStrings) // $ExpectType Option -pipe(numbersOrStrings, ReadonlyArray.findFirst(predicateNumbersOrStrings)) +pipe(numbersOrStrings, Array.findFirst(predicateNumbersOrStrings)) // $ExpectType Option -ReadonlyArray.findFirst(numbersOrStrings, Predicate.isNumber) +Array.findFirst(numbersOrStrings, Predicate.isNumber) // $ExpectType Option -pipe(numbersOrStrings, ReadonlyArray.findFirst(Predicate.isNumber)) +pipe(numbersOrStrings, Array.findFirst(Predicate.isNumber)) // ------------------------------------------------------------------------------------- // findLast // ------------------------------------------------------------------------------------- -ReadonlyArray.findLast(numbersOrStrings, ( +Array.findLast(numbersOrStrings, ( _item // $ExpectType string | number ) => true) -ReadonlyArray.findLast(numbersOrStrings, ( +Array.findLast(numbersOrStrings, ( _item, // $ExpectType string | number _i // $ExpectType number ) => true) // $ExpectType Option -ReadonlyArray.findLast(numbersOrStrings, ( +Array.findLast(numbersOrStrings, ( _item, // $ExpectType string | number _i // $ExpectType number ): _item is number => true) // $ExpectType Option -ReadonlyArray.findLast(numbersOrStrings, ( +Array.findLast(numbersOrStrings, ( _item, // $ExpectType string | number _i // $ExpectType number ) => Option.some(true)) pipe( numbersOrStrings, - ReadonlyArray.findLast(( + Array.findLast(( _item // $ExpectType string | number ) => true) ) pipe( numbersOrStrings, - ReadonlyArray.findLast(( + Array.findLast(( _item, // $ExpectType string | number _i // $ExpectType number ) => true) @@ -473,7 +473,7 @@ pipe( // $ExpectType Option pipe( numbersOrStrings, - ReadonlyArray.findLast(( + Array.findLast(( _item, // $ExpectType string | number _i // $ExpectType number ): _item is number => true) @@ -482,34 +482,34 @@ pipe( // $ExpectType Option pipe( numbersOrStrings, - ReadonlyArray.findLast(( + Array.findLast(( _item, // $ExpectType string | number _i // $ExpectType number ) => Option.some(true)) ) // $ExpectType Option -ReadonlyArray.findLast(numbersOrStrings, predicateNumbersOrStrings) +Array.findLast(numbersOrStrings, predicateNumbersOrStrings) // $ExpectType Option -pipe(numbersOrStrings, ReadonlyArray.findLast(predicateNumbersOrStrings)) +pipe(numbersOrStrings, Array.findLast(predicateNumbersOrStrings)) // $ExpectType Option -ReadonlyArray.findLast(numbersOrStrings, Predicate.isNumber) +Array.findLast(numbersOrStrings, Predicate.isNumber) // $ExpectType Option -pipe(numbersOrStrings, ReadonlyArray.findLast(Predicate.isNumber)) +pipe(numbersOrStrings, Array.findLast(Predicate.isNumber)) // ------------------------------------------------------------------------------------- // liftPredicate // ------------------------------------------------------------------------------------- // $ExpectType string[] -pipe(pimitiveNumerOrString, ReadonlyArray.liftPredicate(Predicate.isString)) +pipe(pimitiveNumerOrString, Array.liftPredicate(Predicate.isString)) pipe( pimitiveNumerOrString, - ReadonlyArray.liftPredicate( + Array.liftPredicate( ( n // $ExpectType string | number ): n is number => typeof n === "number" @@ -517,15 +517,15 @@ pipe( ) // $ExpectType (string | number)[] -pipe(pimitiveNumerOrString, ReadonlyArray.liftPredicate(predicateNumbersOrStrings)) +pipe(pimitiveNumerOrString, Array.liftPredicate(predicateNumbersOrStrings)) // $ExpectType number[] -pipe(pimitiveNumber, ReadonlyArray.liftPredicate(predicateNumbersOrStrings)) +pipe(pimitiveNumber, Array.liftPredicate(predicateNumbersOrStrings)) // $ExpectType number[] pipe( pimitiveNumber, - ReadonlyArray.liftPredicate( + Array.liftPredicate( ( _n // $ExpectType number ) => true @@ -536,126 +536,126 @@ pipe( // span // ------------------------------------------------------------------------------------- -ReadonlyArray.span(numbersOrStrings, ( +Array.span(numbersOrStrings, ( _item // $ExpectType string | number ) => true) -ReadonlyArray.span(numbersOrStrings, ( +Array.span(numbersOrStrings, ( _item, // $ExpectType string | number _i // $ExpectType number ) => true) pipe( numbersOrStrings, - ReadonlyArray.span(( + Array.span(( _item // $ExpectType string | number ) => true) ) pipe( numbersOrStrings, - ReadonlyArray.span(( + Array.span(( _item, // $ExpectType string | number _i // $ExpectType number ) => true) ) // $ExpectType [init: (string | number)[], rest: (string | number)[]] -ReadonlyArray.span(numbersOrStrings, predicateNumbersOrStrings) +Array.span(numbersOrStrings, predicateNumbersOrStrings) // $ExpectType [init: number[], rest: number[]] -ReadonlyArray.span(numbers, predicateNumbersOrStrings) +Array.span(numbers, predicateNumbersOrStrings) // $ExpectType [init: (string | number)[], rest: (string | number)[]] -pipe(numbersOrStrings, ReadonlyArray.span(predicateNumbersOrStrings)) +pipe(numbersOrStrings, Array.span(predicateNumbersOrStrings)) // $ExpectType [init: number[], rest: number[]] -pipe(numbers, ReadonlyArray.span(predicateNumbersOrStrings)) +pipe(numbers, Array.span(predicateNumbersOrStrings)) // $ExpectType [init: number[], rest: string[]] -ReadonlyArray.span(numbersOrStrings, Predicate.isNumber) +Array.span(numbersOrStrings, Predicate.isNumber) // $ExpectType [init: number[], rest: string[]] -pipe(numbersOrStrings, ReadonlyArray.span(Predicate.isNumber)) +pipe(numbersOrStrings, Array.span(Predicate.isNumber)) // ------------------------------------------------------------------------------------- // dropWhile // ------------------------------------------------------------------------------------- // $ExpectType number[] -ReadonlyArray.dropWhile(numbers, predicateNumbersOrStrings) +Array.dropWhile(numbers, predicateNumbersOrStrings) // $ExpectType number[] -pipe(numbers, ReadonlyArray.dropWhile(predicateNumbersOrStrings)) +pipe(numbers, Array.dropWhile(predicateNumbersOrStrings)) // $ExpectType (string | number)[] -ReadonlyArray.dropWhile(numbersOrStrings, Predicate.isNumber) +Array.dropWhile(numbersOrStrings, Predicate.isNumber) // $ExpectType (string | number)[] -pipe(numbersOrStrings, ReadonlyArray.dropWhile(Predicate.isNumber)) +pipe(numbersOrStrings, Array.dropWhile(Predicate.isNumber)) // ------------------------------------------------------------------------------------- // flatMap // ------------------------------------------------------------------------------------- // $ExpectType number[] -ReadonlyArray.flatMap(strings, ( +Array.flatMap(strings, ( _s, // $ExpectType string _i // $ExpectType number -) => ReadonlyArray.empty()) +) => Array.empty()) // $ExpectType number[] pipe( strings, - ReadonlyArray.flatMap(( + Array.flatMap(( _s, // $ExpectType string _i // $ExpectType number - ) => ReadonlyArray.empty()) + ) => Array.empty()) ) // $ExpectType number[] -ReadonlyArray.flatMap(strings, ( +Array.flatMap(strings, ( s, // $ExpectType string _i // $ExpectType number -) => ReadonlyArray.of(s.length)) +) => Array.of(s.length)) // $ExpectType number[] pipe( strings, - ReadonlyArray.flatMap(( + Array.flatMap(( s, // $ExpectType string _i // $ExpectType number - ) => ReadonlyArray.of(s.length)) + ) => Array.of(s.length)) ) // $ExpectType number[] -ReadonlyArray.flatMap(nonEmptyReadonlyStrings, ( +Array.flatMap(nonEmptyReadonlyStrings, ( _s, // $ExpectType string _i // $ExpectType number -) => ReadonlyArray.empty()) +) => Array.empty()) // $ExpectType number[] pipe( nonEmptyReadonlyStrings, - ReadonlyArray.flatMap(( + Array.flatMap(( _s, // $ExpectType string _i // $ExpectType number - ) => ReadonlyArray.empty()) + ) => Array.empty()) ) // $ExpectType [number, ...number[]] -ReadonlyArray.flatMap(nonEmptyReadonlyStrings, ( +Array.flatMap(nonEmptyReadonlyStrings, ( s, // $ExpectType string _i // $ExpectType number -) => ReadonlyArray.of(s.length)) +) => Array.of(s.length)) // $ExpectType [number, ...number[]] pipe( nonEmptyReadonlyStrings, - ReadonlyArray.flatMap(( + Array.flatMap(( s, // $ExpectType string _i // $ExpectType number - ) => ReadonlyArray.of(s.length)) + ) => Array.of(s.length)) ) // ------------------------------------------------------------------------------------- @@ -663,297 +663,297 @@ pipe( // ------------------------------------------------------------------------------------- // $ExpectType number[] -ReadonlyArray.flatten(hole>>()) +Array.flatten(hole>>()) // $ExpectType number[] -ReadonlyArray.flatten(hole>>()) +Array.flatten(hole>>()) // $ExpectType number[] -ReadonlyArray.flatten(hole>>()) +Array.flatten(hole>>()) // $ExpectType [number, ...number[]] -ReadonlyArray.flatten(hole>>()) +Array.flatten(hole>>()) declare const flattenArray: Effect.Effect>> declare const flattenNonEmptyArray: Effect.Effect< - ReadonlyArray.NonEmptyReadonlyArray> + Array.NonEmptyReadonlyArray> > // $ExpectType Effect -flattenArray.pipe(Effect.map((_) => ReadonlyArray.flatten(_))) +flattenArray.pipe(Effect.map((_) => Array.flatten(_))) // $ExpectType Effect -flattenArray.pipe(Effect.map(ReadonlyArray.flatten)) +flattenArray.pipe(Effect.map(Array.flatten)) // $ExpectType Effect<[number, ...number[]], never, never> -flattenNonEmptyArray.pipe(Effect.map((_) => ReadonlyArray.flatten(_))) +flattenNonEmptyArray.pipe(Effect.map((_) => Array.flatten(_))) // $ExpectType Effect<[number, ...number[]], never, never> -flattenNonEmptyArray.pipe(Effect.map(ReadonlyArray.flatten)) +flattenNonEmptyArray.pipe(Effect.map(Array.flatten)) // ------------------------------------------------------------------------------------- // prependAll // ------------------------------------------------------------------------------------- // $ExpectType (string | number)[] -ReadonlyArray.prependAll(strings, numbers) +Array.prependAll(strings, numbers) // $ExpectType (string | number)[] -pipe(strings, ReadonlyArray.prependAll(numbers)) +pipe(strings, Array.prependAll(numbers)) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.prependAll(nonEmptyStrings, numbers) +Array.prependAll(nonEmptyStrings, numbers) // $ExpectType [string | number, ...(string | number)[]] -pipe(nonEmptyStrings, ReadonlyArray.prependAll(numbers)) +pipe(nonEmptyStrings, Array.prependAll(numbers)) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.prependAll(strings, nonEmptyNumbers) +Array.prependAll(strings, nonEmptyNumbers) // $ExpectType [string | number, ...(string | number)[]] -pipe(strings, ReadonlyArray.prependAll(nonEmptyNumbers)) +pipe(strings, Array.prependAll(nonEmptyNumbers)) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.prependAll(nonEmptyStrings, nonEmptyNumbers) +Array.prependAll(nonEmptyStrings, nonEmptyNumbers) // $ExpectType [string | number, ...(string | number)[]] -pipe(nonEmptyStrings, ReadonlyArray.prependAll(nonEmptyNumbers)) +pipe(nonEmptyStrings, Array.prependAll(nonEmptyNumbers)) // ------------------------------------------------------------------------------------- // appendAll // ------------------------------------------------------------------------------------- // $ExpectType (string | number)[] -ReadonlyArray.appendAll(strings, numbers) +Array.appendAll(strings, numbers) // $ExpectType (string | number)[] -pipe(strings, ReadonlyArray.appendAll(numbers)) +pipe(strings, Array.appendAll(numbers)) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.appendAll(nonEmptyStrings, numbers) +Array.appendAll(nonEmptyStrings, numbers) // $ExpectType [string | number, ...(string | number)[]] -pipe(nonEmptyStrings, ReadonlyArray.appendAll(numbers)) +pipe(nonEmptyStrings, Array.appendAll(numbers)) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.appendAll(strings, nonEmptyNumbers) +Array.appendAll(strings, nonEmptyNumbers) // $ExpectType [string | number, ...(string | number)[]] -pipe(strings, ReadonlyArray.appendAll(nonEmptyNumbers)) +pipe(strings, Array.appendAll(nonEmptyNumbers)) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.appendAll(nonEmptyStrings, nonEmptyNumbers) +Array.appendAll(nonEmptyStrings, nonEmptyNumbers) // $ExpectType [string | number, ...(string | number)[]] -pipe(nonEmptyStrings, ReadonlyArray.appendAll(nonEmptyNumbers)) +pipe(nonEmptyStrings, Array.appendAll(nonEmptyNumbers)) // ------------------------------------------------------------------------------------- // zip // ------------------------------------------------------------------------------------- // $ExpectType [string, number][] -ReadonlyArray.zip(strings, numbers) +Array.zip(strings, numbers) // $ExpectType [string, number][] -pipe(strings, ReadonlyArray.zip(numbers)) +pipe(strings, Array.zip(numbers)) // $ExpectType [string, number][] -ReadonlyArray.zip(numbers)(strings) +Array.zip(numbers)(strings) // $ExpectType [[string, number], ...[string, number][]] -ReadonlyArray.zip(nonEmptyStrings, nonEmptyNumbers) +Array.zip(nonEmptyStrings, nonEmptyNumbers) // $ExpectType [[string, number], ...[string, number][]] -pipe(nonEmptyStrings, ReadonlyArray.zip(nonEmptyNumbers)) +pipe(nonEmptyStrings, Array.zip(nonEmptyNumbers)) // $ExpectType [[string, number], ...[string, number][]] -ReadonlyArray.zip(nonEmptyNumbers)(nonEmptyStrings) +Array.zip(nonEmptyNumbers)(nonEmptyStrings) // ------------------------------------------------------------------------------------- // intersperse // ------------------------------------------------------------------------------------- // $ExpectType string[] -ReadonlyArray.intersperse(strings, "a") +Array.intersperse(strings, "a") // $ExpectType (string | number)[] -ReadonlyArray.intersperse(strings, 1) +Array.intersperse(strings, 1) // $ExpectType string[] -pipe(strings, ReadonlyArray.intersperse("a")) +pipe(strings, Array.intersperse("a")) // $ExpectType (string | number)[] -pipe(strings, ReadonlyArray.intersperse(1)) +pipe(strings, Array.intersperse(1)) // $ExpectType string[] -ReadonlyArray.intersperse("a")(strings) +Array.intersperse("a")(strings) // $ExpectType (string | number)[] -ReadonlyArray.intersperse(1)(strings) +Array.intersperse(1)(strings) // $ExpectType [string, ...string[]] -ReadonlyArray.intersperse(nonEmptyStrings, "a") +Array.intersperse(nonEmptyStrings, "a") // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.intersperse(nonEmptyStrings, 1) +Array.intersperse(nonEmptyStrings, 1) // $ExpectType [string, ...string[]] -pipe(nonEmptyStrings, ReadonlyArray.intersperse("a")) +pipe(nonEmptyStrings, Array.intersperse("a")) // $ExpectType [string | number, ...(string | number)[]] -pipe(nonEmptyStrings, ReadonlyArray.intersperse(1)) +pipe(nonEmptyStrings, Array.intersperse(1)) // $ExpectType [string, ...string[]] -ReadonlyArray.intersperse("a")(nonEmptyStrings) +Array.intersperse("a")(nonEmptyStrings) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.intersperse(1)(nonEmptyStrings) +Array.intersperse(1)(nonEmptyStrings) // ------------------------------------------------------------------------------------- // rotate // ------------------------------------------------------------------------------------- // $ExpectType string[] -ReadonlyArray.rotate(strings, 10) +Array.rotate(strings, 10) // $ExpectType string[] -pipe(strings, ReadonlyArray.rotate(10)) +pipe(strings, Array.rotate(10)) // $ExpectType string[] -ReadonlyArray.rotate(10)(strings) +Array.rotate(10)(strings) // $ExpectType [string, ...string[]] -ReadonlyArray.rotate(nonEmptyStrings, 10) +Array.rotate(nonEmptyStrings, 10) // $ExpectType [string, ...string[]] -pipe(nonEmptyStrings, ReadonlyArray.rotate(10)) +pipe(nonEmptyStrings, Array.rotate(10)) // $ExpectType [string, ...string[]] -ReadonlyArray.rotate(10)(nonEmptyStrings) +Array.rotate(10)(nonEmptyStrings) // ------------------------------------------------------------------------------------- // union // ------------------------------------------------------------------------------------- // $ExpectType (string | number)[] -ReadonlyArray.union(strings, numbers) +Array.union(strings, numbers) // $ExpectType (string | number)[] -pipe(strings, ReadonlyArray.union(numbers)) +pipe(strings, Array.union(numbers)) // $ExpectType (string | number)[] -ReadonlyArray.union(numbers)(strings) +Array.union(numbers)(strings) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.union(nonEmptyStrings, numbers) +Array.union(nonEmptyStrings, numbers) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.union(strings, nonEmptyNumbers) +Array.union(strings, nonEmptyNumbers) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.union(nonEmptyStrings, nonEmptyNumbers) +Array.union(nonEmptyStrings, nonEmptyNumbers) // $ExpectType [string | number, ...(string | number)[]] -pipe(nonEmptyStrings, ReadonlyArray.union(numbers)) +pipe(nonEmptyStrings, Array.union(numbers)) // $ExpectType [string | number, ...(string | number)[]] -pipe(strings, ReadonlyArray.union(nonEmptyNumbers)) +pipe(strings, Array.union(nonEmptyNumbers)) // $ExpectType [string | number, ...(string | number)[]] -pipe(nonEmptyStrings, ReadonlyArray.union(nonEmptyNumbers)) +pipe(nonEmptyStrings, Array.union(nonEmptyNumbers)) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.union(numbers)(nonEmptyStrings) +Array.union(numbers)(nonEmptyStrings) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.union(nonEmptyNumbers)(strings) +Array.union(nonEmptyNumbers)(strings) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.union(nonEmptyNumbers)(nonEmptyStrings) +Array.union(nonEmptyNumbers)(nonEmptyStrings) // ------------------------------------------------------------------------------------- // unionWith // ------------------------------------------------------------------------------------- // $ExpectType (string | number)[] -ReadonlyArray.unionWith(strings, numbers, Equal.equivalence()) +Array.unionWith(strings, numbers, Equal.equivalence()) // $ExpectType (string | number)[] -ReadonlyArray.unionWith(strings, numbers, ( +Array.unionWith(strings, numbers, ( _a, // $ExpectType string _b // $ExpectType number ) => true) // $ExpectType (string | number)[] -pipe(strings, ReadonlyArray.unionWith(numbers, Equal.equivalence())) +pipe(strings, Array.unionWith(numbers, Equal.equivalence())) // $ExpectType (string | number)[] pipe( strings, - ReadonlyArray.unionWith(numbers, ( + Array.unionWith(numbers, ( _a, // $ExpectType string _b // $ExpectType number ) => true) ) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.unionWith(nonEmptyStrings, numbers, Equal.equivalence()) +Array.unionWith(nonEmptyStrings, numbers, Equal.equivalence()) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.unionWith(nonEmptyStrings, numbers, ( +Array.unionWith(nonEmptyStrings, numbers, ( _a, // $ExpectType string _b // $ExpectType number ) => true) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.unionWith(strings, nonEmptyNumbers, Equal.equivalence()) +Array.unionWith(strings, nonEmptyNumbers, Equal.equivalence()) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.unionWith(strings, nonEmptyNumbers, ( +Array.unionWith(strings, nonEmptyNumbers, ( _a, // $ExpectType string _b // $ExpectType number ) => true) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.unionWith(nonEmptyStrings, nonEmptyNumbers, Equal.equivalence()) +Array.unionWith(nonEmptyStrings, nonEmptyNumbers, Equal.equivalence()) // $ExpectType [string | number, ...(string | number)[]] -ReadonlyArray.unionWith(nonEmptyStrings, nonEmptyNumbers, ( +Array.unionWith(nonEmptyStrings, nonEmptyNumbers, ( _a, // $ExpectType string _b // $ExpectType number ) => true) // $ExpectType [string | number, ...(string | number)[]] -pipe(nonEmptyStrings, ReadonlyArray.unionWith(numbers, Equal.equivalence())) +pipe(nonEmptyStrings, Array.unionWith(numbers, Equal.equivalence())) // $ExpectType [string | number, ...(string | number)[]] pipe( nonEmptyStrings, - ReadonlyArray.unionWith(numbers, ( + Array.unionWith(numbers, ( _a, // $ExpectType string _b // $ExpectType number ) => true) ) // $ExpectType [string | number, ...(string | number)[]] -pipe(strings, ReadonlyArray.unionWith(nonEmptyNumbers, Equal.equivalence())) +pipe(strings, Array.unionWith(nonEmptyNumbers, Equal.equivalence())) // $ExpectType [string | number, ...(string | number)[]] pipe( strings, - ReadonlyArray.unionWith(nonEmptyNumbers, ( + Array.unionWith(nonEmptyNumbers, ( _a, // $ExpectType string _b // $ExpectType number ) => true) ) // $ExpectType [string | number, ...(string | number)[]] -pipe(nonEmptyStrings, ReadonlyArray.unionWith(nonEmptyNumbers, Equal.equivalence())) +pipe(nonEmptyStrings, Array.unionWith(nonEmptyNumbers, Equal.equivalence())) // $ExpectType [string | number, ...(string | number)[]] pipe( nonEmptyStrings, - ReadonlyArray.unionWith(nonEmptyNumbers, ( + Array.unionWith(nonEmptyNumbers, ( _a, // $ExpectType string _b // $ExpectType number ) => true) @@ -964,58 +964,58 @@ pipe( // ------------------------------------------------------------------------------------- // $ExpectType string[] -ReadonlyArray.dedupe(strings) +Array.dedupe(strings) // $ExpectType string[] -pipe(strings, ReadonlyArray.dedupe) +pipe(strings, Array.dedupe) // $ExpectType [string, ...string[]] -ReadonlyArray.dedupe(nonEmptyStrings) +Array.dedupe(nonEmptyStrings) // $ExpectType [string, ...string[]] -pipe(nonEmptyStrings, ReadonlyArray.dedupe) +pipe(nonEmptyStrings, Array.dedupe) // ------------------------------------------------------------------------------------- // dedupeWith // ------------------------------------------------------------------------------------- // $ExpectType string[] -ReadonlyArray.dedupeWith(strings, Equal.equivalence()) +Array.dedupeWith(strings, Equal.equivalence()) // $ExpectType string[] -ReadonlyArray.dedupeWith(strings, ( +Array.dedupeWith(strings, ( _a, // $ExpectType string _b // $ExpectType string ) => true) // $ExpectType string[] -pipe(strings, ReadonlyArray.dedupeWith(Equal.equivalence())) +pipe(strings, Array.dedupeWith(Equal.equivalence())) // $ExpectType string[] pipe( strings, - ReadonlyArray.dedupeWith(( + Array.dedupeWith(( _a, // $ExpectType string _b // $ExpectType string ) => true) ) // $ExpectType [string, ...string[]] -ReadonlyArray.dedupeWith(nonEmptyStrings, Equal.equivalence()) +Array.dedupeWith(nonEmptyStrings, Equal.equivalence()) // $ExpectType [string, ...string[]] -ReadonlyArray.dedupeWith(nonEmptyStrings, ( +Array.dedupeWith(nonEmptyStrings, ( _a, // $ExpectType string _b // $ExpectType string ) => true) // $ExpectType [string, ...string[]] -pipe(nonEmptyStrings, ReadonlyArray.dedupeWith(Equal.equivalence())) +pipe(nonEmptyStrings, Array.dedupeWith(Equal.equivalence())) // $ExpectType [string, ...string[]] pipe( nonEmptyStrings, - ReadonlyArray.dedupeWith(( + Array.dedupeWith(( _a, // $ExpectType string _b // $ExpectType string ) => true) @@ -1026,7 +1026,7 @@ pipe( // ------------------------------------------------------------------------------------- // $ExpectType string[] -ReadonlyArray.chop(strings, ([ +Array.chop(strings, ([ head, // $ExpectType string ...tail // $ExpectType string[] ]) => [head, tail]) @@ -1034,14 +1034,14 @@ ReadonlyArray.chop(strings, ([ // $ExpectType string[] pipe( strings, - ReadonlyArray.chop(([ + Array.chop(([ head, // $ExpectType string ...tail // $ExpectType string[] ]) => [head, tail]) ) // $ExpectType [string, ...string[]] -ReadonlyArray.chop(nonEmptyStrings, ([ +Array.chop(nonEmptyStrings, ([ head, // $ExpectType string ...tail // $ExpectType string[] ]) => [head, tail]) @@ -1049,7 +1049,7 @@ ReadonlyArray.chop(nonEmptyStrings, ([ // $ExpectType [string, ...string[]] pipe( nonEmptyStrings, - ReadonlyArray.chop(([ + Array.chop(([ head, // $ExpectType string ...tail // $ExpectType string[] ]) => [head, tail]) @@ -1060,62 +1060,62 @@ pipe( // ------------------------------------------------------------------------------------- // $ExpectType [string, ...string[]][] -ReadonlyArray.chunksOf(strings, 10) +Array.chunksOf(strings, 10) // $ExpectType [string, ...string[]][] -pipe(strings, ReadonlyArray.chunksOf(10)) +pipe(strings, Array.chunksOf(10)) // $ExpectType [string, ...string[]][] -ReadonlyArray.chunksOf(10)(strings) +Array.chunksOf(10)(strings) // $ExpectType [[string, ...string[]], ...[string, ...string[]][]] -ReadonlyArray.chunksOf(nonEmptyStrings, 10) +Array.chunksOf(nonEmptyStrings, 10) // $ExpectType [[string, ...string[]], ...[string, ...string[]][]] -pipe(nonEmptyStrings, ReadonlyArray.chunksOf(10)) +pipe(nonEmptyStrings, Array.chunksOf(10)) // $ExpectType [[string, ...string[]], ...[string, ...string[]][]] -ReadonlyArray.chunksOf(10)(nonEmptyStrings) +Array.chunksOf(10)(nonEmptyStrings) // ------------------------------------------------------------------------------------- // reverse // ------------------------------------------------------------------------------------- // $ExpectType string[] -ReadonlyArray.reverse(strings) +Array.reverse(strings) // $ExpectType string[] -pipe(strings, ReadonlyArray.reverse) +pipe(strings, Array.reverse) // $ExpectType [string, ...string[]] -ReadonlyArray.reverse(nonEmptyStrings) +Array.reverse(nonEmptyStrings) // $ExpectType [string, ...string[]] -pipe(nonEmptyStrings, ReadonlyArray.reverse) +pipe(nonEmptyStrings, Array.reverse) // ------------------------------------------------------------------------------------- // sortBy // ------------------------------------------------------------------------------------- // $ExpectType AB[] -pipe(abs, ReadonlyArray.sortBy(ordera)) +pipe(abs, Array.sortBy(ordera)) // $ExpectType AB[] pipe( abs, - ReadonlyArray.sortBy(( + Array.sortBy(( _a, // $ExpectType AB _b // $ExpectType AB ) => 0) ) // $ExpectType [AB, ...AB[]] -pipe(nonEmptyabs, ReadonlyArray.sortBy(ordera)) +pipe(nonEmptyabs, Array.sortBy(ordera)) // $ExpectType [AB, ...AB[]] pipe( nonEmptyabs, - ReadonlyArray.sortBy(( + Array.sortBy(( _a, // $ExpectType AB _b // $ExpectType AB ) => 0) @@ -1126,23 +1126,23 @@ pipe( // ------------------------------------------------------------------------------------- // $ExpectType [string[], number[]] -ReadonlyArray.unzip(hole>()) +Array.unzip(hole>()) // $ExpectType [string[], number[]] -pipe(hole>(), ReadonlyArray.unzip) +pipe(hole>(), Array.unzip) // $ExpectType [[string, ...string[]], [number, ...number[]]] -ReadonlyArray.unzip(hole>()) +Array.unzip(hole>()) // $ExpectType [[string, ...string[]], [number, ...number[]]] -pipe(hole>(), ReadonlyArray.unzip) +pipe(hole>(), Array.unzip) // ------------------------------------------------------------------------------------- // zipWith // ------------------------------------------------------------------------------------- // $ExpectType [string, number][] -ReadonlyArray.zipWith(strings, numbers, ( +Array.zipWith(strings, numbers, ( a, // $ExpectType string b // $ExpectType number ) => [a, b] as [string, number]) @@ -1150,14 +1150,14 @@ ReadonlyArray.zipWith(strings, numbers, ( // $ExpectType [string, number][] pipe( strings, - ReadonlyArray.zipWith(numbers, ( + Array.zipWith(numbers, ( a, // $ExpectType string b // $ExpectType number ) => [a, b] as [string, number]) ) // $ExpectType [[string, number], ...[string, number][]] -ReadonlyArray.zipWith(nonEmptyStrings, nonEmptyNumbers, ( +Array.zipWith(nonEmptyStrings, nonEmptyNumbers, ( a, // $ExpectType string b // $ExpectType number ) => [a, b] as [string, number]) @@ -1165,7 +1165,7 @@ ReadonlyArray.zipWith(nonEmptyStrings, nonEmptyNumbers, ( // $ExpectType [[string, number], ...[string, number][]] pipe( nonEmptyStrings, - ReadonlyArray.zipWith(nonEmptyNumbers, ( + Array.zipWith(nonEmptyNumbers, ( a, // $ExpectType string b // $ExpectType number ) => [a, b] as [string, number]) diff --git a/packages/effect/dtslint/Either.ts b/packages/effect/dtslint/Either.ts index 8e26fdc9f6..c8bc51cd86 100644 --- a/packages/effect/dtslint/Either.ts +++ b/packages/effect/dtslint/Either.ts @@ -1,7 +1,7 @@ +import * as Array from "effect/Array" import * as Either from "effect/Either" import { pipe } from "effect/Function" import * as Predicate from "effect/Predicate" -import * as ReadonlyArray from "effect/ReadonlyArray" declare const string$string: Either.Either declare const string$number: Either.Either @@ -119,7 +119,7 @@ declare const error$arrayOfStrings: Either.Either, Error> // $ExpectType Either<[string, ...string[]], "b" | Error> pipe( error$arrayOfStrings, - Either.filterOrLeft(ReadonlyArray.isNonEmptyArray, ( + Either.filterOrLeft(Array.isNonEmptyArray, ( _s // $ExpectType NoInfer ) => "b" as const) ) @@ -129,7 +129,7 @@ declare const error$readonlyArrayOfStrings: Either.Either, // $ExpectType Either pipe( error$readonlyArrayOfStrings, - Either.filterOrLeft(ReadonlyArray.isNonEmptyReadonlyArray, ( + Either.filterOrLeft(Array.isNonEmptyReadonlyArray, ( _s // $ExpectType NoInfer ) => "b" as const) ) diff --git a/packages/effect/dtslint/ReadonlyRecord.ts b/packages/effect/dtslint/Record.ts similarity index 65% rename from packages/effect/dtslint/ReadonlyRecord.ts rename to packages/effect/dtslint/Record.ts index 97306a9c76..a9e218ee7a 100644 --- a/packages/effect/dtslint/ReadonlyRecord.ts +++ b/packages/effect/dtslint/Record.ts @@ -3,7 +3,7 @@ import * as Either from "effect/Either" import { hole, pipe } from "effect/Function" import * as Option from "effect/Option" import * as Predicate from "effect/Predicate" -import * as ReadonlyRecord from "effect/ReadonlyRecord" +import * as Record from "effect/Record" declare const string$numbers: Record declare const string$numbersOrStrings: Record @@ -24,84 +24,84 @@ declare const template$numbers: Record<`a${string}`, number> // ------------------------------------------------------------------------------------- // $ExpectType string -hole>() +hole>() // $ExpectType symbol -hole>() +hole>() // $ExpectType string -hole>() +hole>() // $ExpectType string -hole>() +hole>() // $ExpectType string -hole>() +hole>() // $ExpectType symbol -hole>() +hole>() // $ExpectType symbol -hole>() +hole>() // $ExpectType string | symbol -hole>() +hole>() // $ExpectType string -hole>() +hole>() // $ExpectType `a${string}` -hole>() +hole>() // $ExpectType `${string}a` -hole>() +hole>() // $ExpectType `a${string}b${string}` -hole>() +hole>() // $ExpectType `a${number}` -hole>() +hole>() // $ExpectType `a${number}b${string}c${number}` -hole>() +hole>() // ------------------------------------------------------------------------------------- // empty // ------------------------------------------------------------------------------------- -export const empty1: Record = ReadonlyRecord.empty() -export const empty2: Record = ReadonlyRecord.empty() +export const empty1: Record = Record.empty() +export const empty2: Record = Record.empty() // @ts-expect-error -export const empty3: Record<"a", number> = ReadonlyRecord.empty() +export const empty3: Record<"a", number> = Record.empty() // $ExpectType Record -ReadonlyRecord.empty() +Record.empty() // $ExpectType Record -ReadonlyRecord.empty<"a">() +Record.empty<"a">() // $ExpectType Record<`a${string}bc`, never> -ReadonlyRecord.empty<`a${string}bc`>() +Record.empty<`a${string}bc`>() // $ExpectType Record -ReadonlyRecord.empty() +Record.empty() // ------------------------------------------------------------------------------------- // fromIterableWith // ------------------------------------------------------------------------------------- // $ExpectType Record -ReadonlyRecord.fromIterableWith([1, 2], ( +Record.fromIterableWith([1, 2], ( n // $ExpectType number ) => [String(n), n]) // $ExpectType Record -ReadonlyRecord.fromIterableWith([symA, symB], ( +Record.fromIterableWith([symA, symB], ( s // $ExpectType symbol ) => [String(s), s]) // $ExpectType Record -ReadonlyRecord.fromIterableWith([1, symA], ( +Record.fromIterableWith([1, symA], ( ns // $ExpectType number | symbol ) => [Predicate.isNumber(ns) ? String(ns) : ns, ns]) @@ -110,17 +110,17 @@ ReadonlyRecord.fromIterableWith([1, symA], ( // ------------------------------------------------------------------------------------- // $ExpectType Record -ReadonlyRecord.fromIterableBy([1, 2], ( +Record.fromIterableBy([1, 2], ( n // $ExpectType number ) => String(n)) // $ExpectType Record -ReadonlyRecord.fromIterableBy([symA, symB], ( +Record.fromIterableBy([symA, symB], ( s // $ExpectType symbol ) => String(s)) // $ExpectType Record -ReadonlyRecord.fromIterableBy([1, symA], ( +Record.fromIterableBy([1, symA], ( ns // $ExpectType number | symbol ) => Predicate.isNumber(ns) ? String(ns) : ns) @@ -129,26 +129,26 @@ ReadonlyRecord.fromIterableBy([1, symA], ( // ------------------------------------------------------------------------------------- // $ExpectType Record -ReadonlyRecord.fromEntries([["a", 1], ["b", 2]]) +Record.fromEntries([["a", 1], ["b", 2]]) // $ExpectType Record -ReadonlyRecord.fromEntries([[symA, 1], [symB, 2]]) +Record.fromEntries([[symA, 1], [symB, 2]]) // $ExpectType Record -ReadonlyRecord.fromEntries([["a", 1], [symB, 2]]) +Record.fromEntries([["a", 1], [symB, 2]]) // ------------------------------------------------------------------------------------- // collect // ------------------------------------------------------------------------------------- // $ExpectType number[] -ReadonlyRecord.collect(string$numbers, ( +Record.collect(string$numbers, ( _, // $ExpectType string a // $ExpectType number ) => a) // $ExpectType number[] -ReadonlyRecord.collect(template$numbers, ( +Record.collect(template$numbers, ( _, // $ExpectType `a${string}` a // $ExpectType number ) => a) @@ -156,14 +156,14 @@ ReadonlyRecord.collect(template$numbers, ( // $ExpectType number[] pipe( string$structAB, - ReadonlyRecord.collect(( + Record.collect(( _, // $ExpectType "a" | "b" a // $ExpectType number ) => a) ) // $ExpectType number[] -ReadonlyRecord.collect(string$structAB, ( +Record.collect(string$structAB, ( _, // $ExpectType "a" | "b" a // $ExpectType number ) => a) @@ -173,219 +173,219 @@ ReadonlyRecord.collect(string$structAB, ( // ------------------------------------------------------------------------------------- // $ExpectType [string, number][] -ReadonlyRecord.toEntries(string$numbers) +Record.toEntries(string$numbers) // $ExpectType [`a${string}`, number][] -ReadonlyRecord.toEntries(template$numbers) +Record.toEntries(template$numbers) // $ExpectType [string, number][] -ReadonlyRecord.toEntries(symbol$numbers) +Record.toEntries(symbol$numbers) declare const brandedRecord: Record, number> // should support brands // $ExpectType [string & Brand<"brandedString">, number][] -ReadonlyRecord.toEntries(brandedRecord) +Record.toEntries(brandedRecord) // $ExpectType ["a" | "b", number][] -ReadonlyRecord.toEntries(string$structAB) +Record.toEntries(string$structAB) // $ExpectType ["a" | "b", number][] -ReadonlyRecord.toEntries(string$structAB) +Record.toEntries(string$structAB) // ------------------------------------------------------------------------------------- // has // ------------------------------------------------------------------------------------- // $ExpectType boolean -ReadonlyRecord.has(string$numbers, "a") +Record.has(string$numbers, "a") // @ts-expect-error -ReadonlyRecord.has(string$numbers, symA) +Record.has(string$numbers, symA) // $ExpectType boolean -ReadonlyRecord.has(template$numbers, "a") +Record.has(template$numbers, "a") // @ts-expect-error -ReadonlyRecord.has(template$numbers, "b") +Record.has(template$numbers, "b") // $ExpectType boolean -ReadonlyRecord.has(symbol$numbers, symA) +Record.has(symbol$numbers, symA) // @ts-expect-error -ReadonlyRecord.has(symbol$numbers, "a") +Record.has(symbol$numbers, "a") // @ts-expect-error -ReadonlyRecord.has(string$structAB, "c") +Record.has(string$structAB, "c") // @ts-expect-error -ReadonlyRecord.has(string$structAB, symA) +Record.has(string$structAB, symA) // ------------------------------------------------------------------------------------- // get // ------------------------------------------------------------------------------------- // $ExpectType Option -pipe(string$numbers, ReadonlyRecord.get("a")) +pipe(string$numbers, Record.get("a")) // @ts-expect-error -pipe(string$numbers, ReadonlyRecord.get(symA)) +pipe(string$numbers, Record.get(symA)) // $ExpectType Option -pipe(template$numbers, ReadonlyRecord.get("a")) +pipe(template$numbers, Record.get("a")) // @ts-expect-error -pipe(template$numbers, ReadonlyRecord.get("b")) +pipe(template$numbers, Record.get("b")) // $ExpectType Option -pipe(symbol$numbers, ReadonlyRecord.get(symA)) +pipe(symbol$numbers, Record.get(symA)) // @ts-expect-error -pipe(symbol$numbers, ReadonlyRecord.get("a")) +pipe(symbol$numbers, Record.get("a")) // $ExpectType Option -pipe(string$structAB, ReadonlyRecord.get("a")) +pipe(string$structAB, Record.get("a")) // @ts-expect-error -pipe(string$structAB, ReadonlyRecord.get("c")) +pipe(string$structAB, Record.get("c")) // ------------------------------------------------------------------------------------- // modify // ------------------------------------------------------------------------------------- // $ExpectType Record -pipe(string$numbers, ReadonlyRecord.modify("a", () => 2)) +pipe(string$numbers, Record.modify("a", () => 2)) // $ExpectType Record -pipe(string$numbers, ReadonlyRecord.modify("a", () => true)) +pipe(string$numbers, Record.modify("a", () => true)) // $ExpectType Record<`a${string}`, number> -pipe(template$numbers, ReadonlyRecord.modify("a", () => 2)) +pipe(template$numbers, Record.modify("a", () => 2)) // $ExpectType Record<`a${string}`, number | boolean> -pipe(template$numbers, ReadonlyRecord.modify("a", () => true)) +pipe(template$numbers, Record.modify("a", () => true)) // @ts-expect-error -pipe(template$numbers, ReadonlyRecord.modify("b", () => true)) +pipe(template$numbers, Record.modify("b", () => true)) // $ExpectType Record -pipe(symbol$numbers, ReadonlyRecord.modify(symA, () => 2)) +pipe(symbol$numbers, Record.modify(symA, () => 2)) // $ExpectType Record -pipe(symbol$numbers, ReadonlyRecord.modify(symA, () => true)) +pipe(symbol$numbers, Record.modify(symA, () => true)) // $ExpectType Record<"a" | "b", number> -pipe(string$structAB, ReadonlyRecord.modify("a", () => 2)) +pipe(string$structAB, Record.modify("a", () => 2)) // $ExpectType Record<"a" | "b", number | boolean> -pipe(string$structAB, ReadonlyRecord.modify("a", () => true)) +pipe(string$structAB, Record.modify("a", () => true)) // ------------------------------------------------------------------------------------- // modifyOption // ------------------------------------------------------------------------------------- // $ExpectType Option> -pipe(string$numbers, ReadonlyRecord.modifyOption("a", () => 2)) +pipe(string$numbers, Record.modifyOption("a", () => 2)) // $ExpectType Option> -pipe(string$numbers, ReadonlyRecord.modifyOption("a", () => true)) +pipe(string$numbers, Record.modifyOption("a", () => true)) // $ExpectType Option> -pipe(template$numbers, ReadonlyRecord.modifyOption("a", () => 2)) +pipe(template$numbers, Record.modifyOption("a", () => 2)) // $ExpectType Option> -pipe(template$numbers, ReadonlyRecord.modifyOption("a", () => true)) +pipe(template$numbers, Record.modifyOption("a", () => true)) // @ts-expect-error -pipe(template$numbers, ReadonlyRecord.modifyOption("b", () => true)) +pipe(template$numbers, Record.modifyOption("b", () => true)) // $ExpectType Option> -pipe(symbol$numbers, ReadonlyRecord.modifyOption(symA, () => 2)) +pipe(symbol$numbers, Record.modifyOption(symA, () => 2)) // $ExpectType Option> -pipe(symbol$numbers, ReadonlyRecord.modifyOption(symA, () => true)) +pipe(symbol$numbers, Record.modifyOption(symA, () => true)) // $ExpectType Option> -pipe(string$structAB, ReadonlyRecord.modifyOption("a", () => 2)) +pipe(string$structAB, Record.modifyOption("a", () => 2)) // $ExpectType Option> -pipe(string$structAB, ReadonlyRecord.modifyOption("a", () => true)) +pipe(string$structAB, Record.modifyOption("a", () => true)) // ------------------------------------------------------------------------------------- // replaceOption // ------------------------------------------------------------------------------------- // $ExpectType Option> -pipe(string$numbers, ReadonlyRecord.replaceOption("a", 2)) +pipe(string$numbers, Record.replaceOption("a", 2)) // $ExpectType Option> -pipe(string$numbers, ReadonlyRecord.replaceOption("a", true)) +pipe(string$numbers, Record.replaceOption("a", true)) // $ExpectType Option> -pipe(template$numbers, ReadonlyRecord.replaceOption("a", 2)) +pipe(template$numbers, Record.replaceOption("a", 2)) // $ExpectType Option> -pipe(template$numbers, ReadonlyRecord.replaceOption("a", true)) +pipe(template$numbers, Record.replaceOption("a", true)) // @ts-expect-error -pipe(template$numbers, ReadonlyRecord.replaceOption("b", true)) +pipe(template$numbers, Record.replaceOption("b", true)) // $ExpectType Option> -pipe(symbol$numbers, ReadonlyRecord.replaceOption(symA, 2)) +pipe(symbol$numbers, Record.replaceOption(symA, 2)) // $ExpectType Option> -pipe(symbol$numbers, ReadonlyRecord.replaceOption(symA, true)) +pipe(symbol$numbers, Record.replaceOption(symA, true)) // $ExpectType Option> -pipe(string$structAB, ReadonlyRecord.replaceOption("a", 2)) +pipe(string$structAB, Record.replaceOption("a", 2)) // $ExpectType Option> -pipe(string$structAB, ReadonlyRecord.replaceOption("a", true)) +pipe(string$structAB, Record.replaceOption("a", true)) // ------------------------------------------------------------------------------------- // remove // ------------------------------------------------------------------------------------- // $ExpectType Record -pipe(string$numbers, ReadonlyRecord.remove("a")) +pipe(string$numbers, Record.remove("a")) // $ExpectType Record<`a${string}`, number> -pipe(template$numbers, ReadonlyRecord.remove("a")) +pipe(template$numbers, Record.remove("a")) // @ts-expect-error -pipe(template$numbers, ReadonlyRecord.remove("b")) +pipe(template$numbers, Record.remove("b")) // $ExpectType Record -pipe(symbol$numbers, ReadonlyRecord.remove(symA)) +pipe(symbol$numbers, Record.remove(symA)) // $ExpectType Record<"b", number> -pipe(string$structAB, ReadonlyRecord.remove("a")) +pipe(string$structAB, Record.remove("a")) // ------------------------------------------------------------------------------------- // pop // ------------------------------------------------------------------------------------- // $ExpectType Option<[number, Record]> -pipe(string$numbers, ReadonlyRecord.pop("a")) +pipe(string$numbers, Record.pop("a")) // $ExpectType Option<[number, Record<`a${string}`, number>]> -pipe(template$numbers, ReadonlyRecord.pop("a")) +pipe(template$numbers, Record.pop("a")) // @ts-expect-error -pipe(template$numbers, ReadonlyRecord.pop("b")) +pipe(template$numbers, Record.pop("b")) // $ExpectType Option<[number, Record]> -pipe(symbol$numbers, ReadonlyRecord.pop(symA)) +pipe(symbol$numbers, Record.pop(symA)) // $ExpectType Option<[number, Record<"b", number>]> -pipe(string$structAB, ReadonlyRecord.pop("a")) +pipe(string$structAB, Record.pop("a")) // ------------------------------------------------------------------------------------- // map // ------------------------------------------------------------------------------------- // $ExpectType Record -ReadonlyRecord.map(string$numbers, ( +Record.map(string$numbers, ( a, // $ExpectType number _ // $ExpectType string ) => a > 0) @@ -393,26 +393,26 @@ ReadonlyRecord.map(string$numbers, ( // $ExpectType Record pipe( string$numbers, - ReadonlyRecord.map(( + Record.map(( a, // $ExpectType number _ // $ExpectType string ) => a > 0) ) // $ExpectType Record<`a${string}`, boolean> -ReadonlyRecord.map(template$numbers, ( +Record.map(template$numbers, ( a, // $ExpectType number _ // $ExpectType `a${string}` ) => a > 0) // $ExpectType Record -ReadonlyRecord.map(symbol$numbers, ( +Record.map(symbol$numbers, ( a, // $ExpectType number _ // $ExpectType string ) => a + 1) // $ExpectType Record<"a" | "b", boolean> -ReadonlyRecord.map(string$structAB, ( +Record.map(string$structAB, ( a, // $ExpectType number _ // $ExpectType "a" | "b" ) => a > 0) @@ -420,7 +420,7 @@ ReadonlyRecord.map(string$structAB, ( // $ExpectType Record<"a" | "b", boolean> pipe( string$structAB, - ReadonlyRecord.map(( + Record.map(( a, // $ExpectType number _ // $ExpectType "a" | "b" ) => a > 0) @@ -431,19 +431,19 @@ pipe( // ------------------------------------------------------------------------------------- // $ExpectType Record -ReadonlyRecord.filterMap(string$numbers, ( +Record.filterMap(string$numbers, ( a, _ // $ExpectType string ) => a > 0 ? Option.some("positive") : Option.none()) // $ExpectType Record<`a${string}`, string> -ReadonlyRecord.filterMap(template$numbers, ( +Record.filterMap(template$numbers, ( a, _ // $ExpectType `a${string}` ) => a > 0 ? Option.some("positive") : Option.none()) // $ExpectType Record -ReadonlyRecord.filterMap(symbol$numbers, ( +Record.filterMap(symbol$numbers, ( a, _ // $ExpectType string ) => a > 0 ? Option.some("positive") : Option.none()) @@ -451,14 +451,14 @@ ReadonlyRecord.filterMap(symbol$numbers, ( // $ExpectType Record pipe( string$structAB, - ReadonlyRecord.filterMap(( + Record.filterMap(( a, key // $ExpectType "a" | "b" ) => key === "a" ? Option.some(a) : Option.none()) ) // $ExpectType Record -ReadonlyRecord.filterMap(string$structAB, ( +Record.filterMap(string$structAB, ( a, key // $ExpectType "a" | "b" ) => key === "a" ? Option.some(a) : Option.none()) @@ -468,13 +468,13 @@ ReadonlyRecord.filterMap(string$structAB, ( // ------------------------------------------------------------------------------------- // $ExpectType Record -ReadonlyRecord.filter(string$numbers, ( +Record.filter(string$numbers, ( a, // $ExpectType number _ // $ExpectType string ) => a > 0) // $ExpectType Record<`a${string}`, number> -ReadonlyRecord.filter(template$numbers, ( +Record.filter(template$numbers, ( a, // $ExpectType number _ // $ExpectType `a${string}` ) => a > 0) @@ -482,42 +482,42 @@ ReadonlyRecord.filter(template$numbers, ( // $ExpectType Record pipe( string$structAB, - ReadonlyRecord.filter(( + Record.filter(( _, // $ExpectType number key // $ExpectType "a" | "b" ) => key === "a") ) // $ExpectType Record -ReadonlyRecord.filter(string$structAB, ( +Record.filter(string$structAB, ( _, // $ExpectType number key // $ExpectType "a" | "b" ) => key === "a") // $ExpectType Record -ReadonlyRecord.filter(string$numbersOrStrings, predicateNumbersOrStrings) +Record.filter(string$numbersOrStrings, predicateNumbersOrStrings) // $ExpectType Record -ReadonlyRecord.filter(string$numbers, predicateNumbersOrStrings) +Record.filter(string$numbers, predicateNumbersOrStrings) // $ExpectType Record -pipe(string$numbersOrStrings, ReadonlyRecord.filter(predicateNumbersOrStrings)) +pipe(string$numbersOrStrings, Record.filter(predicateNumbersOrStrings)) // $ExpectType Record -pipe(string$numbers, ReadonlyRecord.filter(predicateNumbersOrStrings)) +pipe(string$numbers, Record.filter(predicateNumbersOrStrings)) // $ExpectType Record -ReadonlyRecord.filter(string$numbersOrStrings, Predicate.isNumber) +Record.filter(string$numbersOrStrings, Predicate.isNumber) // $ExpectType Record -pipe(string$numbersOrStrings, ReadonlyRecord.filter(Predicate.isNumber)) +pipe(string$numbersOrStrings, Record.filter(Predicate.isNumber)) // ------------------------------------------------------------------------------------- // partitionMap // ------------------------------------------------------------------------------------- // $ExpectType [left: Record, right: Record] -ReadonlyRecord.partitionMap(string$numbers, ( +Record.partitionMap(string$numbers, ( a, _ // $ExpectType string ) => a > 0 ? Either.right("positive") : Either.left(false)) @@ -525,14 +525,14 @@ ReadonlyRecord.partitionMap(string$numbers, ( // $ExpectType [left: Record, right: Record] pipe( string$structAB, - ReadonlyRecord.partitionMap(( + Record.partitionMap(( _, key // $ExpectType "a" | "b" ) => key === "a" ? Either.right("positive") : Either.left(false)) ) // $ExpectType [left: Record, right: Record] -ReadonlyRecord.partitionMap(string$structAB, ( +Record.partitionMap(string$structAB, ( _a, key // $ExpectType "a" | "b" ) => key === "a" ? Either.right("positive") : Either.left(false)) @@ -542,7 +542,7 @@ ReadonlyRecord.partitionMap(string$structAB, ( // ------------------------------------------------------------------------------------- // $ExpectType [excluded: Record, satisfying: Record] -ReadonlyRecord.partition(string$numbers, ( +Record.partition(string$numbers, ( a, // $ExpectType number _ // $ExpectType string ) => a > 0) @@ -550,77 +550,77 @@ ReadonlyRecord.partition(string$numbers, ( // $ExpectType [excluded: Record, satisfying: Record] pipe( string$structAB, - ReadonlyRecord.partition(( + Record.partition(( _a, // $ExpectType number key // $ExpectType "a" | "b" ) => key === "a") ) // $ExpectType [excluded: Record, satisfying: Record] -ReadonlyRecord.partition(string$structAB, ( +Record.partition(string$structAB, ( _a, // $ExpectType number key // $ExpectType "a" | "b" ) => key === "a") // $ExpectType [excluded: Record, satisfying: Record] -ReadonlyRecord.partition(string$numbersOrStrings, predicateNumbersOrStrings) +Record.partition(string$numbersOrStrings, predicateNumbersOrStrings) // $ExpectType [excluded: Record, satisfying: Record] -pipe(string$numbersOrStrings, ReadonlyRecord.partition(predicateNumbersOrStrings)) +pipe(string$numbersOrStrings, Record.partition(predicateNumbersOrStrings)) // $ExpectType [excluded: Record, satisfying: Record] -ReadonlyRecord.partition(string$numbersOrStrings, Predicate.isNumber) +Record.partition(string$numbersOrStrings, Predicate.isNumber) // $ExpectType [excluded: Record, satisfying: Record] -pipe(string$numbersOrStrings, ReadonlyRecord.partition(Predicate.isNumber)) +pipe(string$numbersOrStrings, Record.partition(Predicate.isNumber)) // ------------------------------------------------------------------------------------- // keys // ------------------------------------------------------------------------------------- // $ExpectType ("a" | "b")[] -ReadonlyRecord.keys(string$structAB) +Record.keys(string$structAB) // ------------------------------------------------------------------------------------- // values // ------------------------------------------------------------------------------------- // $ExpectType number[] -ReadonlyRecord.values(string$structAB) +Record.values(string$structAB) // ------------------------------------------------------------------------------------- // set // ------------------------------------------------------------------------------------- // $ExpectType Record -ReadonlyRecord.set(string$numbers, "a", 2) +Record.set(string$numbers, "a", 2) // $ExpectType Record -ReadonlyRecord.set(string$numbers, "a", true) +Record.set(string$numbers, "a", true) // $ExpectType Record<`a${string}`, number> -ReadonlyRecord.set(template$numbers, "a", 2) +Record.set(template$numbers, "a", 2) // $ExpectType Record<`a${string}`, number | boolean> -ReadonlyRecord.set(template$numbers, "a", true) +Record.set(template$numbers, "a", true) // $ExpectType Record<"b" | `a${string}`, number | boolean> -ReadonlyRecord.set(template$numbers, "b", true) +Record.set(template$numbers, "b", true) // $ExpectType Record<"a" | "b", number> -ReadonlyRecord.set(string$structAB, "a", 2) +Record.set(string$structAB, "a", 2) // $ExpectType Record<"a" | "b", number | boolean> -ReadonlyRecord.set(string$structAB, "a", true) +Record.set(string$structAB, "a", true) // $ExpectType Record<"a" | "b" | "c", number | boolean> -ReadonlyRecord.set(string$structAB, "c", true) +Record.set(string$structAB, "c", true) // ------------------------------------------------------------------------------------- // reduce // ------------------------------------------------------------------------------------- -ReadonlyRecord.reduce(string$structAB, "", ( +Record.reduce(string$structAB, "", ( _acc, // $ExpectType string _value, // $ExpectType number key // $ExpectType "a" | "b" @@ -630,14 +630,14 @@ ReadonlyRecord.reduce(string$structAB, "", ( // some // ------------------------------------------------------------------------------------- -ReadonlyRecord.some(string$structAB, ( +Record.some(string$structAB, ( _value, _key // $ExpectType "a" | "b" ) => false) pipe( string$numbersOrStrings, - ReadonlyRecord.some(( + Record.some(( _item // $ExpectType string | number ) => true) ) @@ -647,20 +647,20 @@ pipe( // ------------------------------------------------------------------------------------- // $ExpectType Record -ReadonlyRecord.union(string$numbers, string$numbers, (_, b) => b) +Record.union(string$numbers, string$numbers, (_, b) => b) // $ExpectType Record -ReadonlyRecord.union(string$numbers, string$numbersOrStrings, (_, b) => b) +Record.union(string$numbers, string$numbersOrStrings, (_, b) => b) // $ExpectType Record<"a" | "b" | "c" | "d", string | number> -ReadonlyRecord.union(string$structAB, string$structCD, (_, b) => b) +Record.union(string$structAB, string$structCD, (_, b) => b) // ------------------------------------------------------------------------------------- // singleton // ------------------------------------------------------------------------------------- // $ExpectType Record<"a", number> -ReadonlyRecord.singleton("a", 1) +Record.singleton("a", 1) // ------------------------------------------------------------------------------------- // every @@ -668,21 +668,21 @@ ReadonlyRecord.singleton("a", 1) pipe( string$numbersOrStrings, - ReadonlyRecord.every(( + Record.every(( _item // $ExpectType string | number ) => true) ) -ReadonlyRecord.every(string$structAB, ( +Record.every(string$structAB, ( _value, // $ExpectType number _key // $ExpectType "a" | "b" ) => false) -if (ReadonlyRecord.every(string$numbersOrStrings, Predicate.isString)) { +if (Record.every(string$numbersOrStrings, Predicate.isString)) { string$numbersOrStrings // $ExpectType ReadonlyRecord } -if (ReadonlyRecord.every(string$numbersOrStrings, Predicate.isString)) { +if (Record.every(string$numbersOrStrings, Predicate.isString)) { string$numbersOrStrings // $ExpectType ReadonlyRecord } @@ -691,29 +691,29 @@ if (ReadonlyRecord.every(string$numbersOrStrings, Predicate.isString)) { // ------------------------------------------------------------------------------------- // $ExpectType Record -ReadonlyRecord.intersection(string$numbers, string$numbersOrStrings, (a, _) => a) +Record.intersection(string$numbers, string$numbersOrStrings, (a, _) => a) // $ExpectType Record -ReadonlyRecord.intersection(string$numbers, string$numbersOrStrings, (_, b) => b) +Record.intersection(string$numbers, string$numbersOrStrings, (_, b) => b) // $ExpectType Record -ReadonlyRecord.intersection(string$structAB, string$structCD, (_, b) => b) +Record.intersection(string$structAB, string$structCD, (_, b) => b) // $ExpectType Record -ReadonlyRecord.intersection(string$structAB, string$structCD, (a, _) => a) +Record.intersection(string$structAB, string$structCD, (a, _) => a) // $ExpectType Record -ReadonlyRecord.intersection(string$numbers, string$numbers, (a, _) => a) +Record.intersection(string$numbers, string$numbers, (a, _) => a) // $ExpectType Record -ReadonlyRecord.intersection(string$numbers, string$structCD, (a, _) => a) +Record.intersection(string$numbers, string$structCD, (a, _) => a) // $ExpectType Record -ReadonlyRecord.intersection(string$structAB, { +Record.intersection(string$structAB, { c: 2 }, (a, _) => a) // $ExpectType Record<"b", number> -ReadonlyRecord.intersection(string$structAB, { +Record.intersection(string$structAB, { b: 2 }, (a, _) => a) diff --git a/packages/effect/dtslint/Struct.ts b/packages/effect/dtslint/Struct.ts index dcafcb678d..76dca239e8 100644 --- a/packages/effect/dtslint/Struct.ts +++ b/packages/effect/dtslint/Struct.ts @@ -122,7 +122,7 @@ pipe(symbolStruct, S.pick(asym, bsym)) // $ExpectType { [asym]?: number; [bsym]?: number; } pipe(symbolNumberRecord, S.pick(asym, bsym)) -// $ExpectType { 2: number; 1: string; } +// $ExpectType { 1: string; 2: number; } pipe(numberStruct, S.pick(1, 2)) // @ts-expect-error @@ -134,7 +134,7 @@ S.pick(4)(numberStruct) // $ExpectType { [x: number]: unknown; } S.pick(4 as number)(numberStruct) -// $ExpectType { 2?: number; 1?: number; } +// $ExpectType { 1?: number; 2?: number; } pipe(numberNumberRecord, S.pick(1, 2)) // $ExpectType { ab?: number; aa?: number; } diff --git a/packages/effect/src/ReadonlyArray.ts b/packages/effect/src/Array.ts similarity index 97% rename from packages/effect/src/ReadonlyArray.ts rename to packages/effect/src/Array.ts index 89a7b15f7f..7a3f1d6098 100644 --- a/packages/effect/src/ReadonlyArray.ts +++ b/packages/effect/src/Array.ts @@ -11,14 +11,14 @@ import * as Equivalence from "./Equivalence.js" import type { LazyArg } from "./Function.js" import { dual, identity } from "./Function.js" import type { TypeLambda } from "./HKT.js" -import * as readonlyArray from "./internal/readonlyArray.js" +import * as readonlyArray from "./internal/array.js" import * as EffectIterable from "./Iterable.js" import type { Option } from "./Option.js" import * as O from "./Option.js" import * as Order from "./Order.js" import type { Predicate, Refinement } from "./Predicate.js" import { isBoolean } from "./Predicate.js" -import * as ReadonlyRecord from "./ReadonlyRecord.js" +import * as Record from "./Record.js" import * as Tuple from "./Tuple.js" /** @@ -51,13 +51,21 @@ export const make = >( ...elements: Elements ): NonEmptyArray => elements +/** + * Creates a new `Array` of the specified length. + * + * @category constructors + * @since 2.0.0 + */ +export const allocate = (n: number): Array => new Array(n) + /** * Return a `NonEmptyArray` of length `n` with element `i` initialized with `f(i)`. * * **Note**. `n` is normalized to an integer >= 1. * * @example - * import { makeBy } from 'effect/ReadonlyArray' + * import { makeBy } from 'effect/Array' * * assert.deepStrictEqual(makeBy(5, n => n * 2), [0, 2, 4, 6, 8]) * @@ -66,18 +74,18 @@ export const make = >( */ export const makeBy = (n: number, f: (i: number) => A): NonEmptyArray => { const max = Math.max(1, Math.floor(n)) - const out: NonEmptyArray = [f(0)] - for (let i = 1; i < max; i++) { - out.push(f(i)) + const out = new Array(max) + for (let i = 0; i < max; i++) { + out[i] = f(i) } - return out + return out as NonEmptyArray } /** * Return a `NonEmptyArray` containing a range of integers, including both endpoints. * * @example - * import { range } from 'effect/ReadonlyArray' + * import { range } from 'effect/Array' * * assert.deepStrictEqual(range(1, 3), [1, 2, 3]) * @@ -93,7 +101,7 @@ export const range = (start: number, end: number): NonEmptyArray => * **Note**. `n` is normalized to an integer >= 1. * * @example - * import { replicate } from 'effect/ReadonlyArray' + * import { replicate } from 'effect/Array' * * assert.deepStrictEqual(replicate("a", 3), ["a", "a", "a"]) * @@ -120,7 +128,7 @@ export const fromIterable = (collection: Iterable): Array => * @param self - The record to transform. * * @example - * import { fromRecord } from "effect/ReadonlyArray" + * import { fromRecord } from "effect/Array" * * const x = { a: 1, b: 2, c: 3 } * assert.deepStrictEqual(fromRecord(x), [["a", 1], ["b", 2], ["c", 3]]) @@ -128,7 +136,7 @@ export const fromIterable = (collection: Iterable): Array => * @category conversions * @since 2.0.0 */ -export const fromRecord: (self: Readonly>) => Array<[K, A]> = ReadonlyRecord.toEntries +export const fromRecord: (self: Readonly>) => Array<[K, A]> = Record.toEntries /** * @category conversions @@ -233,10 +241,10 @@ export const prepend: { * If either array is non-empty, the result is also a non-empty array. * * @example - * import * as ReadonlyArray from "effect/ReadonlyArray" + * import * as Array from "effect/Array" * * assert.deepStrictEqual( - * ReadonlyArray.prependAll([1, 2], ["a", "b"]), + * Array.prependAll([1, 2], ["a", "b"]), * ["a", "b", 1, 2] * ) * @@ -323,13 +331,29 @@ export const scanRight: { return out }) +/** + * Determine if `unknown` is an Array. + * + * @param self - The value to check. + * + * @example + * import { isArray } from "effect/Array" + * + * assert.deepStrictEqual(isArray(null), false); + * assert.deepStrictEqual(isArray([1, 2, 3]), true); + * + * @category guards + * @since 2.0.0 + */ +export const isArray: (self: unknown) => self is Array = Array.isArray + /** * Determine if an `Array` is empty narrowing down the type to `[]`. * * @param self - The `Array` to check. * * @example - * import { isEmptyArray } from "effect/ReadonlyArray" + * import { isEmptyArray } from "effect/Array" * * assert.deepStrictEqual(isEmptyArray([]), true); * assert.deepStrictEqual(isEmptyArray([1, 2, 3]), false); @@ -345,7 +369,7 @@ export const isEmptyArray = (self: Array): self is [] => self.length === 0 * @param self - The `ReadonlyArray` to check. * * @example - * import { isEmptyReadonlyArray } from "effect/ReadonlyArray" + * import { isEmptyReadonlyArray } from "effect/Array" * * assert.deepStrictEqual(isEmptyReadonlyArray([]), true); * assert.deepStrictEqual(isEmptyReadonlyArray([1, 2, 3]), false); @@ -363,7 +387,7 @@ export const isEmptyReadonlyArray: (self: ReadonlyArray) => self is readon * @param self - The `Array` to check. * * @example - * import { isNonEmptyArray } from "effect/ReadonlyArray" + * import { isNonEmptyArray } from "effect/Array" * * assert.deepStrictEqual(isNonEmptyArray([]), false); * assert.deepStrictEqual(isNonEmptyArray([1, 2, 3]), true); @@ -381,7 +405,7 @@ export const isNonEmptyArray: (self: Array) => self is NonEmptyArray = * @param self - The `ReadonlyArray` to check. * * @example - * import { isNonEmptyReadonlyArray } from "effect/ReadonlyArray" + * import { isNonEmptyReadonlyArray } from "effect/Array" * * assert.deepStrictEqual(isNonEmptyReadonlyArray([]), false); * assert.deepStrictEqual(isNonEmptyReadonlyArray([1, 2, 3]), true); @@ -1317,15 +1341,15 @@ export const group: (self: NonEmptyReadonlyArray) => NonEmptyArray( f: (a: A) => K - ): (self: Iterable) => Record, NonEmptyArray> + ): (self: Iterable) => Record, NonEmptyArray> ( self: Iterable, f: (a: A) => K - ): Record, NonEmptyArray> + ): Record, NonEmptyArray> } = dual(2, ( self: Iterable, f: (a: A) => K -): Record, NonEmptyArray> => { +): Record, NonEmptyArray> => { const out: Record> = {} for (const a of self) { const k = f(a) @@ -1628,7 +1652,7 @@ export const partitionMap: { * Retrieves the `Some` values from an `Iterable` of `Option`s, collecting them into an array. * * @example - * import { getSomes } from "effect/ReadonlyArray" + * import { getSomes } from "effect/Array" * import { some, none } from "effect/Option" * * assert.deepStrictEqual( @@ -1645,7 +1669,7 @@ export const getSomes: (self: Iterable>) => Array = filterMap(id * Retrieves the `Left` values from an `Iterable` of `Either`s, collecting them into an array. * * @example - * import { getLefts } from "effect/ReadonlyArray" + * import { getLefts } from "effect/Array" * import { right, left } from "effect/Either" * * assert.deepStrictEqual( @@ -1671,7 +1695,7 @@ export const getLefts = (self: Iterable>): Array => { * Retrieves the `Right` values from an `Iterable` of `Either`s, collecting them into an array. * * @example - * import { getRights } from "effect/ReadonlyArray" + * import { getRights } from "effect/Array" * import { right, left } from "effect/Either" * * assert.deepStrictEqual( diff --git a/packages/effect/src/Brand.ts b/packages/effect/src/Brand.ts index d13675e922..2ff9bce4d7 100644 --- a/packages/effect/src/Brand.ts +++ b/packages/effect/src/Brand.ts @@ -16,11 +16,11 @@ * * @since 2.0.0 */ +import * as Array from "./Array.js" import * as Either from "./Either.js" import { identity } from "./Function.js" import * as Option from "./Option.js" import type { Predicate } from "./Predicate.js" -import * as ReadonlyArray from "./ReadonlyArray.js" import type * as Types from "./Types.js" /** @@ -69,7 +69,7 @@ export declare namespace Brand { * @since 2.0.0 * @category models */ - export interface BrandErrors extends ReadonlyArray {} + export interface BrandErrors extends Array {} /** * Represents an error that occurs when the provided value of the branded type does not pass the refinement predicate. @@ -183,7 +183,7 @@ export const error = (message: string, meta?: unknown): Brand.BrandErrors => [{ */ export const errors: (...errors: Array) => Brand.BrandErrors = ( ...errors: Array -): Brand.BrandErrors => ReadonlyArray.flatten(errors) +): Brand.BrandErrors => Array.flatten(errors) /** * Returns a `Brand.Constructor` that can construct a branded type from an unbranded value using the provided `refinement` diff --git a/packages/effect/src/Chunk.ts b/packages/effect/src/Chunk.ts index c523ebd266..4c69239a79 100644 --- a/packages/effect/src/Chunk.ts +++ b/packages/effect/src/Chunk.ts @@ -1,6 +1,8 @@ /** * @since 2.0.0 */ +import * as RA from "./Array.js" +import type { NonEmptyReadonlyArray } from "./Array.js" import type { Either } from "./Either.js" import * as Equal from "./Equal.js" import * as Equivalence from "./Equivalence.js" @@ -15,8 +17,6 @@ import * as Order from "./Order.js" import type { Pipeable } from "./Pipeable.js" import { pipeArguments } from "./Pipeable.js" import { hasProperty, type Predicate, type Refinement } from "./Predicate.js" -import * as RA from "./ReadonlyArray.js" -import type { NonEmptyReadonlyArray } from "./ReadonlyArray.js" import type { Covariant } from "./Types.js" const TypeId: unique symbol = Symbol.for("effect/Chunk") as TypeId diff --git a/packages/effect/src/Cron.ts b/packages/effect/src/Cron.ts index 67e07371b7..42a0e2a936 100644 --- a/packages/effect/src/Cron.ts +++ b/packages/effect/src/Cron.ts @@ -1,6 +1,7 @@ /** * @since 2.0.0 */ +import * as Array from "./Array.js" import * as Either from "./Either.js" import * as Equal from "./Equal.js" import * as equivalence from "./Equivalence.js" @@ -10,7 +11,6 @@ import { format, type Inspectable, NodeInspectSymbol } from "./Inspectable.js" import * as N from "./Number.js" import { type Pipeable, pipeArguments } from "./Pipeable.js" import { hasProperty } from "./Predicate.js" -import * as ReadonlyArray from "./ReadonlyArray.js" import * as String from "./String.js" import type { Mutable } from "./Types.js" @@ -46,11 +46,11 @@ const CronProto: Omit }): Cron => { const o: Mutable = Object.create(CronProto) - o.minutes = new Set(ReadonlyArray.sort(minutes, N.Order)) - o.hours = new Set(ReadonlyArray.sort(hours, N.Order)) - o.days = new Set(ReadonlyArray.sort(days, N.Order)) - o.months = new Set(ReadonlyArray.sort(months, N.Order)) - o.weekdays = new Set(ReadonlyArray.sort(weekdays, N.Order)) + o.minutes = new Set(Array.sort(minutes, N.Order)) + o.hours = new Set(Array.sort(hours, N.Order)) + o.days = new Set(Array.sort(days, N.Order)) + o.months = new Set(Array.sort(months, N.Order)) + o.weekdays = new Set(Array.sort(weekdays, N.Order)) return o } @@ -364,7 +364,7 @@ export const Equivalence: equivalence.Equivalence = equivalence.make((self const restrictionsArrayEquals = equivalence.array(equivalence.number) const restrictionsEquals = (self: ReadonlySet, that: ReadonlySet): boolean => - restrictionsArrayEquals(ReadonlyArray.fromIterable(self), ReadonlyArray.fromIterable(that)) + restrictionsArrayEquals(Array.fromIterable(self), Array.fromIterable(that)) /** * Checks if two `Cron`s are equal. diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 0b0df2b5e1..3b6cbf5d2d 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -5196,7 +5196,7 @@ export const makeSpanScoped: ( readonly parent?: Tracer.AnySpan | undefined readonly root?: boolean | undefined readonly context?: Context.Context | undefined - } + } | undefined ) => Effect = fiberRuntime.makeSpanScoped /** diff --git a/packages/effect/src/FiberRefs.ts b/packages/effect/src/FiberRefs.ts index f1efaca7c5..f3f0029e12 100644 --- a/packages/effect/src/FiberRefs.ts +++ b/packages/effect/src/FiberRefs.ts @@ -1,6 +1,7 @@ /** * @since 2.0.0 */ +import type * as Arr from "./Array.js" import type * as Effect from "./Effect.js" import type * as FiberId from "./FiberId.js" import type * as FiberRef from "./FiberRef.js" @@ -8,7 +9,6 @@ import type * as HashSet from "./HashSet.js" import * as internal from "./internal/fiberRefs.js" import type * as Option from "./Option.js" import type { Pipeable } from "./Pipeable.js" -import type * as Arr from "./ReadonlyArray.js" /** * @since 2.0.0 diff --git a/packages/effect/src/Iterable.ts b/packages/effect/src/Iterable.ts index 61fa9b03f5..92b07f6267 100644 --- a/packages/effect/src/Iterable.ts +++ b/packages/effect/src/Iterable.ts @@ -4,6 +4,7 @@ * @since 2.0.0 */ +import type { NonEmptyArray } from "./Array.js" import type { Either } from "./Either.js" import * as E from "./Either.js" import * as Equal from "./Equal.js" @@ -11,8 +12,7 @@ import { dual, identity } from "./Function.js" import type { Option } from "./Option.js" import * as O from "./Option.js" import { isBoolean } from "./Predicate.js" -import type { NonEmptyArray } from "./ReadonlyArray.js" -import type * as ReadonlyRecord from "./ReadonlyRecord.js" +import type * as Record from "./Record.js" import * as Tuple from "./Tuple.js" /** @@ -626,15 +626,15 @@ export const group: (self: Iterable) => Iterable> = group export const groupBy: { ( f: (a: A) => K - ): (self: Iterable) => Record, NonEmptyArray> + ): (self: Iterable) => Record, NonEmptyArray> ( self: Iterable, f: (a: A) => K - ): Record, NonEmptyArray> + ): Record, NonEmptyArray> } = dual(2, ( self: Iterable, f: (a: A) => K -): Record, NonEmptyArray> => { +): Record, NonEmptyArray> => { const out: Record> = {} for (const a of self) { const k = f(a) diff --git a/packages/effect/src/List.ts b/packages/effect/src/List.ts index ad9057e24c..a1e95dd856 100644 --- a/packages/effect/src/List.ts +++ b/packages/effect/src/List.ts @@ -21,6 +21,7 @@ * Licensed under Apache License 2.0 * (http://www.apache.org/licenses/LICENSE-2.0). */ +import * as Array from "./Array.js" import * as Chunk from "./Chunk.js" import * as Either from "./Either.js" import * as Equal from "./Equal.js" @@ -32,7 +33,6 @@ import * as Option from "./Option.js" import type { Pipeable } from "./Pipeable.js" import { pipeArguments } from "./Pipeable.js" import { hasProperty, type Predicate, type Refinement } from "./Predicate.js" -import * as ReadonlyArray from "./ReadonlyArray.js" /** * Represents an immutable linked list of elements of type `A`. @@ -84,14 +84,14 @@ export interface Cons extends Iterable, Equal.Equal, Pipeable, Inspect * @category conversions * @since 2.0.0 */ -export const toArray = (self: List): Array => Array.from(self) +export const toArray = (self: List): Array => Array.fromIterable(self) /** * @category equivalence * @since 2.0.0 */ export const getEquivalence = (isEquivalent: Equivalence.Equivalence): Equivalence.Equivalence> => - Equivalence.mapInput(ReadonlyArray.getEquivalence(isEquivalent), toArray) + Equivalence.mapInput(Array.getEquivalence(isEquivalent), toArray) const _equivalence = getEquivalence(Equal.equals) diff --git a/packages/effect/src/MutableHashMap.ts b/packages/effect/src/MutableHashMap.ts index 501fd5af10..16071b33d5 100644 --- a/packages/effect/src/MutableHashMap.ts +++ b/packages/effect/src/MutableHashMap.ts @@ -1,6 +1,7 @@ /** * @since 2.0.0 */ +import type { NonEmptyArray } from "./Array.js" import * as Equal from "./Equal.js" import { dual } from "./Function.js" import * as Hash from "./Hash.js" @@ -8,7 +9,6 @@ import { format, type Inspectable, NodeInspectSymbol, toJSON } from "./Inspectab import * as Option from "./Option.js" import type { Pipeable } from "./Pipeable.js" import { pipeArguments } from "./Pipeable.js" -import type { NonEmptyArray } from "./ReadonlyArray.js" const TypeId: unique symbol = Symbol.for("effect/MutableHashMap") as TypeId diff --git a/packages/effect/src/ReadonlyRecord.ts b/packages/effect/src/Record.ts similarity index 96% rename from packages/effect/src/ReadonlyRecord.ts rename to packages/effect/src/Record.ts index 0a0e3cec47..f7b98bf79f 100644 --- a/packages/effect/src/ReadonlyRecord.ts +++ b/packages/effect/src/Record.ts @@ -68,7 +68,7 @@ export const empty = (): Record< * @param self - record to test for emptiness. * * @example - * import { isEmptyRecord } from "effect/ReadonlyRecord" + * import { isEmptyRecord } from "effect/Record" * * assert.deepStrictEqual(isEmptyRecord({}), true); * assert.deepStrictEqual(isEmptyRecord({ a: 3 }), false); @@ -85,7 +85,7 @@ export const isEmptyRecord = (self: Record): self is * @param self - record to test for emptiness. * * @example - * import { isEmptyReadonlyRecord } from "effect/ReadonlyRecord" + * import { isEmptyReadonlyRecord } from "effect/Record" * * assert.deepStrictEqual(isEmptyReadonlyRecord({}), true); * assert.deepStrictEqual(isEmptyReadonlyRecord({ a: 3 }), false); @@ -105,7 +105,7 @@ export const isEmptyReadonlyRecord: ( * @param f - A projection function that maps values of the iterable to a tuple of a key and a value. * * @example - * import { fromIterableWith } from "effect/ReadonlyRecord" + * import { fromIterableWith } from "effect/Record" * * const input = [1, 2, 3, 4] * @@ -147,7 +147,7 @@ export const fromIterableWith: { * @param f - A function that extracts the key for each element. * * @example - * import { fromIterableBy } from "effect/ReadonlyRecord" + * import { fromIterableBy } from "effect/Record" * * const users = [ * { id: "2", name: "name2" }, @@ -179,7 +179,7 @@ export const fromIterableBy = ( * @param self - The iterable of key-value pairs. * * @example - * import { fromEntries } from "effect/ReadonlyRecord" + * import { fromEntries } from "effect/Record" * * const input: Array<[string, number]> = [["a", 1], ["b", 2]] * @@ -199,7 +199,7 @@ export const fromEntries: ( * @param f - The custom mapping function to apply to each key/value of the record. * * @example - * import { collect } from "effect/ReadonlyRecord" + * import { collect } from "effect/Record" * * const x = { a: 1, b: 2, c: 3 } * assert.deepStrictEqual(collect(x, (key, n) => [key, n]), [["a", 1], ["b", 2], ["c", 3]]) @@ -227,7 +227,7 @@ export const collect: { * @param self - The record to transform. * * @example - * import { toEntries } from "effect/ReadonlyRecord" + * import { toEntries } from "effect/Record" * * const x = { a: 1, b: 2, c: 3 } * assert.deepStrictEqual(toEntries(x), [["a", 1], ["b", 2], ["c", 3]]) @@ -246,7 +246,7 @@ export const toEntries: (self: ReadonlyRecord) => Arr * @param self - A record to calculate the number of key/value pairs in. * * @example - * import { size } from "effect/ReadonlyRecord"; + * import { size } from "effect/Record"; * * assert.deepStrictEqual(size({ a: "a", b: 1, c: true }), 3); * @@ -261,7 +261,7 @@ export const size = (self: ReadonlyRecord): number => * @param key - the key to look for in the record. * * @example - * import { empty, has } from "effect/ReadonlyRecord" + * import { empty, has } from "effect/Record" * * assert.deepStrictEqual(has({ a: 1, b: 2 }, "a"), true); * assert.deepStrictEqual(has(empty(), "c"), false); @@ -291,7 +291,7 @@ export const has: { * @param key - Key to retrieve from record. * * @example - * import { get } from "effect/ReadonlyRecord" + * import { get } from "effect/Record" * import { some, none } from "effect/Option" * * const person: Record = { name: "John Doe", age: 35 } @@ -319,7 +319,7 @@ export const get: { * @param f - The function to apply to the element. * * @example - * import { modify } from "effect/ReadonlyRecord" + * import { modify } from "effect/Record" * import { some, none } from "effect/Option" * * const f = (x: number) => x * 2 @@ -360,7 +360,7 @@ export const modify: { * @param f - The function to apply to the element. * * @example - * import { modifyOption } from "effect/ReadonlyRecord" + * import { modifyOption } from "effect/Record" * import { some, none } from "effect/Option" * * const f = (x: number) => x * 2 @@ -408,7 +408,7 @@ export const modifyOption: { * @param b - The new value to replace the existing value with. * * @example - * import { empty, replaceOption } from "effect/ReadonlyRecord" + * import { empty, replaceOption } from "effect/Record" * import { some, none } from "effect/Option" * * assert.deepStrictEqual( @@ -446,7 +446,7 @@ export const replaceOption: { * @param key - the key to remove from the record. * * @example - * import { remove } from "effect/ReadonlyRecord" + * import { remove } from "effect/Record" * * assert.deepStrictEqual(remove({ a: 1, b: 2 }, "a"), { b: 2 }) * @@ -476,7 +476,7 @@ export const remove: { * @param key - The key of the property to retrieve. * * @example - * import { pop } from "effect/ReadonlyRecord" + * import { pop } from "effect/Record" * import { some, none } from 'effect/Option' * * assert.deepStrictEqual(pop({ a: 1, b: 2 }, "a"), some([1, { b: 2 }])) @@ -506,7 +506,7 @@ export const pop: { * @param f - A transformation function that will be applied to each of the values in the record. * * @example - * import { map } from "effect/ReadonlyRecord" + * import { map } from "effect/Record" * * const f = (n: number) => `-${n}` * @@ -537,7 +537,7 @@ export const map: { * Maps the keys of a `ReadonlyRecord` while preserving the corresponding values. * * @example - * import { mapKeys } from "effect/ReadonlyRecord" + * import { mapKeys } from "effect/Record" * * assert.deepStrictEqual(mapKeys({ a: 3, b: 5 }, (key) => key.toUpperCase()), { A: 3, B: 5 }) * @@ -571,7 +571,7 @@ export const mapKeys: { * Maps entries of a `ReadonlyRecord` using the provided function, allowing modification of both keys and corresponding values. * * @example - * import { mapEntries } from "effect/ReadonlyRecord" + * import { mapEntries } from "effect/Record" * * assert.deepStrictEqual(mapEntries({ a: 3, b: 5 }, (a, key) => [key.toUpperCase(), a + 1]), { A: 4, B: 6 }) * @@ -609,7 +609,7 @@ export const mapEntries: { * @param f - The transformation function. * * @example - * import { filterMap } from "effect/ReadonlyRecord" + * import { filterMap } from "effect/Record" * import { some, none } from 'effect/Option' * * const x = { a: 1, b: 2, c: 3 } @@ -650,7 +650,7 @@ export const filterMap: { * @param predicate - A function that returns a `boolean` value to determine if the entry should be included in the new record. * * @example - * import { filter } from "effect/ReadonlyRecord" + * import { filter } from "effect/Record" * * const x = { a: 1, b: 2, c: 3, d: 4 } * assert.deepStrictEqual(filter(x, (n) => n > 2), { c: 3, d: 4 }) @@ -695,7 +695,7 @@ export const filter: { * @param self - A record with `Option` values. * * @example - * import { getSomes } from "effect/ReadonlyRecord" + * import { getSomes } from "effect/Record" * import { some, none } from "effect/Option" * * assert.deepStrictEqual( @@ -716,7 +716,7 @@ export const getSomes: ( * Given a record with `Either` values, returns a new record containing only the `Left` values, preserving the original keys. * * @example - * import { getLefts } from "effect/ReadonlyRecord" + * import { getLefts } from "effect/Record" * import { right, left } from "effect/Either" * * assert.deepStrictEqual( @@ -745,7 +745,7 @@ export const getLefts = ( * Given a record with `Either` values, returns a new record containing only the `Right` values, preserving the original keys. * * @example - * import { getRights } from "effect/ReadonlyRecord" + * import { getRights } from "effect/Record" * import { right, left } from "effect/Either" * * assert.deepStrictEqual( @@ -777,7 +777,7 @@ export const getRights = ( * @param f - The predicate function to apply to each element. * * @example - * import { partitionMap } from "effect/ReadonlyRecord" + * import { partitionMap } from "effect/Record" * import { left, right } from 'effect/Either' * * const x = { a: 1, b: 2, c: 3 } @@ -824,7 +824,7 @@ export const partitionMap: { * @param self - the record to partition. * * @example - * import { separate } from "effect/ReadonlyRecord" + * import { separate } from "effect/Record" * import { left, right } from 'effect/Either' * * assert.deepStrictEqual( @@ -846,7 +846,7 @@ export const separate: ( * @param predicate - The partitioning function to determine the partitioning of each value of the record. * * @example - * import { partition } from "effect/ReadonlyRecord" + * import { partition } from "effect/Record" * * assert.deepStrictEqual( * partition({ a: 1, b: 3 }, (n) => n > 2), @@ -924,7 +924,7 @@ export const values = (self: ReadonlyRecord): Array(self: ReadonlyArray): self is NonEmptyArray => self.length > 0 diff --git a/packages/effect/src/internal/cause.ts b/packages/effect/src/internal/cause.ts index ba7353d5f6..883bdc6b80 100644 --- a/packages/effect/src/internal/cause.ts +++ b/packages/effect/src/internal/cause.ts @@ -1,3 +1,4 @@ +import * as Array from "../Array.js" import type * as Cause from "../Cause.js" import * as Chunk from "../Chunk.js" import * as Either from "../Either.js" @@ -11,7 +12,6 @@ import * as Option from "../Option.js" import { pipeArguments } from "../Pipeable.js" import { hasProperty, isFunction } from "../Predicate.js" import type { Predicate, Refinement } from "../Predicate.js" -import * as ReadonlyArray from "../ReadonlyArray.js" import type { AnySpan, Span } from "../Tracer.js" import { getBugErrorMessage } from "./errors.js" import * as OpCodes from "./opCodes/cause.js" @@ -584,7 +584,7 @@ const flattenCauseLoop = ( while (1) { const [parallel, sequential] = pipe( causes, - ReadonlyArray.reduce( + Array.reduce( [HashSet.empty(), Chunk.empty>()] as const, ([parallel, sequential], cause) => { const [par, seq] = evaluateCause(cause) @@ -1046,7 +1046,7 @@ export const prettyErrorMessage = (u: unknown): string => { hasProperty(u, "toString") && isFunction(u["toString"]) && u["toString"] !== Object.prototype.toString && - u["toString"] !== Array.prototype.toString + u["toString"] !== globalThis.Array.prototype.toString ) { return u["toString"]() } diff --git a/packages/effect/src/internal/configError.ts b/packages/effect/src/internal/configError.ts index 29d17328cd..6d8e6d1944 100644 --- a/packages/effect/src/internal/configError.ts +++ b/packages/effect/src/internal/configError.ts @@ -1,9 +1,9 @@ +import * as RA from "../Array.js" import type * as Cause from "../Cause.js" import type * as ConfigError from "../ConfigError.js" import * as Either from "../Either.js" import { constFalse, constTrue, dual, pipe } from "../Function.js" import { hasProperty } from "../Predicate.js" -import * as RA from "../ReadonlyArray.js" import * as OpCodes from "./opCodes/configError.js" /** @internal */ diff --git a/packages/effect/src/internal/configProvider.ts b/packages/effect/src/internal/configProvider.ts index 02011a5380..bccd0b6848 100644 --- a/packages/effect/src/internal/configProvider.ts +++ b/packages/effect/src/internal/configProvider.ts @@ -1,3 +1,4 @@ +import * as Array from "../Array.js" import type * as Config from "../Config.js" import type * as ConfigError from "../ConfigError.js" import type * as ConfigProvider from "../ConfigProvider.js" @@ -12,7 +13,6 @@ import * as HashSet from "../HashSet.js" import * as number from "../Number.js" import * as Option from "../Option.js" import { pipeArguments } from "../Pipeable.js" -import * as ReadonlyArray from "../ReadonlyArray.js" import * as regexp from "../RegExp.js" import type * as _config from "./config.js" import * as configError from "./configError.js" @@ -85,12 +85,12 @@ export const makeFlat = ( export const fromFlat = (flat: ConfigProvider.ConfigProvider.Flat): ConfigProvider.ConfigProvider => make({ load: (config) => - core.flatMap(fromFlatLoop(flat, ReadonlyArray.empty(), config, false), (chunk) => - Option.match(ReadonlyArray.head(chunk), { + core.flatMap(fromFlatLoop(flat, Array.empty(), config, false), (chunk) => + Option.match(Array.head(chunk), { onNone: () => core.fail( configError.MissingData( - ReadonlyArray.empty(), + Array.empty(), `Expected a single value having structure: ${config}` ) ), @@ -104,7 +104,7 @@ export const fromEnv = ( config?: Partial ): ConfigProvider.ConfigProvider => { const { pathDelim, seqDelim } = Object.assign({}, { pathDelim: "_", seqDelim: "," }, config) - const makePathString = (path: ReadonlyArray): string => pipe(path, ReadonlyArray.join(pathDelim)) + const makePathString = (path: ReadonlyArray): string => pipe(path, Array.join(pathDelim)) const unmakePathString = (pathString: string): ReadonlyArray => pathString.split(pathDelim) const getEnv = () => @@ -131,10 +131,10 @@ export const fromEnv = ( core.sync(() => { const current = getEnv() const keys = Object.keys(current) - const keyPaths = Array.from(keys).map((value) => unmakePathString(value.toUpperCase())) + const keyPaths = keys.map((value) => unmakePathString(value.toUpperCase())) const filteredKeyPaths = keyPaths.filter((keyPath) => { for (let i = 0; i < path.length; i++) { - const pathComponent = pipe(path, ReadonlyArray.unsafeGet(i)) + const pathComponent = pipe(path, Array.unsafeGet(i)) const currentElement = keyPath[i] if (currentElement === undefined || pathComponent !== currentElement) { return false @@ -154,11 +154,11 @@ export const fromMap = ( config?: Partial ): ConfigProvider.ConfigProvider => { const { pathDelim, seqDelim } = Object.assign({ seqDelim: ",", pathDelim: "." }, config) - const makePathString = (path: ReadonlyArray): string => pipe(path, ReadonlyArray.join(pathDelim)) + const makePathString = (path: ReadonlyArray): string => pipe(path, Array.join(pathDelim)) const unmakePathString = (pathString: string): ReadonlyArray => pathString.split(pathDelim) const mapWithIndexSplit = splitIndexInKeys( map, - (str) => Array.from(unmakePathString(str)), + (str) => unmakePathString(str), makePathString ) const load = ( @@ -180,10 +180,10 @@ export const fromMap = ( path: ReadonlyArray ): Effect.Effect, ConfigError.ConfigError> => core.sync(() => { - const keyPaths = Array.from(mapWithIndexSplit.keys()).map(unmakePathString) + const keyPaths = Array.fromIterable(mapWithIndexSplit.keys()).map(unmakePathString) const filteredKeyPaths = keyPaths.filter((keyPath) => { for (let i = 0; i < path.length; i++) { - const pathComponent = pipe(path, ReadonlyArray.unsafeGet(i)) + const pathComponent = pipe(path, Array.unsafeGet(i)) const currentElement = keyPath[i] if (currentElement === undefined || pathComponent !== currentElement) { return false @@ -203,14 +203,14 @@ const extend = ( left: ReadonlyArray, right: ReadonlyArray ): [ReadonlyArray, ReadonlyArray] => { - const leftPad = ReadonlyArray.unfold( + const leftPad = Array.unfold( left.length, (index) => index >= right.length ? Option.none() : Option.some([leftDef(index), index + 1]) ) - const rightPad = ReadonlyArray.unfold( + const rightPad = Array.unfold( right.length, (index) => index >= left.length ? @@ -244,7 +244,7 @@ const fromFlatLoop = ( const op = config as _config.ConfigPrimitive switch (op._tag) { case OpCodes.OP_CONSTANT: { - return core.succeed(ReadonlyArray.of(op.value)) as Effect.Effect, ConfigError.ConfigError> + return core.succeed(Array.of(op.value)) as Effect.Effect, ConfigError.ConfigError> } case OpCodes.OP_DESCRIBED: { return core.suspend( @@ -296,7 +296,7 @@ const fromFlatLoop = ( return core.suspend(() => fromFlatLoop( flat, - concat(prefix, ReadonlyArray.of(op.name)), + concat(prefix, Array.of(op.name)), op.config, split ) @@ -310,7 +310,7 @@ const fromFlatLoop = ( flat.load(prefix, op, split), core.flatMap((values) => { if (values.length === 0) { - const name = pipe(ReadonlyArray.last(prefix), Option.getOrElse(() => "")) + const name = pipe(Array.last(prefix), Option.getOrElse(() => "")) return core.fail(configError.MissingData([], `Expected ${op.description} with name ${name}`)) } return core.succeed(values) @@ -329,20 +329,20 @@ const fromFlatLoop = ( core.flatMap((indices) => { if (indices.length === 0) { return core.suspend(() => - core.map(fromFlatLoop(flat, patchedPrefix, op.config, true), ReadonlyArray.of) + core.map(fromFlatLoop(flat, patchedPrefix, op.config, true), Array.of) ) as unknown as Effect.Effect, ConfigError.ConfigError> } return pipe( core.forEachSequential( indices, - (index) => fromFlatLoop(flat, ReadonlyArray.append(prefix, `[${index}]`), op.config, true) + (index) => fromFlatLoop(flat, Array.append(prefix, `[${index}]`), op.config, true) ), core.map((chunkChunk) => { - const flattened = ReadonlyArray.flatten(chunkChunk) + const flattened = Array.flatten(chunkChunk) if (flattened.length === 0) { - return ReadonlyArray.of(ReadonlyArray.empty()) + return Array.of(Array.empty()) } - return ReadonlyArray.of(flattened) + return Array.of(flattened) }) ) as unknown as Effect.Effect, ConfigError.ConfigError> }) @@ -363,21 +363,18 @@ const fromFlatLoop = ( core.forEachSequential((key) => fromFlatLoop( flat, - concat(prefix, ReadonlyArray.of(key)), + concat(prefix, Array.of(key)), op.valueConfig, split ) ), - core.map((values) => { - if (values.length === 0) { - return ReadonlyArray.of(HashMap.empty()) + core.map((matrix) => { + if (matrix.length === 0) { + return Array.of(HashMap.empty()) } - const matrix = values.map((x) => Array.from(x)) return pipe( transpose(matrix), - ReadonlyArray.map((values) => - HashMap.fromIterable(ReadonlyArray.zip(ReadonlyArray.fromIterable(keys), values)) - ) + Array.map((values) => HashMap.fromIterable(Array.zip(Array.fromIterable(keys), values))) ) }) ) @@ -407,17 +404,17 @@ const fromFlatLoop = ( return core.fail(right.left) } if (Either.isRight(left) && Either.isRight(right)) { - const path = pipe(prefix, ReadonlyArray.join(".")) + const path = pipe(prefix, Array.join(".")) const fail = fromFlatLoopFail(prefix, path) const [lefts, rights] = extend( fail, fail, - pipe(left.right, ReadonlyArray.map(Either.right)), - pipe(right.right, ReadonlyArray.map(Either.right)) + pipe(left.right, Array.map(Either.right)), + pipe(right.right, Array.map(Either.right)) ) return pipe( lefts, - ReadonlyArray.zip(rights), + Array.zip(rights), core.forEachSequential(([left, right]) => pipe( core.zip(left, right), @@ -590,8 +587,8 @@ export const within = dual< f: (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider ) => ConfigProvider.ConfigProvider >(3, (self, path, f) => { - const unnest = ReadonlyArray.reduce(path, self, (provider, name) => unnested(provider, name)) - const nest = ReadonlyArray.reduceRight(path, f(unnest), (provider, name) => nested(provider, name)) + const unnest = Array.reduce(path, self, (provider, name) => unnested(provider, name)) + const nest = Array.reduceRight(path, f(unnest), (provider, name) => nested(provider, name)) return orElse(nest, () => self) }) @@ -612,7 +609,7 @@ const parsePrimitive = ( primitive.parse(text), core.mapBoth({ onFailure: configError.prefixed(path), - onSuccess: ReadonlyArray.of + onSuccess: Array.of }) ) } @@ -631,8 +628,8 @@ const indicesFrom = (quotedIndices: HashSet.HashSet): Effect.Effect ReadonlyArray.empty(), - onSuccess: ReadonlyArray.sort(number.Order) + onFailure: () => Array.empty(), + onSuccess: Array.sort(number.Order) }), core.either, core.map(Either.merge) @@ -664,10 +661,10 @@ const splitIndexInKeys = ( for (const [pathString, value] of map) { const keyWithIndex = pipe( unmakePathString(pathString), - ReadonlyArray.flatMap((key) => + Array.flatMap((key) => Option.match(splitIndexFrom(key), { - onNone: () => ReadonlyArray.of(key), - onSome: ([key, index]) => ReadonlyArray.make(key, `[${index}]`) + onNone: () => Array.of(key), + onSome: ([key, index]) => Array.make(key, `[${index}]`) }) ) ) @@ -720,7 +717,7 @@ interface JsonArray extends Array { const hiddenDelimiter = "\ufeff" - const indexedEntries = ReadonlyArray.map( + const indexedEntries = Array.map( getIndexedEntries(json as JsonMap), ([key, value]): [string, string] => [configPathToString(key).join(hiddenDelimiter), value] ) @@ -762,10 +759,10 @@ const getIndexedEntries = ( value: string | number | boolean | JsonMap | JsonArray | null ): ReadonlyArray<[path: ReadonlyArray, value: string]> => { if (typeof value === "string") { - return ReadonlyArray.make([path, value] as [ReadonlyArray, string]) + return Array.make([path, value] as [ReadonlyArray, string]) } if (typeof value === "number" || typeof value === "boolean") { - return ReadonlyArray.make([path, String(value)] as [ReadonlyArray, string]) + return Array.make([path, String(value)] as [ReadonlyArray, string]) } if (Array.isArray(value)) { return loopArray(path, value) @@ -773,27 +770,27 @@ const getIndexedEntries = ( if (typeof value === "object" && value !== null) { return loopObject(path, value) } - return ReadonlyArray.empty<[ReadonlyArray, string]>() + return Array.empty<[ReadonlyArray, string]>() } const loopArray = ( path: ReadonlyArray, values: JsonArray ): ReadonlyArray<[path: ReadonlyArray, value: string]> => - ReadonlyArray.match(values, { - onEmpty: () => ReadonlyArray.make([path, ""] as [ReadonlyArray, string]), - onNonEmpty: ReadonlyArray.flatMap((value, index) => loopAny(ReadonlyArray.append(path, keyIndex(index)), value)) + Array.match(values, { + onEmpty: () => Array.make([path, ""] as [ReadonlyArray, string]), + onNonEmpty: Array.flatMap((value, index) => loopAny(Array.append(path, keyIndex(index)), value)) }) const loopObject = ( path: ReadonlyArray, value: JsonMap ): ReadonlyArray<[path: ReadonlyArray, value: string]> => Object.entries(value).flatMap(([key, value]) => { - const newPath = ReadonlyArray.append(path, keyName(key)) + const newPath = Array.append(path, keyName(key)) const result = loopAny(newPath, value) - if (ReadonlyArray.isEmptyReadonlyArray(result)) { - return ReadonlyArray.make([newPath, ""] as [ReadonlyArray, string]) + if (Array.isEmptyReadonlyArray(result)) { + return Array.make([newPath, ""] as [ReadonlyArray, string]) } return result }) - return loopObject(ReadonlyArray.empty(), config) + return loopObject(Array.empty(), config) } diff --git a/packages/effect/src/internal/configProvider/pathPatch.ts b/packages/effect/src/internal/configProvider/pathPatch.ts index 64813b047b..f4f463a5a7 100644 --- a/packages/effect/src/internal/configProvider/pathPatch.ts +++ b/packages/effect/src/internal/configProvider/pathPatch.ts @@ -1,10 +1,10 @@ +import * as RA from "../../Array.js" import type * as ConfigError from "../../ConfigError.js" import type * as PathPatch from "../../ConfigProviderPathPatch.js" import * as Either from "../../Either.js" import { dual, pipe } from "../../Function.js" import * as List from "../../List.js" import * as Option from "../../Option.js" -import * as RA from "../../ReadonlyArray.js" import * as configError from "../configError.js" /** @internal */ diff --git a/packages/effect/src/internal/core-effect.ts b/packages/effect/src/internal/core-effect.ts index 1b87889703..261a30d07e 100644 --- a/packages/effect/src/internal/core-effect.ts +++ b/packages/effect/src/internal/core-effect.ts @@ -1,3 +1,4 @@ +import * as Array from "../Array.js" import type * as Cause from "../Cause.js" import * as Chunk from "../Chunk.js" import * as Clock from "../Clock.js" @@ -21,7 +22,6 @@ import type * as MetricLabel from "../MetricLabel.js" import * as Option from "../Option.js" import * as Predicate from "../Predicate.js" import type * as Random from "../Random.js" -import * as ReadonlyArray from "../ReadonlyArray.js" import * as Ref from "../Ref.js" import type * as runtimeFlagsPatch from "../RuntimeFlagsPatch.js" import * as Tracer from "../Tracer.js" @@ -512,7 +512,7 @@ export const filterMap = dual< >(2, (elements, pf) => core.map( core.forEachSequential(elements, identity), - ReadonlyArray.filterMap(pf) + Array.filterMap(pf) )) /* @internal */ @@ -695,7 +695,7 @@ export const firstSuccessOf = >( } return pipe( Chunk.tailNonEmpty(list), - ReadonlyArray.reduce(Chunk.headNonEmpty(list), (left, right) => core.orElse(left, () => right) as Eff) + Array.reduce(Chunk.headNonEmpty(list), (left, right) => core.orElse(left, () => right) as Eff) ) }) @@ -1020,7 +1020,7 @@ export const loop: { ): any => options.discard ? loopDiscard(initial, options.while, options.step, options.body) - : core.map(loopInternal(initial, options.while, options.step, options.body), Array.from) + : core.map(loopInternal(initial, options.while, options.step, options.body), Array.fromIterable) const loopInternal = ( initial: Z, @@ -1184,7 +1184,7 @@ export const orElseSucceed = dual< export const parallelErrors = (self: Effect.Effect): Effect.Effect, R> => core.matchCauseEffect(self, { onFailure: (cause) => { - const errors = Array.from(internalCause.failures(cause)) + const errors = Array.fromIterable(internalCause.failures(cause)) return errors.length === 0 ? core.failCause(cause as Cause.Cause) : core.fail(errors) @@ -1278,7 +1278,7 @@ export const reduce = dual< zero: Z, f: (z: Z, a: A, i: number) => Effect.Effect ) => - ReadonlyArray.fromIterable(elements).reduce( + Array.fromIterable(elements).reduce( (acc, el, i) => core.flatMap(acc, (a) => f(a, el, i)), core.succeed(zero) as Effect.Effect ) @@ -1298,7 +1298,7 @@ export const reduceRight = dual< >( 3, (elements: Iterable, zero: Z, f: (a: A, z: Z, i: number) => Effect.Effect) => - ReadonlyArray.fromIterable(elements).reduceRight( + Array.fromIterable(elements).reduceRight( (acc, el, i) => core.flatMap(acc, (a) => f(el, a, i)), core.succeed(zero) as Effect.Effect ) @@ -1435,7 +1435,7 @@ export const labelMetrics = dual< (self: Effect.Effect, labels: Iterable) => Effect.Effect >( 2, - (self, labels) => core.fiberRefLocallyWith(self, core.currentMetricLabels, (old) => ReadonlyArray.union(old, labels)) + (self, labels) => core.fiberRefLocallyWith(self, core.currentMetricLabels, (old) => Array.union(old, labels)) ) /* @internal */ @@ -2082,7 +2082,7 @@ export const unsafeMakeSpan = ( ...(options?.links ?? []) ] : Chunk.toReadonlyArray(linksFromEnv.value) : - options?.links ?? ReadonlyArray.empty() + options?.links ?? Array.empty() const span = tracer.span( name, diff --git a/packages/effect/src/internal/core.ts b/packages/effect/src/internal/core.ts index 24855c0194..86af70a272 100644 --- a/packages/effect/src/internal/core.ts +++ b/packages/effect/src/internal/core.ts @@ -1,3 +1,4 @@ +import * as Array from "../Array.js" import type * as Cause from "../Cause.js" import * as Chunk from "../Chunk.js" import * as Context from "../Context.js" @@ -27,7 +28,6 @@ import * as MutableRef from "../MutableRef.js" import * as Option from "../Option.js" import { pipeArguments } from "../Pipeable.js" import { hasProperty, isObject, isPromiseLike, isString, type Predicate, type Refinement } from "../Predicate.js" -import * as ReadonlyArray from "../ReadonlyArray.js" import type * as Request from "../Request.js" import type * as BlockedRequests from "../RequestBlock.js" import type * as RequestResolver from "../RequestResolver.js" @@ -886,8 +886,8 @@ export const forEachSequential: { 2, (self: Iterable, f: (a: A, i: number) => Effect.Effect): Effect.Effect, E, R> => suspend(() => { - const arr = ReadonlyArray.fromIterable(self) - const ret = new Array(arr.length) + const arr = Array.fromIterable(self) + const ret = Array.allocate(arr.length) let i = 0 return as( whileLoop({ @@ -897,7 +897,7 @@ export const forEachSequential: { ret[i++] = b } }), - ret + ret as Array ) }) ) @@ -910,7 +910,7 @@ export const forEachSequentialDiscard: { 2, (self: Iterable, f: (a: A, i: number) => Effect.Effect): Effect.Effect => suspend(() => { - const arr = ReadonlyArray.fromIterable(self) + const arr = Array.fromIterable(self) let i = 0 return whileLoop({ while: () => i < arr.length, @@ -1156,7 +1156,7 @@ export const partitionMap = ( elements: Iterable, f: (a: A) => Either.Either ): [left: Array, right: Array] => - ReadonlyArray.fromIterable(elements).reduceRight( + Array.fromIterable(elements).reduceRight( ([lefts, rights], current) => { const either = f(current) switch (either._tag) { @@ -1168,7 +1168,7 @@ export const partitionMap = ( } } }, - [new Array(), new Array()] + [Array.empty(), Array.empty()] ) /* @internal */ @@ -2000,7 +2000,7 @@ export const withUnhandledErrorLogLevel = dual< /** @internal */ export const currentMetricLabels: FiberRef.FiberRef> = globalValue( Symbol.for("effect/FiberRef/currentMetricLabels"), - () => fiberRefUnsafeMakeReadonlyArray(ReadonlyArray.empty()) + () => fiberRefUnsafeMakeReadonlyArray(Array.empty()) ) /* @internal */ @@ -2110,8 +2110,8 @@ export const causeSquashWith = dual< Chunk.head, Option.match({ onNone: () => { - const interrupts = Array.from(internalCause.interruptors(self)).flatMap((fiberId) => - Array.from(FiberId.ids(fiberId)).map((id) => `#${id}`) + const interrupts = Array.fromIterable(internalCause.interruptors(self)).flatMap((fiberId) => + Array.fromIterable(FiberId.ids(fiberId)).map((id) => `#${id}`) ) return new InterruptedException(interrupts ? `Interrupted by fibers: ${interrupts.join(", ")}` : void 0) }, @@ -2694,7 +2694,7 @@ const exitCollectAllInternal = ( } return pipe( Chunk.tailNonEmpty(list), - ReadonlyArray.reduce( + Array.reduce( pipe(Chunk.headNonEmpty(list), exitMap>(Chunk.of)), (accumulator, current) => pipe( @@ -2706,7 +2706,7 @@ const exitCollectAllInternal = ( ) ), exitMap(Chunk.reverse), - exitMap((chunk) => Array.from(chunk)), + exitMap((chunk) => Chunk.toReadonlyArray(chunk) as Array), Option.some ) } diff --git a/packages/effect/src/internal/dataSource.ts b/packages/effect/src/internal/dataSource.ts index 23f5209343..fd67947bc7 100644 --- a/packages/effect/src/internal/dataSource.ts +++ b/packages/effect/src/internal/dataSource.ts @@ -1,10 +1,10 @@ +import * as RA from "../Array.js" import * as Cause from "../Cause.js" import * as Chunk from "../Chunk.js" import type * as Context from "../Context.js" import * as Effect from "../Effect.js" import type * as Either from "../Either.js" import { dual, pipe } from "../Function.js" -import * as RA from "../ReadonlyArray.js" import type * as Request from "../Request.js" import type * as RequestResolver from "../RequestResolver.js" import * as core from "./core.js" diff --git a/packages/effect/src/internal/differ/readonlyArrayPatch.ts b/packages/effect/src/internal/differ/readonlyArrayPatch.ts index 3669e86ad0..0b2aa31002 100644 --- a/packages/effect/src/internal/differ/readonlyArrayPatch.ts +++ b/packages/effect/src/internal/differ/readonlyArrayPatch.ts @@ -1,7 +1,7 @@ +import * as Array from "../../Array.js" import type * as Differ from "../../Differ.js" import * as Equal from "../../Equal.js" import * as Dual from "../../Function.js" -import * as ReadonlyArray from "../../ReadonlyArray.js" import * as Data from "../data.js" /** @internal */ @@ -135,7 +135,7 @@ export const diff = ( patch = combine(patch, makeSlice(0, i)) } if (i < options.newValue.length) { - patch = combine(patch, makeAppend(ReadonlyArray.drop(i)(options.newValue))) + patch = combine(patch, makeAppend(Array.drop(i)(options.newValue))) } return patch } @@ -173,10 +173,10 @@ export const patch = Dual.dual< return oldValue } let readonlyArray = oldValue.slice() - let patches: Array> = ReadonlyArray.of(self) - while (ReadonlyArray.isNonEmptyArray(patches)) { - const head: Instruction = ReadonlyArray.headNonEmpty(patches) as Instruction - const tail = ReadonlyArray.tailNonEmpty(patches) + let patches: Array> = Array.of(self) + while (Array.isNonEmptyArray(patches)) { + const head: Instruction = Array.headNonEmpty(patches) as Instruction + const tail = Array.tailNonEmpty(patches) switch (head._tag) { case "Empty": { patches = tail diff --git a/packages/effect/src/internal/fiberRefs.ts b/packages/effect/src/internal/fiberRefs.ts index 8579f4c417..3b3e26b32c 100644 --- a/packages/effect/src/internal/fiberRefs.ts +++ b/packages/effect/src/internal/fiberRefs.ts @@ -1,3 +1,4 @@ +import * as Arr from "../Array.js" import type * as Effect from "../Effect.js" import * as Equal from "../Equal.js" import type * as FiberId from "../FiberId.js" @@ -7,7 +8,6 @@ import { dual, pipe } from "../Function.js" import * as HashSet from "../HashSet.js" import * as Option from "../Option.js" import { pipeArguments } from "../Pipeable.js" -import * as Arr from "../ReadonlyArray.js" import * as core from "./core.js" /** @internal */ diff --git a/packages/effect/src/internal/fiberRefs/patch.ts b/packages/effect/src/internal/fiberRefs/patch.ts index 46f1ad59e8..d4ef0ed498 100644 --- a/packages/effect/src/internal/fiberRefs/patch.ts +++ b/packages/effect/src/internal/fiberRefs/patch.ts @@ -1,9 +1,9 @@ +import * as Arr from "../../Array.js" import { equals } from "../../Equal.js" import type * as FiberId from "../../FiberId.js" import type * as FiberRefs from "../../FiberRefs.js" import type * as FiberRefsPatch from "../../FiberRefsPatch.js" import { dual } from "../../Function.js" -import * as Arr from "../../ReadonlyArray.js" import * as _fiberRefs from "../fiberRefs.js" /** @internal */ diff --git a/packages/effect/src/internal/fiberRuntime.ts b/packages/effect/src/internal/fiberRuntime.ts index 44d461966e..04d860f0ee 100644 --- a/packages/effect/src/internal/fiberRuntime.ts +++ b/packages/effect/src/internal/fiberRuntime.ts @@ -1,3 +1,4 @@ +import * as RA from "../Array.js" import * as Boolean from "../Boolean.js" import type * as Cause from "../Cause.js" import * as Chunk from "../Chunk.js" @@ -31,7 +32,6 @@ import * as Option from "../Option.js" import { pipeArguments } from "../Pipeable.js" import * as Predicate from "../Predicate.js" import type * as Random from "../Random.js" -import * as RA from "../ReadonlyArray.js" import * as Ref from "../Ref.js" import type { Entry, Request } from "../Request.js" import type * as RequestBlock from "../RequestBlock.js" @@ -3576,7 +3576,7 @@ export const makeSpanScoped = ( readonly parent?: Tracer.AnySpan | undefined readonly root?: boolean | undefined readonly context?: Context.Context | undefined - } + } | undefined ): Effect.Effect => core.uninterruptible( core.withFiberRuntime((fiber) => { diff --git a/packages/effect/src/internal/metric.ts b/packages/effect/src/internal/metric.ts index e434b7d79d..f4a510e5fa 100644 --- a/packages/effect/src/internal/metric.ts +++ b/packages/effect/src/internal/metric.ts @@ -1,3 +1,4 @@ +import * as Array from "../Array.js" import * as Clock from "../Clock.js" import * as Duration from "../Duration.js" import type * as Effect from "../Effect.js" @@ -14,7 +15,6 @@ import type * as MetricPair from "../MetricPair.js" import type * as MetricRegistry from "../MetricRegistry.js" import type * as MetricState from "../MetricState.js" import { pipeArguments } from "../Pipeable.js" -import * as ReadonlyArray from "../ReadonlyArray.js" import * as Cause from "./cause.js" import * as _effect from "./core-effect.js" import * as core from "./core.js" @@ -275,7 +275,7 @@ export const taggedWithLabelsInput = dual< (input, extraTags) => self.unsafeUpdate( input, - ReadonlyArray.union(f(input), extraTags) + Array.union(f(input), extraTags) ), self.unsafeValue ), @@ -294,8 +294,8 @@ export const taggedWithLabels = dual< >(2, (self, extraTags) => { return make( self.keyType, - (input, extraTags1) => self.unsafeUpdate(input, ReadonlyArray.union(extraTags, extraTags1)), - (extraTags1) => self.unsafeValue(ReadonlyArray.union(extraTags, extraTags1)) + (input, extraTags1) => self.unsafeUpdate(input, Array.union(extraTags, extraTags1)), + (extraTags1) => self.unsafeValue(Array.union(extraTags, extraTags1)) ) }) diff --git a/packages/effect/src/internal/metric/boundaries.ts b/packages/effect/src/internal/metric/boundaries.ts index 5eee59ee2c..d7e93c95d0 100644 --- a/packages/effect/src/internal/metric/boundaries.ts +++ b/packages/effect/src/internal/metric/boundaries.ts @@ -1,3 +1,4 @@ +import * as Array from "../../Array.js" import * as Chunk from "../../Chunk.js" import * as Equal from "../../Equal.js" import { pipe } from "../../Function.js" @@ -5,7 +6,6 @@ import * as Hash from "../../Hash.js" import type * as MetricBoundaries from "../../MetricBoundaries.js" import { pipeArguments } from "../../Pipeable.js" import { hasProperty } from "../../Predicate.js" -import * as ReadonlyArray from "../../ReadonlyArray.js" /** @internal */ const MetricBoundariesSymbolKey = "effect/MetricBoundaries" @@ -44,8 +44,8 @@ export const isMetricBoundaries = (u: unknown): u is MetricBoundaries.MetricBoun export const fromIterable = (iterable: Iterable): MetricBoundaries.MetricBoundaries => { const values = pipe( iterable, - ReadonlyArray.appendAll(Chunk.of(Number.POSITIVE_INFINITY)), - ReadonlyArray.dedupe + Array.appendAll(Chunk.of(Number.POSITIVE_INFINITY)), + Array.dedupe ) return new MetricBoundariesImpl(values) } @@ -57,7 +57,7 @@ export const linear = (options: { readonly count: number }): MetricBoundaries.MetricBoundaries => pipe( - ReadonlyArray.makeBy(options.count - 1, (i) => options.start + i * options.width), + Array.makeBy(options.count - 1, (i) => options.start + i * options.width), Chunk.unsafeFromArray, fromIterable ) @@ -69,7 +69,7 @@ export const exponential = (options: { readonly count: number }): MetricBoundaries.MetricBoundaries => pipe( - ReadonlyArray.makeBy(options.count - 1, (i) => options.start * Math.pow(options.factor, i)), + Array.makeBy(options.count - 1, (i) => options.start * Math.pow(options.factor, i)), Chunk.unsafeFromArray, fromIterable ) diff --git a/packages/effect/src/internal/metric/hook.ts b/packages/effect/src/internal/metric/hook.ts index 8b70d21489..d38277fb06 100644 --- a/packages/effect/src/internal/metric/hook.ts +++ b/packages/effect/src/internal/metric/hook.ts @@ -1,3 +1,4 @@ +import * as Array from "../../Array.js" import * as Duration from "../../Duration.js" import type { LazyArg } from "../../Function.js" import { dual, pipe } from "../../Function.js" @@ -7,7 +8,6 @@ import type * as MetricState from "../../MetricState.js" import * as number from "../../Number.js" import * as Option from "../../Option.js" import { pipeArguments } from "../../Pipeable.js" -import * as ReadonlyArray from "../../ReadonlyArray.js" import * as metricState from "./state.js" /** @internal */ @@ -123,8 +123,8 @@ export const histogram = (key: MetricKey.MetricKey.Histogram): MetricHook.Metric pipe( bounds, - ReadonlyArray.sort(number.Order), - ReadonlyArray.map((n, i) => { + Array.sort(number.Order), + Array.map((n, i) => { boundaries[i] = n }) ) @@ -162,7 +162,7 @@ export const histogram = (key: MetricKey.MetricKey.Histogram): MetricHook.Metric } const getBuckets = (): ReadonlyArray => { - const builder: Array = Array(size) + const builder: Array = Array.allocate(size) as any let cumulated = 0 for (let i = 0; i < size; i++) { const boundary = boundaries[i] @@ -189,8 +189,8 @@ export const histogram = (key: MetricKey.MetricKey.Histogram): MetricHook.Metric /** @internal */ export const summary = (key: MetricKey.MetricKey.Summary): MetricHook.MetricHook.Summary => { const { error, maxAge, maxSize, quantiles } = key.keyType - const sortedQuantiles = pipe(quantiles, ReadonlyArray.sort(number.Order)) - const values = Array(maxSize) + const sortedQuantiles = pipe(quantiles, Array.sort(number.Order)) + const values = Array.allocate(maxSize) let head = 0 let count = 0 @@ -228,7 +228,7 @@ export const summary = (key: MetricKey.MetricKey.Summary): MetricHook.MetricHook return calculateQuantiles( error, sortedQuantiles, - ReadonlyArray.sort(builder, number.Order) + Array.sort(builder, number.Order) ) } @@ -291,8 +291,8 @@ const calculateQuantiles = ( ): ReadonlyArray]> => { // The number of samples examined const sampleCount = sortedSamples.length - if (!ReadonlyArray.isNonEmptyReadonlyArray(sortedQuantiles)) { - return ReadonlyArray.empty() + if (!Array.isNonEmptyReadonlyArray(sortedQuantiles)) { + return Array.empty() } const head = sortedQuantiles[0] const tail = sortedQuantiles.slice(1) @@ -304,7 +304,7 @@ const calculateQuantiles = ( head, sortedSamples ) - const resolved = ReadonlyArray.of(resolvedHead) + const resolved = Array.of(resolvedHead) tail.forEach((quantile) => { resolved.push( resolveQuantile( @@ -317,7 +317,7 @@ const calculateQuantiles = ( ) ) }) - return ReadonlyArray.map(resolved, (rq) => [rq.quantile, rq.value] as const) + return Array.map(resolved, (rq) => [rq.quantile, rq.value] as const) } /** @internal */ @@ -344,7 +344,7 @@ const resolveQuantile = ( // eslint-disable-next-line no-constant-condition while (1) { // If the remaining list of samples is empty, there is nothing more to resolve - if (!ReadonlyArray.isNonEmptyReadonlyArray(rest_1)) { + if (!Array.isNonEmptyReadonlyArray(rest_1)) { return { quantile: quantile_1, value: Option.none(), @@ -357,14 +357,14 @@ const resolveQuantile = ( if (quantile_1 === 1) { return { quantile: quantile_1, - value: Option.some(ReadonlyArray.lastNonEmpty(rest_1)), + value: Option.some(Array.lastNonEmpty(rest_1)), consumed: consumed_1 + rest_1.length, rest: [] } } // Split into two chunks - the first chunk contains all elements of the same // value as the chunk head - const sameHead = ReadonlyArray.span(rest_1, (n) => n <= rest_1[0]) + const sameHead = Array.span(rest_1, (n) => n <= rest_1[0]) // How many elements do we want to accept for this quantile const desired = quantile_1 * sampleCount_1 // The error margin @@ -378,7 +378,7 @@ const resolveQuantile = ( if (candConsumed < desired - allowedError) { error_2 = error_1 sampleCount_2 = sampleCount_1 - current_2 = ReadonlyArray.head(rest_1) + current_2 = Array.head(rest_1) consumed_2 = candConsumed quantile_2 = quantile_1 rest_2 = sameHead[1] @@ -406,7 +406,7 @@ const resolveQuantile = ( case "None": { error_2 = error_1 sampleCount_2 = sampleCount_1 - current_2 = ReadonlyArray.head(rest_1) + current_2 = Array.head(rest_1) consumed_2 = candConsumed quantile_2 = quantile_1 rest_2 = sameHead[1] @@ -423,7 +423,7 @@ const resolveQuantile = ( if (candError < prevError) { error_2 = error_1 sampleCount_2 = sampleCount_1 - current_2 = ReadonlyArray.head(rest_1) + current_2 = Array.head(rest_1) consumed_2 = candConsumed quantile_2 = quantile_1 rest_2 = sameHead[1] diff --git a/packages/effect/src/internal/metric/key.ts b/packages/effect/src/internal/metric/key.ts index 69e2307809..4bda8b45e9 100644 --- a/packages/effect/src/internal/metric/key.ts +++ b/packages/effect/src/internal/metric/key.ts @@ -1,3 +1,4 @@ +import * as Array from "../../Array.js" import type * as Duration from "../../Duration.js" import * as Equal from "../../Equal.js" import { dual, pipe } from "../../Function.js" @@ -9,7 +10,6 @@ import type * as MetricLabel from "../../MetricLabel.js" import * as Option from "../../Option.js" import { pipeArguments } from "../../Pipeable.js" import { hasProperty } from "../../Predicate.js" -import * as ReadonlyArray from "../../ReadonlyArray.js" import * as metricKeyType from "./keyType.js" import * as metricLabel from "./label.js" @@ -26,7 +26,7 @@ const metricKeyVariance = { _Type: (_: never) => _ } -const arrayEquivilence = ReadonlyArray.getEquivalence(Equal.equals) +const arrayEquivilence = Array.getEquivalence(Equal.equals) /** @internal */ class MetricKeyImpl> implements MetricKey.MetricKey { @@ -164,4 +164,4 @@ export const taggedWithLabels = dual< >(2, (self, extraTags) => extraTags.length === 0 ? self - : new MetricKeyImpl(self.name, self.keyType, self.description, ReadonlyArray.union(self.tags, extraTags))) + : new MetricKeyImpl(self.name, self.keyType, self.description, Array.union(self.tags, extraTags))) diff --git a/packages/effect/src/internal/metric/state.ts b/packages/effect/src/internal/metric/state.ts index 997f4fd565..1d01b5996c 100644 --- a/packages/effect/src/internal/metric/state.ts +++ b/packages/effect/src/internal/metric/state.ts @@ -1,3 +1,4 @@ +import * as Array from "../../Array.js" import * as Equal from "../../Equal.js" import { pipe } from "../../Function.js" import * as Hash from "../../Hash.js" @@ -5,7 +6,6 @@ import type * as MetricState from "../../MetricState.js" import type * as Option from "../../Option.js" import { pipeArguments } from "../../Pipeable.js" import { hasProperty } from "../../Predicate.js" -import * as ReadonlyArray from "../../ReadonlyArray.js" /** @internal */ const MetricStateSymbolKey = "effect/MetricState" @@ -80,7 +80,7 @@ class CounterState implements MetricState.MetricSta } } -const arrayEquals = ReadonlyArray.getEquivalence(Equal.equals) +const arrayEquals = Array.getEquivalence(Equal.equals) /** @internal */ class FrequencyState implements MetricState.MetricState.Frequency { @@ -91,14 +91,14 @@ class FrequencyState implements MetricState.MetricState.Frequency { [Hash.symbol](): number { return pipe( Hash.string(FrequencyStateSymbolKey), - Hash.combine(Hash.array(ReadonlyArray.fromIterable(this.occurrences.entries()))), + Hash.combine(Hash.array(Array.fromIterable(this.occurrences.entries()))), Hash.cached(this) ) } [Equal.symbol](that: unknown): boolean { return isFrequencyState(that) && arrayEquals( - ReadonlyArray.fromIterable(this.occurrences.entries()), - ReadonlyArray.fromIterable(that.occurrences.entries()) + Array.fromIterable(this.occurrences.entries()), + Array.fromIterable(that.occurrences.entries()) ) } pipe() { diff --git a/packages/effect/src/internal/queue.ts b/packages/effect/src/internal/queue.ts index f787f8d4a6..d99925bc17 100644 --- a/packages/effect/src/internal/queue.ts +++ b/packages/effect/src/internal/queue.ts @@ -1,3 +1,4 @@ +import * as Array from "../Array.js" import * as Chunk from "../Chunk.js" import type * as Deferred from "../Deferred.js" import type * as Effect from "../Effect.js" @@ -8,7 +9,6 @@ import * as Option from "../Option.js" import { pipeArguments } from "../Pipeable.js" import { hasProperty } from "../Predicate.js" import type * as Queue from "../Queue.js" -import * as ReadonlyArray from "../ReadonlyArray.js" import * as core from "./core.js" import * as fiberRuntime from "./fiberRuntime.js" @@ -208,11 +208,11 @@ class QueueImpl implements Queue.Queue { if (MutableRef.get(this.shutdownFlag)) { return core.interrupt } - const values = ReadonlyArray.fromIterable(iterable) + const values = Array.fromIterable(iterable) const pTakers = this.queue.length() === 0 - ? ReadonlyArray.fromIterable(unsafePollN(this.takers, values.length)) - : ReadonlyArray.empty - const [forTakers, remaining] = pipe(values, ReadonlyArray.splitAt(pTakers.length)) + ? Array.fromIterable(unsafePollN(this.takers, values.length)) + : Array.empty + const [forTakers, remaining] = pipe(values, Array.splitAt(pTakers.length)) for (let i = 0; i < pTakers.length; i++) { const taker = (pTakers as any)[i] const item = forTakers[i] @@ -602,7 +602,7 @@ class BackPressureStrategy implements Queue.Strategy { } unsafeOffer(iterable: Iterable, deferred: Deferred.Deferred): void { - const stuff = Array.from(iterable) + const stuff = Array.fromIterable(iterable) for (let i = 0; i < stuff.length; i++) { const value = stuff[i] if (i === stuff.length - 1) { diff --git a/packages/effect/src/internal/redBlackTree/iterator.ts b/packages/effect/src/internal/redBlackTree/iterator.ts index 3dd8205c82..6014978c15 100644 --- a/packages/effect/src/internal/redBlackTree/iterator.ts +++ b/packages/effect/src/internal/redBlackTree/iterator.ts @@ -1,5 +1,5 @@ +import * as Array from "../../Array.js" import * as Option from "../../Option.js" -import * as ReadonlyArray from "../../ReadonlyArray.js" import type * as RBT from "../../RedBlackTree.js" import type { RedBlackTreeImpl } from "../redBlackTree.js" import type * as Node from "./node.js" @@ -83,7 +83,7 @@ export class RedBlackTreeIterator implements Iterator<[K, V]> { * Returns the key */ get entry(): Option.Option<[K, V]> { - return Option.map(ReadonlyArray.last(this.stack), (node) => [node.key, node.value]) + return Option.map(Array.last(this.stack), (node) => [node.key, node.value]) } /** diff --git a/packages/effect/src/internal/runtime.ts b/packages/effect/src/internal/runtime.ts index a7ab7a12ee..411e1c4bc8 100644 --- a/packages/effect/src/internal/runtime.ts +++ b/packages/effect/src/internal/runtime.ts @@ -1,4 +1,5 @@ import { equals } from "effect/Equal" +import type * as ReadonlyArray from "../Array.js" import type * as Cause from "../Cause.js" import * as Context from "../Context.js" import type * as Effect from "../Effect.js" @@ -12,7 +13,6 @@ import * as Inspectable from "../Inspectable.js" import * as Option from "../Option.js" import { pipeArguments } from "../Pipeable.js" import * as Predicate from "../Predicate.js" -import type * as ReadonlyArray from "../ReadonlyArray.js" import type * as Runtime from "../Runtime.js" import type * as RuntimeFlags from "../RuntimeFlags.js" import * as _scheduler from "../Scheduler.js" diff --git a/packages/effect/src/internal/secret.ts b/packages/effect/src/internal/secret.ts index 595e9ae2c9..ab0868afbd 100644 --- a/packages/effect/src/internal/secret.ts +++ b/packages/effect/src/internal/secret.ts @@ -1,8 +1,8 @@ +import * as Array from "../Array.js" import * as Equal from "../Equal.js" import { pipe } from "../Function.js" import * as Hash from "../Hash.js" import { hasProperty } from "../Predicate.js" -import * as ReadonlyArray from "../ReadonlyArray.js" import type * as Secret from "../Secret.js" /** @internal */ @@ -56,7 +56,7 @@ export const make = (bytes: Array): Secret.Secret => { /** @internal */ export const fromIterable = (iterable: Iterable): Secret.Secret => - make(ReadonlyArray.fromIterable(iterable).map((char) => char.charCodeAt(0))) + make(Array.fromIterable(iterable).map((char) => char.charCodeAt(0))) /** @internal */ export const fromString = (text: string): Secret.Secret => { diff --git a/packages/effect/src/internal/sink.ts b/packages/effect/src/internal/sink.ts index 4068110767..0b6b583134 100644 --- a/packages/effect/src/internal/sink.ts +++ b/packages/effect/src/internal/sink.ts @@ -1,3 +1,4 @@ +import * as Array from "../Array.js" import * as Cause from "../Cause.js" import type * as Channel from "../Channel.js" import * as Chunk from "../Chunk.js" @@ -17,7 +18,6 @@ import { pipeArguments } from "../Pipeable.js" import { hasProperty, type Predicate, type Refinement } from "../Predicate.js" import * as PubSub from "../PubSub.js" import * as Queue from "../Queue.js" -import * as ReadonlyArray from "../ReadonlyArray.js" import * as Ref from "../Ref.js" import type * as Scope from "../Scope.js" import type * as Sink from "../Sink.js" @@ -213,7 +213,7 @@ const collectAllWhileReader = ( ): Channel.Channel, Chunk.Chunk, never, never, Chunk.Chunk, unknown> => core.readWith({ onInput: (input: Chunk.Chunk) => { - const [collected, leftovers] = pipe(Chunk.toReadonlyArray(input), ReadonlyArray.span(predicate)) + const [collected, leftovers] = pipe(Chunk.toReadonlyArray(input), Array.span(predicate)) if (leftovers.length === 0) { return collectAllWhileReader( predicate, diff --git a/packages/effect/src/internal/stm/stm.ts b/packages/effect/src/internal/stm/stm.ts index 930c1c7362..ecbdfebfa3 100644 --- a/packages/effect/src/internal/stm/stm.ts +++ b/packages/effect/src/internal/stm/stm.ts @@ -1,3 +1,4 @@ +import * as RA from "../../Array.js" import * as Cause from "../../Cause.js" import * as Chunk from "../../Chunk.js" import * as Context from "../../Context.js" @@ -10,7 +11,6 @@ import { constFalse, constTrue, constVoid, dual, identity, pipe } from "../../Fu import * as Option from "../../Option.js" import type { Predicate, Refinement } from "../../Predicate.js" import * as predicate from "../../Predicate.js" -import * as RA from "../../ReadonlyArray.js" import type * as STM from "../../STM.js" import type { MergeRecord } from "../../Types.js" import * as effectCore from "../core.js" diff --git a/packages/effect/src/internal/stm/tMap.ts b/packages/effect/src/internal/stm/tMap.ts index c92fbe8bd4..2dead7c424 100644 --- a/packages/effect/src/internal/stm/tMap.ts +++ b/packages/effect/src/internal/stm/tMap.ts @@ -1,3 +1,4 @@ +import * as RA from "../../Array.js" import * as Chunk from "../../Chunk.js" import * as Equal from "../../Equal.js" import type { LazyArg } from "../../Function.js" @@ -6,7 +7,6 @@ import * as Hash from "../../Hash.js" import * as HashMap from "../../HashMap.js" import * as Option from "../../Option.js" import { hasProperty } from "../../Predicate.js" -import * as RA from "../../ReadonlyArray.js" import * as STM from "../../STM.js" import type * as TArray from "../../TArray.js" import type * as TMap from "../../TMap.js" diff --git a/packages/effect/src/internal/stm/tPriorityQueue.ts b/packages/effect/src/internal/stm/tPriorityQueue.ts index 7ff5fa37c2..98c1ecc17f 100644 --- a/packages/effect/src/internal/stm/tPriorityQueue.ts +++ b/packages/effect/src/internal/stm/tPriorityQueue.ts @@ -1,9 +1,9 @@ +import * as Array from "../../Array.js" import * as Chunk from "../../Chunk.js" import { dual, pipe } from "../../Function.js" import * as Option from "../../Option.js" import type * as Order from "../../Order.js" import type { Predicate } from "../../Predicate.js" -import * as ReadonlyArray from "../../ReadonlyArray.js" import * as SortedMap from "../../SortedMap.js" import type * as STM from "../../STM.js" import type * as TPriorityQueue from "../../TPriorityQueue.js" @@ -42,7 +42,7 @@ export const fromIterable = (order: Order.Order) => (iterable: Iterable): STM.STM> => pipe( tRef.make( - Array.from(iterable).reduce( + Array.fromIterable(iterable).reduce( (map, value) => pipe( map, @@ -52,8 +52,8 @@ export const fromIterable = map, SortedMap.get(value), Option.match({ - onNone: () => ReadonlyArray.of(value), - onSome: ReadonlyArray.prepend(value) + onNone: () => Array.of(value), + onSome: Array.prepend(value) }) ) ) @@ -86,8 +86,8 @@ export const offer = dual< map, value, Option.match(SortedMap.get(map, value), { - onNone: () => ReadonlyArray.of(value), - onSome: ReadonlyArray.prepend(value) + onNone: () => Array.of(value), + onSome: Array.prepend(value) }) ))) @@ -97,14 +97,14 @@ export const offerAll = dual< (self: TPriorityQueue.TPriorityQueue, values: Iterable) => STM.STM >(2, (self, values) => tRef.update(self.ref, (map) => - Array.from(values).reduce( + Array.fromIterable(values).reduce( (map, value) => SortedMap.set( map, value, Option.match(SortedMap.get(map, value), { - onNone: () => ReadonlyArray.of(value), - onSome: ReadonlyArray.prepend(value) + onNone: () => Array.of(value), + onSome: Array.prepend(value) }) ), map @@ -147,7 +147,7 @@ export const retainIf = dual< self.ref, (map) => SortedMap.reduce(map, SortedMap.empty(SortedMap.getOrder(map)), (map, value, key) => { - const filtered: ReadonlyArray = ReadonlyArray.filter(value, predicate) + const filtered: ReadonlyArray = Array.filter(value, predicate) return filtered.length > 0 ? SortedMap.set(map, key, filtered as [A, ...Array]) : SortedMap.remove(map, key) @@ -228,7 +228,7 @@ export const takeUpTo = dual< let next: IteratorResult]], any> while ((next = iterator.next()) && !next.done && index < n) { const [key, value] = next.value - const [left, right] = pipe(value, ReadonlyArray.splitAt(n - index)) + const [left, right] = pipe(value, Array.splitAt(n - index)) for (const value of left) { builder.push(value) } diff --git a/packages/effect/src/internal/stm/tPubSub.ts b/packages/effect/src/internal/stm/tPubSub.ts index 2f869ede59..089be12ce5 100644 --- a/packages/effect/src/internal/stm/tPubSub.ts +++ b/packages/effect/src/internal/stm/tPubSub.ts @@ -1,8 +1,8 @@ +import * as RA from "../../Array.js" import * as Effect from "../../Effect.js" import { dual, identity, pipe } from "../../Function.js" import * as HashSet from "../../HashSet.js" import * as Option from "../../Option.js" -import * as RA from "../../ReadonlyArray.js" import type * as Scope from "../../Scope.js" import type * as STM from "../../STM.js" import type * as TPubSub from "../../TPubSub.js" diff --git a/packages/effect/src/internal/stm/tQueue.ts b/packages/effect/src/internal/stm/tQueue.ts index c44675d78a..90039374f3 100644 --- a/packages/effect/src/internal/stm/tQueue.ts +++ b/packages/effect/src/internal/stm/tQueue.ts @@ -1,8 +1,8 @@ +import * as RA from "../../Array.js" import * as Chunk from "../../Chunk.js" import { dual, pipe } from "../../Function.js" import * as Option from "../../Option.js" import { hasProperty, type Predicate } from "../../Predicate.js" -import * as RA from "../../ReadonlyArray.js" import * as STM from "../../STM.js" import type * as TQueue from "../../TQueue.js" import type * as TRef from "../../TRef.js" diff --git a/packages/effect/src/internal/stm/tSet.ts b/packages/effect/src/internal/stm/tSet.ts index 1c6f2dda58..902ebbd74e 100644 --- a/packages/effect/src/internal/stm/tSet.ts +++ b/packages/effect/src/internal/stm/tSet.ts @@ -1,9 +1,9 @@ +import * as RA from "../../Array.js" import * as Chunk from "../../Chunk.js" import { dual, pipe } from "../../Function.js" import * as HashSet from "../../HashSet.js" import type * as Option from "../../Option.js" import { hasProperty, type Predicate } from "../../Predicate.js" -import * as RA from "../../ReadonlyArray.js" import * as STM from "../../STM.js" import type * as TMap from "../../TMap.js" import type * as TSet from "../../TSet.js" diff --git a/packages/effect/test/ReadonlyArray.test.ts b/packages/effect/test/Array.test.ts similarity index 99% rename from packages/effect/test/ReadonlyArray.test.ts rename to packages/effect/test/Array.test.ts index 379e6baceb..b157c6bde9 100644 --- a/packages/effect/test/ReadonlyArray.test.ts +++ b/packages/effect/test/Array.test.ts @@ -1,11 +1,11 @@ import { deepStrictEqual, double, strictEqual } from "effect-test/util" +import * as RA from "effect/Array" import * as E from "effect/Either" import { identity, pipe } from "effect/Function" import * as Number from "effect/Number" import * as O from "effect/Option" import * as Order from "effect/Order" import type { Predicate } from "effect/Predicate" -import * as RA from "effect/ReadonlyArray" import * as String from "effect/String" import * as fc from "fast-check" import { assert, describe, expect, it } from "vitest" diff --git a/packages/effect/test/Channel/mapping.test.ts b/packages/effect/test/Channel/mapping.test.ts index b3da5409db..9f47888b71 100644 --- a/packages/effect/test/Channel/mapping.test.ts +++ b/packages/effect/test/Channel/mapping.test.ts @@ -1,4 +1,5 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Channel from "effect/Channel" import * as ChildExecutorDecision from "effect/ChildExecutorDecision" import * as Chunk from "effect/Chunk" @@ -6,7 +7,6 @@ import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import { constVoid, pipe } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import * as UpstreamPullRequest from "effect/UpstreamPullRequest" import * as UpstreamPullStrategy from "effect/UpstreamPullStrategy" @@ -56,7 +56,7 @@ describe("Channel", () => { Channel.mapOut((n) => n + 1), Channel.runCollect ) - assert.deepStrictEqual(Array.from(chunk), [2, 3, 4]) + assert.deepStrictEqual(Chunk.toReadonlyArray(chunk), [2, 3, 4]) assert.isUndefined(value) })) @@ -68,7 +68,7 @@ describe("Channel", () => { Channel.flatMap(() => Channel.write("x")), Channel.runCollect ) - assert.deepStrictEqual(Array.from(chunk), ["1", "x"]) + assert.deepStrictEqual(Chunk.toReadonlyArray(chunk), ["1", "x"]) assert.isUndefined(value) })) @@ -79,7 +79,7 @@ describe("Channel", () => { Channel.concatMap((i) => Channel.writeAll(i, i)), Channel.runCollect ) - assert.deepStrictEqual(Array.from(result), [1, 1, 2, 2, 3, 3]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [1, 1, 2, 2, 3, 3]) })) it.effect("concatMap - complex", () => @@ -92,7 +92,7 @@ describe("Channel", () => { Channel.mapOut(Second), Channel.runCollect ) - assert.deepStrictEqual(Array.from(result), [ + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [ Second(First(1)), Second(First(1)), Second(First(1)), @@ -120,7 +120,7 @@ describe("Channel", () => { Channel.pipeTo(readers), Channel.runCollect ) - assert.deepStrictEqual(Array.from(result), [1, 2, 3, 4]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2, 3, 4]) })) it.effect("concatMap - downstream failure", () => @@ -197,7 +197,7 @@ describe("Channel", () => { ), Channel.runCollect ) - assert.deepStrictEqual(Array.from(chunk), [1, 2, 3]) + assert.deepStrictEqual(Chunk.toReadonlyArray(chunk), [1, 2, 3]) assert.deepStrictEqual(array1, ["Inner-1", "Inner-2", "Inner-3"]) assert.deepStrictEqual(array2, ["Outer-0"]) })) @@ -229,7 +229,7 @@ describe("Channel", () => { }) ), Channel.runCollect, - Effect.map(([chunk]) => pipe(Array.from(chunk), ReadonlyArray.getSomes)) + Effect.map(([chunk]) => pipe(Chunk.toReadonlyArray(chunk), Array.getSomes)) ) assert.deepStrictEqual(result, [ [1, 1] as const, @@ -275,7 +275,7 @@ describe("Channel", () => { }) ), Channel.runCollect, - Effect.map(([chunk]) => pipe(Array.from(chunk), ReadonlyArray.getSomes)) + Effect.map(([chunk]) => pipe(Chunk.toReadonlyArray(chunk), Array.getSomes)) ) assert.deepStrictEqual(result, [ [1, 1] as const, diff --git a/packages/effect/test/Channel/reading.test.ts b/packages/effect/test/Channel/reading.test.ts index 7847b72260..3dbc5fc29c 100644 --- a/packages/effect/test/Channel/reading.test.ts +++ b/packages/effect/test/Channel/reading.test.ts @@ -1,5 +1,7 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Channel from "effect/Channel" +import * as Chunk from "effect/Chunk" import * as Effect from "effect/Effect" import * as Equal from "effect/Equal" import { pipe } from "effect/Function" @@ -8,7 +10,6 @@ import * as HashSet from "effect/HashSet" import * as MergeDecision from "effect/MergeDecision" import * as Option from "effect/Option" import * as Random from "effect/Random" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import { assert, describe } from "vitest" @@ -32,7 +33,7 @@ export const refWriter = ( return Channel.readWith({ onInput: (a: A) => Channel.flatMap( - Channel.fromEffect(Effect.asVoid(Ref.update(ref, ReadonlyArray.prepend(a)))), + Channel.fromEffect(Effect.asVoid(Ref.update(ref, Array.prepend(a)))), () => refWriter(ref) ), onFailure: () => Channel.void, @@ -46,8 +47,8 @@ export const refReader = ( return pipe( Channel.fromEffect( Ref.modify(ref, (array) => { - if (ReadonlyArray.isEmptyReadonlyArray(array)) { - return [Option.none(), ReadonlyArray.empty()] as const + if (Array.isEmptyReadonlyArray(array)) { + return [Option.none(), Array.empty()] as const } return [Option.some(array[0]!), array.slice(1)] as const }) @@ -90,7 +91,7 @@ describe("Channel", () => { ) const result = yield* $(Channel.runCollect(channel)) const [chunk, value] = result - assert.deepStrictEqual(Array.from(chunk), [ + assert.deepStrictEqual(Chunk.toReadonlyArray(chunk), [ new Whatever(1), new Whatever(2), new Whatever(3), @@ -130,8 +131,8 @@ describe("Channel", () => { Channel.pipeTo(innerChannel) ) const [chunk, list] = yield* $(Channel.runCollect(channel)) - assert.deepStrictEqual(Array.from(chunk), [1, 1, 2, 2]) - assert.deepStrictEqual(Array.from(list), [1, 1, 2, 2]) + assert.deepStrictEqual(Chunk.toReadonlyArray(chunk), [1, 1, 2, 2]) + assert.deepStrictEqual(list, [1, 1, 2, 2]) })) it.effect("read pipelining 2", () => @@ -214,7 +215,7 @@ describe("Channel", () => { ) const channel = pipe(left, Channel.pipeTo(right)) const result = yield* $(Channel.runDrain(channel), Effect.zipRight(Ref.get(ref))) - assert.deepStrictEqual(Array.from(result), [ + assert.deepStrictEqual(result, [ "Acquire outer", "Acquire 1", "Read 1", @@ -229,8 +230,8 @@ describe("Channel", () => { it.effect("simple concurrent reads", () => Effect.gen(function*($) { const capacity = 128 - const elements = yield* $(Effect.all(Array.from({ length: capacity }, () => Random.nextInt))) - const source = yield* $(Ref.make(ReadonlyArray.fromIterable(elements))) + const elements = yield* $(Effect.replicateEffect(Random.nextInt, capacity)) + const source = yield* $(Ref.make(Array.fromIterable(elements))) const destination = yield* $(Ref.make>([])) const twoWriters = pipe( refWriter(destination), @@ -266,8 +267,8 @@ describe("Channel", () => { Effect.gen(function*($) { const capacity = 128 const f = (n: number) => n + 1 - const elements = yield* $(Effect.all(Array.from({ length: capacity }, () => Random.nextInt))) - const source = yield* $(Ref.make(ReadonlyArray.fromIterable(elements))) + const elements = yield* $(Effect.replicateEffect(Random.nextInt, capacity)) + const source = yield* $(Ref.make(Array.fromIterable(elements))) const destination = yield* $(Ref.make>([])) const twoWriters = pipe( mapper(f), diff --git a/packages/effect/test/Chunk.test.ts b/packages/effect/test/Chunk.test.ts index 2da8618ffb..80e2df2034 100644 --- a/packages/effect/test/Chunk.test.ts +++ b/packages/effect/test/Chunk.test.ts @@ -1,4 +1,5 @@ import * as Util from "effect-test/util" +import * as RA from "effect/Array" import * as Chunk from "effect/Chunk" import * as Duration from "effect/Duration" import * as E from "effect/Either" @@ -8,7 +9,6 @@ import * as N from "effect/Number" import * as Option from "effect/Option" import * as Order from "effect/Order" import type { Predicate } from "effect/Predicate" -import * as RA from "effect/ReadonlyArray" import * as fc from "fast-check" import { assert, describe, expect, it } from "vitest" diff --git a/packages/effect/test/Differ.test.ts b/packages/effect/test/Differ.test.ts index 9d2321b3da..82e7db7871 100644 --- a/packages/effect/test/Differ.test.ts +++ b/packages/effect/test/Differ.test.ts @@ -1,10 +1,10 @@ +import * as RA from "effect/Array" import * as Chunk from "effect/Chunk" import * as Differ from "effect/Differ" import * as Equal from "effect/Equal" import { pipe } from "effect/Function" import * as HashMap from "effect/HashMap" import * as HashSet from "effect/HashSet" -import * as RA from "effect/ReadonlyArray" import { assert, describe, it as it_ } from "vitest" function diffLaws( diff --git a/packages/effect/test/Effect/finalization.test.ts b/packages/effect/test/Effect/finalization.test.ts index c7fbabf0a2..72b3d903e3 100644 --- a/packages/effect/test/Effect/finalization.test.ts +++ b/packages/effect/test/Effect/finalization.test.ts @@ -1,4 +1,5 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import * as Chunk from "effect/Chunk" import * as Deferred from "effect/Deferred" @@ -8,7 +9,6 @@ import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" import { identity, pipe } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import { assert, describe } from "vitest" @@ -241,27 +241,27 @@ describe("Effect", () => { yield* $( Ref.get(ref), Effect.zipLeft(Effect.sleep(Duration.millis(1))), - Effect.repeat({ until: (list) => pipe(list, ReadonlyArray.findFirst((s) => s === "start 1"), Option.isSome) }) + Effect.repeat({ until: (list) => pipe(list, Array.findFirst((s) => s === "start 1"), Option.isSome) }) ) yield* $(Fiber.interrupt(fiber)) yield* $( Ref.get(ref), Effect.zipLeft(Effect.sleep(Duration.millis(1))), - Effect.repeat({ until: (list) => pipe(list, ReadonlyArray.findFirst((s) => s === "release 2"), Option.isSome) }) + Effect.repeat({ until: (list) => pipe(list, Array.findFirst((s) => s === "release 2"), Option.isSome) }) ) const result = yield* $(Ref.get(ref)) assert.isTrue(pipe( result, - ReadonlyArray.findFirst((s) => s === "start 1"), + Array.findFirst((s) => s === "start 1"), Option.isSome )) assert.isTrue(pipe( result, - ReadonlyArray.findFirst((s) => s === "release 1"), + Array.findFirst((s) => s === "release 1"), Option.isSome )) - assert.isTrue(pipe(result, ReadonlyArray.findFirst((s) => s === "start 2"), Option.isSome)) - assert.isTrue(pipe(result, ReadonlyArray.findFirst((s) => s === "release 2"), Option.isSome)) + assert.isTrue(pipe(result, Array.findFirst((s) => s === "start 2"), Option.isSome)) + assert.isTrue(pipe(result, Array.findFirst((s) => s === "release 2"), Option.isSome)) })) it.live("interrupt waits for finalizer", () => Effect.gen(function*($) { diff --git a/packages/effect/test/Effect/interruption.test.ts b/packages/effect/test/Effect/interruption.test.ts index 0f9d3b973b..b0024c268f 100644 --- a/packages/effect/test/Effect/interruption.test.ts +++ b/packages/effect/test/Effect/interruption.test.ts @@ -1,5 +1,6 @@ import * as it from "effect-test/utils/extend" import { withLatch, withLatchAwait } from "effect-test/utils/latch" +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import * as Chunk from "effect/Chunk" import * as Deferred from "effect/Deferred" @@ -13,7 +14,6 @@ import { constVoid, pipe } from "effect/Function" import * as HashSet from "effect/HashSet" import * as MutableRef from "effect/MutableRef" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import * as TestClock from "effect/TestClock" import { assert, describe } from "vitest" @@ -250,10 +250,10 @@ describe("Effect", () => { ) yield* $(Deferred.await(latch1), Effect.zipRight(Fiber.interrupt(fiber))) const result = yield* $(Ref.get(exits), Effect.map(process)) - assert.strictEqual(Array.from(result).length, 2) + assert.strictEqual(Chunk.size(result), 2) assert.isTrue(pipe( result, - ReadonlyArray.reduce(true, (acc, curr) => + Array.reduce(true, (acc, curr) => acc && Exit.isFailure(curr) && Cause.isInterruptedOnly(curr.effect_instruction_i0)) )) })) diff --git a/packages/effect/test/Effect/query-nested.test.ts b/packages/effect/test/Effect/query-nested.test.ts index ab9ca1bb94..bd3b85f100 100644 --- a/packages/effect/test/Effect/query-nested.test.ts +++ b/packages/effect/test/Effect/query-nested.test.ts @@ -1,9 +1,9 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Context from "effect/Context" import { seconds } from "effect/Duration" import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Request from "effect/Request" import * as Resolver from "effect/RequestResolver" import { describe, expect } from "vitest" @@ -65,12 +65,12 @@ export interface GetChildExtra extends Request.Request { export const GetChildExtra = Request.tagged("GetChildExtra") -export const parents = ReadonlyArray.range(1, 2).map((id) => ({ id })) +export const parents = Array.range(1, 2).map((id) => ({ id })) export const children: ReadonlyMap> = new Map( - ReadonlyArray.map(parents, (p) => [ + Array.map(parents, (p) => [ p.id, - ReadonlyArray.of({ id: p.id * 10, parentId: p.id }) + Array.of({ id: p.id * 10, parentId: p.id }) ]) ) diff --git a/packages/effect/test/Effect/query.test.ts b/packages/effect/test/Effect/query.test.ts index 81b735ee8e..1e6ec8c966 100644 --- a/packages/effect/test/Effect/query.test.ts +++ b/packages/effect/test/Effect/query.test.ts @@ -1,4 +1,5 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import * as Context from "effect/Context" import { seconds } from "effect/Duration" @@ -7,7 +8,6 @@ import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" import * as FiberRef from "effect/FiberRef" import * as Layer from "effect/Layer" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Request from "effect/Request" import * as Resolver from "effect/RequestResolver" import * as TestClock from "effect/TestClock" @@ -24,12 +24,12 @@ interface Requests { } const Requests = Context.GenericTag("requests") -export const userIds: ReadonlyArray = ReadonlyArray.range(1, 26) +export const userIds: ReadonlyArray = Array.range(1, 26) export const userNames: ReadonlyMap = new Map( - ReadonlyArray.zipWith( + Array.zipWith( userIds, - ReadonlyArray.map(ReadonlyArray.range(97, 122), (a) => String.fromCharCode(a)), + Array.map(Array.range(97, 122), (a) => String.fromCharCode(a)), (a, b) => [a, b] as const ) ) diff --git a/packages/effect/test/Effect/traversing.test.ts b/packages/effect/test/Effect/traversing.test.ts index 0b49982bed..17fadeada2 100644 --- a/packages/effect/test/Effect/traversing.test.ts +++ b/packages/effect/test/Effect/traversing.test.ts @@ -1,4 +1,5 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import * as Chunk from "effect/Chunk" import * as Deferred from "effect/Deferred" @@ -7,7 +8,6 @@ import * as Either from "effect/Either" import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" import { constVoid, identity, pipe } from "effect/Function" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import { assert, describe } from "vitest" @@ -20,7 +20,7 @@ describe("Effect", () => { Effect.dropWhile((n) => Effect.succeed(n % 2 === 1)) ) ) - assert.deepStrictEqual(Array.from(result), [2, 3, 4, 5]) + assert.deepStrictEqual(result, [2, 3, 4, 5]) })) it.effect("dropWhile - error", () => Effect.gen(function*($) { @@ -64,12 +64,12 @@ describe("Effect", () => { })) it.effect("loop - loops with the specified effectual function", () => Effect.gen(function*($) { - const ref = yield* $(Ref.make(ReadonlyArray.empty())) + const ref = yield* $(Ref.make(Array.empty())) yield* $( Effect.loop(0, { while: (n) => n < 5, step: (n) => n + 1, - body: (n) => Ref.update(ref, ReadonlyArray.append(n)) + body: (n) => Ref.update(ref, Array.append(n)) }) ) const result = yield* $(Ref.get(ref)) @@ -77,11 +77,11 @@ describe("Effect", () => { })) it.effect("loop/discard - loops with the specified effectual function", () => Effect.gen(function*($) { - const ref = yield* $(Ref.make(ReadonlyArray.empty())) + const ref = yield* $(Ref.make(Array.empty())) yield* $(Effect.loop(0, { while: (n) => n < 5, step: (n) => n + 1, - body: (n) => Ref.update(ref, ReadonlyArray.append(n)), + body: (n) => Ref.update(ref, Array.append(n)), discard: true })) const result = yield* $(Ref.get(ref)) @@ -100,12 +100,12 @@ describe("Effect", () => { it.effect("replicate - positive", () => Effect.gen(function*($) { const result = yield* $(Effect.all(pipe(Effect.succeed(12), Effect.replicate(2)))) - assert.deepStrictEqual(Array.from(result), [12, 12]) + assert.deepStrictEqual(result, [12, 12]) })) it.effect(" - returns the list of results", () => Effect.gen(function*($) { const result = yield* $([1, 2, 3, 4, 5, 6], Effect.forEach((n) => Effect.succeed(n + 1))) - assert.deepStrictEqual(Array.from(result), [2, 3, 4, 5, 6, 7]) + assert.deepStrictEqual(result, [2, 3, 4, 5, 6, 7]) })) it.effect("forEach - both evaluates effects and returns results in the same order", () => Effect.gen(function*($) { @@ -120,8 +120,8 @@ describe("Effect", () => { ) ) const effects = yield* $(Ref.get(ref), Effect.map(Chunk.reverse)) - assert.deepStrictEqual(Array.from(effects), ["1", "2", "3"]) - assert.deepStrictEqual(Array.from(result), [1, 2, 3]) + assert.deepStrictEqual(Chunk.toReadonlyArray(effects), ["1", "2", "3"]) + assert.deepStrictEqual(result, [1, 2, 3]) })) it.effect("forEach - fails if one of the effects fails", () => Effect.gen(function*($) { @@ -143,8 +143,8 @@ describe("Effect", () => { })) it.effect("forEach/discard - runs effects in order", () => Effect.gen(function*($) { - const ref = yield* $(Ref.make(ReadonlyArray.empty())) - yield* $([1, 2, 3, 4, 5], Effect.forEach((n) => Ref.update(ref, ReadonlyArray.append(n)), { discard: true })) + const ref = yield* $(Ref.make(Array.empty())) + yield* $([1, 2, 3, 4, 5], Effect.forEach((n) => Ref.update(ref, Array.append(n)), { discard: true })) const result = yield* $(Ref.get(ref)) assert.deepStrictEqual(result, [1, 2, 3, 4, 5]) })) @@ -160,23 +160,23 @@ describe("Effect", () => { it.effect("forEach/concurrency - runs single task", () => Effect.gen(function*($) { const result = yield* $([2], Effect.forEach((n) => Effect.succeed(n * 2), { concurrency: "unbounded" })) - assert.deepStrictEqual(Array.from(result), [4]) + assert.deepStrictEqual(result, [4]) })) it.effect("forEach/concurrency - runs two tasks", () => Effect.gen(function*($) { const result = yield* $([2, 3], Effect.forEach((n) => Effect.succeed(n * 2), { concurrency: "unbounded" })) - assert.deepStrictEqual(Array.from(result), [4, 6]) + assert.deepStrictEqual(result, [4, 6]) })) it.effect("forEach/concurrency - runs many tasks", () => Effect.gen(function*($) { - const array = Array.from({ length: 100 }, (_, i) => i + 1) + const array = Array.makeBy(100, (i) => i + 1) const result = yield* $(array, Effect.forEach((n) => Effect.succeed(n * 2), { concurrency: "unbounded" })) - assert.deepStrictEqual(Array.from(result), array.map((n) => n * 2)) + assert.deepStrictEqual(result, array.map((n) => n * 2)) })) it.effect("forEach/concurrency - runs a task that fails", () => Effect.gen(function*($) { const result = yield* $( - Array.from({ length: 10 }, (_, i) => i + 1), + Array.makeBy(10, (i) => i + 1), Effect.forEach((n) => n === 5 ? Effect.fail("boom") : Effect.succeed(n * 2), { concurrency: "unbounded" }), Effect.flip ) @@ -185,7 +185,7 @@ describe("Effect", () => { it.effect("forEach/concurrency - runs two failed tasks", () => Effect.gen(function*($) { const result = yield* $( - Array.from({ length: 10 }, (_, i) => i + 1), + Array.makeBy(10, (i) => i + 1), Effect.forEach((n) => n === 5 ? Effect.fail("boom1") @@ -199,7 +199,7 @@ describe("Effect", () => { it.effect("forEach/concurrency - runs a task that dies", () => Effect.gen(function*($) { const result = yield* $( - Array.from({ length: 10 }, (_, i) => i + 1), + Array.makeBy(10, (i) => i + 1), Effect.forEach((n) => n === 5 ? Effect.dieMessage("boom") : Effect.succeed(n * 2), { concurrency: "unbounded" }), @@ -210,7 +210,7 @@ describe("Effect", () => { it.effect("forEach/concurrency - runs a task that is interrupted", () => Effect.gen(function*($) { const result = yield* $( - Array.from({ length: 10 }, (_, i) => i + 1), + Array.makeBy(10, (i) => i + 1), Effect.forEach((n) => n === 5 ? Effect.interrupt : Effect.succeed(n * 2), { concurrency: "unbounded" }), Effect.exit ) @@ -234,7 +234,7 @@ describe("Effect", () => { ["1", "2", "3"], Effect.forEach((s) => Effect.sync(() => Number.parseInt(s)), { concurrency: "unbounded" }) ) - assert.deepStrictEqual(Array.from(result), [1, 2, 3]) + assert.deepStrictEqual(result, [1, 2, 3]) })) it.effect("forEach/concurrency - runs effects in parallel", () => Effect.gen(function*($) { @@ -277,7 +277,7 @@ describe("Effect", () => { Effect.gen(function*($) { const ref = yield* $(Ref.make(0)) const fibers = yield* $( - Array.from({ length: 100 }, (_, i) => i + 1), + Array.makeBy(100, (i) => i + 1), Effect.forEach(() => pipe(Ref.update(ref, (_) => _ + 1), Effect.fork), { concurrency: "unbounded" }) ) yield* $(fibers, Effect.forEach(Fiber.await)) @@ -292,19 +292,19 @@ describe("Effect", () => { Effect.forEach((n) => Effect.succeed(n.toString()), { concurrency: 2 }) ) ) - assert.deepStrictEqual(Array.from(result), ["1", "2", "3"]) + assert.deepStrictEqual(result, ["1", "2", "3"]) })) it.effect("forEach/concurrency - parallelism - works on large lists", () => Effect.gen(function*($) { const parallelism = 10 - const array = Array.from({ length: 100000 }, (_, i) => i) + const array = Array.makeBy(100000, (i) => i) const result = yield* $( pipe( array, Effect.forEach((n) => Effect.succeed(n), { concurrency: parallelism }) ) ) - assert.deepStrictEqual(Array.from(result), array) + assert.deepStrictEqual(result, array) })) it.effect("forEach/concurrency - parallelism - runs effects in parallel", () => Effect.gen(function*($) { @@ -374,7 +374,7 @@ describe("Effect", () => { onSuccess: () => Chunk.empty() }) ) - assert.deepStrictEqual(Array.from(result), [1, 2, 3]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2, 3]) })) it.effect("forEach/concurrency+discard - runs all effects", () => Effect.gen(function*($) { @@ -387,7 +387,7 @@ describe("Effect", () => { }) ) const result = yield* $(Ref.get(ref), Effect.map(Chunk.reverse)) - assert.deepStrictEqual(Array.from(result), [1, 2, 3, 4, 5]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2, 3, 4, 5]) })) it.effect("forEach/concurrency+discard - completes on empty input", () => Effect.gen(function*($) { @@ -411,7 +411,7 @@ describe("Effect", () => { }) ) const result = yield* $(Ref.get(ref), Effect.map(Chunk.reverse)) - assert.deepStrictEqual(Array.from(result), [1, 2, 3, 4, 5]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2, 3, 4, 5]) })) it.effect("merge - on flipped result", () => Effect.gen(function*($) { @@ -488,26 +488,26 @@ describe("Effect", () => { })) it.effect("partition - collects only successes", () => Effect.gen(function*($) { - const array = Array.from({ length: 10 }, (_, i) => i) + const array = Array.makeBy(10, (i) => i) const [left, right] = yield* $(array, Effect.partition(Effect.succeed)) - assert.deepStrictEqual(Array.from(left), []) - assert.deepStrictEqual(Array.from(right), array) + assert.deepStrictEqual(left, []) + assert.deepStrictEqual(right, array) })) it.effect("partition - collects only failures", () => Effect.gen(function*($) { - const array = Array.from({ length: 10 }, () => 0) + const array = Array.makeBy(10, () => 0) const [left, right] = yield* $(array, Effect.partition(Effect.fail)) - assert.deepStrictEqual(Array.from(left), array) - assert.deepStrictEqual(Array.from(right), []) + assert.deepStrictEqual(left, array) + assert.deepStrictEqual(right, []) })) it.effect("partition - collects failures and successes", () => Effect.gen(function*($) { - const array = Array.from({ length: 10 }, (_, i) => i) + const array = Array.makeBy(10, (i) => i) const [left, right] = yield* $( pipe(array, Effect.partition((n) => n % 2 === 0 ? Effect.fail(n) : Effect.succeed(n))) ) - assert.deepStrictEqual(Array.from(left), [0, 2, 4, 6, 8]) - assert.deepStrictEqual(Array.from(right), [1, 3, 5, 7, 9]) + assert.deepStrictEqual(left, [0, 2, 4, 6, 8]) + assert.deepStrictEqual(right, [1, 3, 5, 7, 9]) })) it.effect("partition - evaluates effects in correct order", () => Effect.gen(function*($) { @@ -515,35 +515,35 @@ describe("Effect", () => { const ref = yield* $(Ref.make(Chunk.empty())) yield* $(array, Effect.partition((n) => Ref.update(ref, Chunk.prepend(n)))) const result = yield* $(Ref.get(ref), Effect.map(Chunk.reverse)) - assert.deepStrictEqual(Array.from(result), [2, 4, 6, 3, 5, 6]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [2, 4, 6, 3, 5, 6]) })) it.effect("partition/concurrency - collects successes", () => Effect.gen(function*($) { - const array = Array.from({ length: 1000 }, (_, i) => i) + const array = Array.makeBy(1000, (i) => i) const [left, right] = yield* $( array, Effect.partition(Effect.succeed, { concurrency: "unbounded" }) ) - assert.deepStrictEqual(Array.from(left), []) - assert.deepStrictEqual(Array.from(right), array) + assert.deepStrictEqual(left, []) + assert.deepStrictEqual(right, array) })) it.effect("partition/concurrency - collects failures", () => Effect.gen(function*($) { - const array = Array.from({ length: 10 }, () => 0) + const array = Array.makeBy(10, () => 0) const [left, right] = yield* $( array, Effect.partition(Effect.fail, { concurrency: "unbounded" }) ) - assert.deepStrictEqual(Array.from(left), array) - assert.deepStrictEqual(Array.from(right), []) + assert.deepStrictEqual(left, array) + assert.deepStrictEqual(right, []) })) it.effect("partition/concurrency - collects failures and successes", () => Effect.gen(function*($) { - const array = Array.from({ length: 10 }, (_, i) => i) + const array = Array.makeBy(10, (i) => i) const [left, right] = yield* $( pipe( array, @@ -552,42 +552,42 @@ describe("Effect", () => { }) ) ) - assert.deepStrictEqual(Array.from(left), [0, 2, 4, 6, 8]) - assert.deepStrictEqual(Array.from(right), [1, 3, 5, 7, 9]) + assert.deepStrictEqual(left, [0, 2, 4, 6, 8]) + assert.deepStrictEqual(right, [1, 3, 5, 7, 9]) })) it.effect("partition/concurrency - parallelism - collects successes", () => Effect.gen(function*($) { - const array = Array.from({ length: 1000 }, (_, i) => i) + const array = Array.makeBy(1000, (i) => i) const [left, right] = yield* $( array, Effect.partition(Effect.succeed, { concurrency: 3 }) ) - assert.deepStrictEqual(Array.from(left), []) - assert.deepStrictEqual(Array.from(right), array) + assert.deepStrictEqual(left, []) + assert.deepStrictEqual(right, array) })) it.effect("partition/concurrency - parallelism - collects failures", () => Effect.gen(function*($) { - const array = Array.from({ length: 10 }, () => 0) + const array = Array.makeBy(10, () => 0) const [left, right] = yield* $( array, Effect.partition(Effect.fail, { concurrency: 3 }) ) - assert.deepStrictEqual(Array.from(left), array) - assert.deepStrictEqual(Array.from(right), []) + assert.deepStrictEqual(left, array) + assert.deepStrictEqual(right, []) })) it.effect("partition/concurrency - parallelism - collects failures and successes", () => Effect.gen(function*($) { - const array = Array.from({ length: 10 }, (_, i) => i) + const array = Array.makeBy(10, (i) => i) const [left, right] = yield* $( array, Effect.partition((n) => n % 2 === 0 ? Effect.fail(n) : Effect.succeed(n), { concurrency: 3 }) ) - assert.deepStrictEqual(Array.from(left), [0, 2, 4, 6, 8]) - assert.deepStrictEqual(Array.from(right), [1, 3, 5, 7, 9]) + assert.deepStrictEqual(left, [0, 2, 4, 6, 8]) + assert.deepStrictEqual(right, [1, 3, 5, 7, 9]) })) it.effect("reduce - with a successful step function sums the list properly", () => Effect.gen(function*($) { @@ -685,7 +685,7 @@ describe("Effect", () => { (n) => Effect.succeed(n >= 3) ) ) - assert.deepStrictEqual(Array.from(result), [1, 2, 3]) + assert.deepStrictEqual(result, [1, 2, 3]) })) it.effect("takeUntil - error", () => Effect.gen(function*($) { @@ -706,7 +706,7 @@ describe("Effect", () => { Effect.takeWhile((n) => Effect.succeed(n % 2 === 1)) ) ) - assert.deepStrictEqual(Array.from(result), [1]) + assert.deepStrictEqual(result, [1]) })) it.effect("takeWhile - error", () => Effect.gen(function*($) { diff --git a/packages/effect/test/Fiber.test.ts b/packages/effect/test/Fiber.test.ts index 55eec46cb9..716dd39cc6 100644 --- a/packages/effect/test/Fiber.test.ts +++ b/packages/effect/test/Fiber.test.ts @@ -1,5 +1,6 @@ import * as it from "effect-test/utils/extend" import { withLatch } from "effect-test/utils/latch" +import * as Array from "effect/Array" import * as Chunk from "effect/Chunk" import * as Deferred from "effect/Deferred" import * as Effect from "effect/Effect" @@ -11,13 +12,12 @@ import * as FiberStatus from "effect/FiberStatus" import { constVoid, pipe } from "effect/Function" import * as HashSet from "effect/HashSet" import * as Queue from "effect/Queue" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import { assert, describe } from "vitest" const initial = "initial" const update = "update" -const fibers = Array.from({ length: 10000 }, () => Fiber.void) +const fibers = Array.makeBy(10000, () => Fiber.void) describe("Fiber", () => { it.effect("should track blockingOn in await", () => @@ -133,7 +133,7 @@ describe("Fiber", () => { Effect.forever ) return pipe( - Effect.forkAll(Array.from({ length: n }, () => worker1)), + Effect.forkAll(Array.makeBy(n, () => worker1)), Effect.flatMap(Fiber.join), Effect.zipRight(Effect.never) ) @@ -145,7 +145,7 @@ describe("Fiber", () => { return pipe(Queue.offer(queue, n), Effect.asVoid) } const queue = yield* $(Queue.unbounded()) - yield* $(Queue.offerAll(queue, Array.from(Array(100), (_, i) => i + 1))) + yield* $(Queue.offerAll(queue, Array.range(1, 100))) const result = yield* $(Effect.exit(shard(queue, 4, worker))) yield* $(Queue.shutdown(queue)) assert.isTrue(Exit.isFailure(result)) @@ -165,7 +165,7 @@ describe("Fiber", () => { it.effect("dual roots", () => Effect.gen(function*($) { const rootContains = (fiber: Fiber.RuntimeFiber): Effect.Effect => { - return pipe(Fiber.roots, Effect.map(Chunk.unsafeFromArray), Effect.map(ReadonlyArray.contains(fiber))) + return pipe(Fiber.roots, Effect.map(Chunk.unsafeFromArray), Effect.map(Array.contains(fiber))) } const fiber1 = yield* $(Effect.forkDaemon(Effect.never)) const fiber2 = yield* $(Effect.forkDaemon(Effect.never)) @@ -201,7 +201,7 @@ describe("Fiber", () => { it.effect("await does not return until all fibers have completed execution", () => Effect.gen(function*($) { const ref = yield* $(Ref.make(0)) - const fiber = yield* $(Effect.forkAll(Array.from({ length: 100 }, () => Ref.set(ref, 10)))) + const fiber = yield* $(Effect.forkAll(Array.makeBy(100, () => Ref.set(ref, 10)))) yield* $(Fiber.interrupt(fiber)) yield* $(Ref.set(ref, -1)) const result = yield* $(Ref.get(ref)) diff --git a/packages/effect/test/FiberMap.test.ts b/packages/effect/test/FiberMap.test.ts index fd5cb3d4d4..f89263a47f 100644 --- a/packages/effect/test/FiberMap.test.ts +++ b/packages/effect/test/FiberMap.test.ts @@ -1,4 +1,4 @@ -import { Effect, Exit, ReadonlyArray, Ref, Scope } from "effect" +import { Array, Effect, Exit, Ref, Scope } from "effect" import * as it from "effect-test/utils/extend" import * as FiberMap from "effect/FiberMap" import { assert, describe } from "vitest" @@ -11,7 +11,7 @@ describe("FiberMap", () => { Effect.gen(function*(_) { const map = yield* _(FiberMap.make()) yield* _( - Effect.forEach(ReadonlyArray.range(1, 10), (i) => + Effect.forEach(Array.range(1, 10), (i) => Effect.onInterrupt( Effect.never, () => Ref.update(ref, (n) => n + 1) @@ -34,7 +34,7 @@ describe("FiberMap", () => { Effect.gen(function*(_) { const map = yield* _(FiberMap.make()) const run = yield* _(FiberMap.runtime(map)()) - ReadonlyArray.range(1, 10).forEach((i) => + Array.range(1, 10).forEach((i) => run( i, Effect.onInterrupt( diff --git a/packages/effect/test/FiberSet.test.ts b/packages/effect/test/FiberSet.test.ts index d6ee1545e0..15270c6c5a 100644 --- a/packages/effect/test/FiberSet.test.ts +++ b/packages/effect/test/FiberSet.test.ts @@ -1,4 +1,4 @@ -import { Effect, Exit, ReadonlyArray, Ref, Scope } from "effect" +import { Array, Effect, Exit, Ref, Scope } from "effect" import * as it from "effect-test/utils/extend" import * as FiberSet from "effect/FiberSet" import { assert, describe } from "vitest" @@ -34,7 +34,7 @@ describe("FiberSet", () => { Effect.gen(function*(_) { const set = yield* _(FiberSet.make()) const run = yield* _(FiberSet.runtime(set)()) - ReadonlyArray.range(1, 10).forEach(() => + Array.range(1, 10).forEach(() => run( Effect.onInterrupt( Effect.never, diff --git a/packages/effect/test/KeyedPool.test.ts b/packages/effect/test/KeyedPool.test.ts index a7449b7d2b..8cb8257249 100644 --- a/packages/effect/test/KeyedPool.test.ts +++ b/packages/effect/test/KeyedPool.test.ts @@ -1,11 +1,11 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Duration from "effect/Duration" import * as Effect from "effect/Effect" import * as Fiber from "effect/Fiber" import { pipe } from "effect/Function" import * as KeyedPool from "effect/KeyedPool" import * as Random from "effect/Random" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import * as TestClock from "effect/TestClock" import { describe, expect } from "vitest" @@ -27,7 +27,7 @@ describe("KeyedPool", () => { ) const fiber = yield* $(Effect.fork( Effect.forEach( - ReadonlyArray.range(1, N), + Array.range(1, N), () => Effect.scoped( Effect.zipRight( @@ -53,7 +53,7 @@ describe("KeyedPool", () => { })) const fiber = yield* $(Effect.fork( Effect.forEach( - ReadonlyArray.range(1, N), + Array.range(1, N), () => Effect.scoped(pipe( KeyedPool.get(pool, "key1"), diff --git a/packages/effect/test/List.test.ts b/packages/effect/test/List.test.ts index 9c6013c358..bb94112c80 100644 --- a/packages/effect/test/List.test.ts +++ b/packages/effect/test/List.test.ts @@ -1,10 +1,10 @@ +import * as Array from "effect/Array" import * as Chunk from "effect/Chunk" import * as Duration from "effect/Duration" import * as Either from "effect/Either" import { equals, symbol } from "effect/Equal" import * as List from "effect/List" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import { describe, expect, it } from "vitest" const testStructuralSharing = (a: List.List, b: List.List, n = 0): number | undefined => { @@ -25,7 +25,7 @@ describe("List", () => { }) it("is an iterable", () => { - expect(Array.from(List.make(0, 1, 2, 3))).toEqual([0, 1, 2, 3]) + expect(Array.fromIterable(List.make(0, 1, 2, 3))).toEqual([0, 1, 2, 3]) }) it("isList", () => { @@ -251,8 +251,8 @@ describe("List", () => { }) it("to iterable", () => { - expect(ReadonlyArray.fromIterable(List.empty())).toEqual([]) - expect(ReadonlyArray.fromIterable(List.make(1, 2, 3))).toEqual([1, 2, 3]) + expect(Array.fromIterable(List.empty())).toEqual([]) + expect(Array.fromIterable(List.make(1, 2, 3))).toEqual([1, 2, 3]) }) it("fromIterable", () => { diff --git a/packages/effect/test/Metric.test.ts b/packages/effect/test/Metric.test.ts index c937e9a3b6..7ce9b77676 100644 --- a/packages/effect/test/Metric.test.ts +++ b/packages/effect/test/Metric.test.ts @@ -1,4 +1,5 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Clock from "effect/Clock" import * as Duration from "effect/Duration" import * as Effect from "effect/Effect" @@ -12,7 +13,6 @@ import * as MetricLabel from "effect/MetricLabel" import * as MetricPolling from "effect/MetricPolling" import * as MetricState from "effect/MetricState" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Schedule from "effect/Schedule" import { assert, describe, expect } from "vitest" @@ -653,12 +653,11 @@ describe("Metric", () => { const result3 = yield* _(Metric.value(counter3)) const snapshot = yield* _(Metric.snapshot) - const values = Array.from(snapshot) const pair1 = yield* _( - ReadonlyArray.findFirst(values, (key) => Equal.equals(key.metricKey, MetricKey.counter(name))) + Array.findFirst(snapshot, (key) => Equal.equals(key.metricKey, MetricKey.counter(name))) ) const pair2 = yield* _( - ReadonlyArray.findFirst(values, (key) => + Array.findFirst(snapshot, (key) => Equal.equals( key.metricKey, MetricKey.counter(name, { @@ -667,7 +666,7 @@ describe("Metric", () => { )) ) const pair3 = yield* _( - ReadonlyArray.findFirst(values, (key) => + Array.findFirst(snapshot, (key) => Equal.equals( key.metricKey, MetricKey.counter(name, { @@ -703,8 +702,8 @@ describe("Metric", () => { Metric.counter(id).register() const snapshot = yield* _(Metric.snapshot) const value = pipe( - ReadonlyArray.fromIterable(snapshot), - ReadonlyArray.findFirst((_) => _.metricKey.name === id) + Array.fromIterable(snapshot), + Array.findFirst((_) => _.metricKey.name === id) ) expect(value._tag).toBe("Some") })) diff --git a/packages/effect/test/Order.test.ts b/packages/effect/test/Order.test.ts index 2d89be1404..a13f98e50e 100644 --- a/packages/effect/test/Order.test.ts +++ b/packages/effect/test/Order.test.ts @@ -1,7 +1,7 @@ import * as U from "effect-test/util" +import { sort } from "effect/Array" import { pipe } from "effect/Function" import * as _ from "effect/Order" -import { sort } from "effect/ReadonlyArray" import { describe, it } from "vitest" describe("Order", () => { diff --git a/packages/effect/test/PubSub.test.ts b/packages/effect/test/PubSub.test.ts index 220b493957..94ba8bdb25 100644 --- a/packages/effect/test/PubSub.test.ts +++ b/packages/effect/test/PubSub.test.ts @@ -1,11 +1,11 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Deferred from "effect/Deferred" import * as Effect from "effect/Effect" import * as Fiber from "effect/Fiber" import { pipe } from "effect/Function" import * as PubSub from "effect/PubSub" import * as Queue from "effect/Queue" -import * as ReadonlyArray from "effect/ReadonlyArray" import { assert, describe } from "vitest" describe("PubSub", () => { @@ -65,7 +65,7 @@ describe("PubSub", () => { }) it.effect("sequential publishers and subscribers with one publisher and one subscriber", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(0, 9) + const values = Array.range(0, 9) const deferred1 = yield* $(Deferred.make()) const deferred2 = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.bounded(10)) @@ -91,7 +91,7 @@ describe("PubSub", () => { })) it.effect("sequential publishers and subscribers with one publisher and two subscribers", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(0, 9) + const values = Array.range(0, 9) const deferred1 = yield* $(Deferred.make()) const deferred2 = yield* $(Deferred.make()) const deferred3 = yield* $(Deferred.make()) @@ -135,7 +135,7 @@ describe("PubSub", () => { })) it.effect("backpressured concurrent publishers and subscribers - one to one", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(0, 64) + const values = Array.range(0, 64) const deferred = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.bounded(64)) const subscriber = yield* $( @@ -160,7 +160,7 @@ describe("PubSub", () => { })) it.effect("backpressured concurrent publishers and subscribers - one to many", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(0, 64) + const values = Array.range(0, 64) const deferred1 = yield* $(Deferred.make()) const deferred2 = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.bounded(64)) @@ -200,7 +200,7 @@ describe("PubSub", () => { })) it.effect("backpressured concurrent publishers and subscribers - many to many", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(1, 64) + const values = Array.range(1, 64) const deferred1 = yield* $(Deferred.make()) const deferred2 = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.bounded(64 * 2)) @@ -211,7 +211,7 @@ describe("PubSub", () => { Deferred.succeed(deferred1, void 0), Effect.zipRight(pipe( values, - ReadonlyArray.appendAll(values), + Array.appendAll(values), Effect.forEach((_) => Queue.take(subscription)) )) ) @@ -226,7 +226,7 @@ describe("PubSub", () => { Deferred.succeed(deferred2, void 0), Effect.zipRight(pipe( values, - ReadonlyArray.appendAll(values), + Array.appendAll(values), Effect.forEach((_) => Queue.take(subscription)) )) ) @@ -241,24 +241,24 @@ describe("PubSub", () => { Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork ) - yield* $(values, ReadonlyArray.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork) + yield* $(values, Array.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork) const result1 = yield* $(Fiber.join(subscriber1)) const result2 = yield* $(Fiber.join(subscriber2)) yield* $(Fiber.join(fiber)) - assert.deepStrictEqual(pipe(result1, ReadonlyArray.filter((n) => n > 0)), values) + assert.deepStrictEqual(pipe(result1, Array.filter((n) => n > 0)), values) assert.deepStrictEqual( - pipe(result1, ReadonlyArray.filter((n) => n < 0)), - pipe(values, ReadonlyArray.map((n) => -n)) + pipe(result1, Array.filter((n) => n < 0)), + pipe(values, Array.map((n) => -n)) ) - assert.deepStrictEqual(pipe(result2, ReadonlyArray.filter((n) => n > 0)), values) + assert.deepStrictEqual(pipe(result2, Array.filter((n) => n > 0)), values) assert.deepStrictEqual( - pipe(result2, ReadonlyArray.filter((n) => n < 0)), - pipe(values, ReadonlyArray.map((n) => -n)) + pipe(result2, Array.filter((n) => n < 0)), + pipe(values, Array.map((n) => -n)) ) })) it.effect("dropping concurrent publishers and subscribers - one to one", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(0, 64) + const values = Array.range(0, 64) const deferred = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.dropping(64)) const subscriber = yield* $( @@ -283,7 +283,7 @@ describe("PubSub", () => { })) it.effect("dropping concurrent publishers and subscribers - one to many", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(0, 64) + const values = Array.range(0, 64) const deferred1 = yield* $(Deferred.make()) const deferred2 = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.dropping(64)) @@ -323,7 +323,7 @@ describe("PubSub", () => { })) it.effect("dropping concurrent publishers and subscribers - many to many", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(1, 64) + const values = Array.range(1, 64) const deferred1 = yield* $(Deferred.make()) const deferred2 = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.dropping(64 * 2)) @@ -334,7 +334,7 @@ describe("PubSub", () => { Deferred.succeed(deferred1, void 0), Effect.zipRight(pipe( values, - ReadonlyArray.appendAll(values), + Array.appendAll(values), Effect.forEach((_) => Queue.take(subscription)) )) ) @@ -349,7 +349,7 @@ describe("PubSub", () => { Deferred.succeed(deferred2, void 0), Effect.zipRight(pipe( values, - ReadonlyArray.appendAll(values), + Array.appendAll(values), Effect.forEach((_) => Queue.take(subscription)) )) ) @@ -364,24 +364,24 @@ describe("PubSub", () => { Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork ) - yield* $(values, ReadonlyArray.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork) + yield* $(values, Array.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork) const result1 = yield* $(Fiber.join(subscriber1)) const result2 = yield* $(Fiber.join(subscriber2)) yield* $(Fiber.join(fiber)) - assert.deepStrictEqual(pipe(result1, ReadonlyArray.filter((n) => n > 0)), values) + assert.deepStrictEqual(pipe(result1, Array.filter((n) => n > 0)), values) assert.deepStrictEqual( - pipe(result1, ReadonlyArray.filter((n) => n < 0)), - pipe(values, ReadonlyArray.map((n) => -n)) + pipe(result1, Array.filter((n) => n < 0)), + pipe(values, Array.map((n) => -n)) ) - assert.deepStrictEqual(pipe(result2, ReadonlyArray.filter((n) => n > 0)), values) + assert.deepStrictEqual(pipe(result2, Array.filter((n) => n > 0)), values) assert.deepStrictEqual( - pipe(result2, ReadonlyArray.filter((n) => n < 0)), - pipe(values, ReadonlyArray.map((n) => -n)) + pipe(result2, Array.filter((n) => n < 0)), + pipe(values, Array.map((n) => -n)) ) })) it.effect("sliding concurrent publishers and subscribers - one to one", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(0, 64) + const values = Array.range(0, 64) const deferred = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.sliding(64)) const subscriber = yield* $( @@ -406,7 +406,7 @@ describe("PubSub", () => { })) it.effect("sliding concurrent publishers and subscribers - one to many", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(0, 64) + const values = Array.range(0, 64) const deferred1 = yield* $(Deferred.make()) const deferred2 = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.sliding(64)) @@ -446,7 +446,7 @@ describe("PubSub", () => { })) it.effect("sliding concurrent publishers and subscribers - many to many", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(1, 64) + const values = Array.range(1, 64) const deferred1 = yield* $(Deferred.make()) const deferred2 = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.sliding(64 * 2)) @@ -457,7 +457,7 @@ describe("PubSub", () => { Deferred.succeed(deferred1, void 0), Effect.zipRight(pipe( values, - ReadonlyArray.appendAll(values), + Array.appendAll(values), Effect.forEach((_) => Queue.take(subscription)) )) ) @@ -472,7 +472,7 @@ describe("PubSub", () => { Deferred.succeed(deferred2, void 0), Effect.zipRight(pipe( values, - ReadonlyArray.appendAll(values), + Array.appendAll(values), Effect.forEach((_) => Queue.take(subscription)) )) ) @@ -487,24 +487,24 @@ describe("PubSub", () => { Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork ) - yield* $(values, ReadonlyArray.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork) + yield* $(values, Array.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork) const result1 = yield* $(Fiber.join(subscriber1)) const result2 = yield* $(Fiber.join(subscriber2)) yield* $(Fiber.join(fiber)) - assert.deepStrictEqual(pipe(result1, ReadonlyArray.filter((n) => n > 0)), values) + assert.deepStrictEqual(pipe(result1, Array.filter((n) => n > 0)), values) assert.deepStrictEqual( - pipe(result1, ReadonlyArray.filter((n) => n < 0)), - pipe(values, ReadonlyArray.map((n) => -n)) + pipe(result1, Array.filter((n) => n < 0)), + pipe(values, Array.map((n) => -n)) ) - assert.deepStrictEqual(pipe(result2, ReadonlyArray.filter((n) => n > 0)), values) + assert.deepStrictEqual(pipe(result2, Array.filter((n) => n > 0)), values) assert.deepStrictEqual( - pipe(result2, ReadonlyArray.filter((n) => n < 0)), - pipe(values, ReadonlyArray.map((n) => -n)) + pipe(result2, Array.filter((n) => n < 0)), + pipe(values, Array.map((n) => -n)) ) })) it.effect("unbounded concurrent publishers and subscribers - one to one", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(0, 64) + const values = Array.range(0, 64) const deferred = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.unbounded()) const subscriber = yield* $( @@ -530,7 +530,7 @@ describe("PubSub", () => { })) it.effect("unbounded concurrent publishers and subscribers - one to many", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(0, 64) + const values = Array.range(0, 64) const deferred1 = yield* $(Deferred.make()) const deferred2 = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.unbounded()) @@ -570,7 +570,7 @@ describe("PubSub", () => { })) it.effect("unbounded concurrent publishers and subscribers - many to many", () => Effect.gen(function*($) { - const values = ReadonlyArray.range(1, 64) + const values = Array.range(1, 64) const deferred1 = yield* $(Deferred.make()) const deferred2 = yield* $(Deferred.make()) const pubsub = yield* $(PubSub.unbounded()) @@ -581,7 +581,7 @@ describe("PubSub", () => { Deferred.succeed(deferred1, void 0), Effect.zipRight(pipe( values, - ReadonlyArray.appendAll(values), + Array.appendAll(values), Effect.forEach((_) => Queue.take(subscription)) )) ) @@ -597,7 +597,7 @@ describe("PubSub", () => { Deferred.succeed(deferred2, void 0), Effect.zipRight(pipe( values, - ReadonlyArray.appendAll(values), + Array.appendAll(values), Effect.forEach((_) => Queue.take(subscription)) )) ) @@ -612,19 +612,19 @@ describe("PubSub", () => { Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork ) - yield* $(values, ReadonlyArray.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork) + yield* $(values, Array.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork) const result1 = yield* $(Fiber.join(subscriber1)) const result2 = yield* $(Fiber.join(subscriber2)) yield* $(Fiber.join(fiber)) - assert.deepStrictEqual(ReadonlyArray.filter(result1, (n) => n > 0), values) + assert.deepStrictEqual(Array.filter(result1, (n) => n > 0), values) assert.deepStrictEqual( - ReadonlyArray.filter(result1, (n) => n < 0), - ReadonlyArray.map(values, (n) => -n) + Array.filter(result1, (n) => n < 0), + Array.map(values, (n) => -n) ) - assert.deepStrictEqual(ReadonlyArray.filter(result2, (n) => n > 0), values) + assert.deepStrictEqual(Array.filter(result2, (n) => n > 0), values) assert.deepStrictEqual( - ReadonlyArray.filter(result2, (n) => n < 0), - ReadonlyArray.map(values, (n) => -n) + Array.filter(result2, (n) => n < 0), + Array.map(values, (n) => -n) ) })) it.effect("null values", () => { diff --git a/packages/effect/test/Queue.test.ts b/packages/effect/test/Queue.test.ts index 74b5e6db47..e10968a182 100644 --- a/packages/effect/test/Queue.test.ts +++ b/packages/effect/test/Queue.test.ts @@ -1,4 +1,5 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import * as Chunk from "effect/Chunk" import * as Deferred from "effect/Deferred" @@ -9,7 +10,6 @@ import * as Fiber from "effect/Fiber" import { identity, pipe } from "effect/Function" import * as Option from "effect/Option" import * as Queue from "effect/Queue" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import { assert, describe, expect } from "vitest" @@ -47,10 +47,10 @@ describe("Queue", () => { it.effect("dropping - with offerAll, check ordering", () => Effect.gen(function*($) { const queue = yield* $(Queue.dropping(128)) - const result1 = yield* $(Queue.offerAll(queue, Array.from(new Array(256), (_, i) => i + 1))) + const result1 = yield* $(Queue.offerAll(queue, Array.makeBy(256, (i) => i + 1))) const result2 = yield* $(Queue.takeAll(queue)) assert.isFalse(result1) - assert.deepStrictEqual(Chunk.toReadonlyArray(result2), Array.from(new Array(128), (_, i) => i + 1)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result2), Array.makeBy(128, (i) => i + 1)) })) it.effect("dropping - with pending taker", () => Effect.gen(function*($) { @@ -151,7 +151,7 @@ describe("Queue", () => { Effect.gen(function*($) { const queue = yield* $(Queue.bounded(10)) const ref = yield* $(Ref.make>([])) - const values = Array.from(new Array(10), (_, i) => i + 1) + const values = Array.makeBy(10, (i) => i + 1) const fiber = yield* $(Effect.forkAll(values.map((n) => Queue.offer(queue, n)))) yield* $(waitForSize(queue, 10)) yield* $( @@ -232,16 +232,16 @@ describe("Queue", () => { it.effect("offerAll with takeAll", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(10)) - const values = ReadonlyArray.range(1, 10) + const values = Array.range(1, 10) yield* $(Queue.offerAll(queue, values)) yield* $(waitForSize(queue, 10)) const result = yield* $(Queue.takeAll(queue)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 10)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 10)) })) it.effect("offerAll with takeAll and back pressure", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(2)) - const values = ReadonlyArray.range(1, 3) + const values = Array.range(1, 3) const fiber = yield* $(Queue.offerAll(queue, values), Effect.fork) const size = yield* $(waitForSize(queue, 3)) const result = yield* $(Queue.takeAll(queue)) @@ -252,8 +252,8 @@ describe("Queue", () => { it.effect("offerAll with takeAll and back pressure + interruption", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(2)) - const values1 = ReadonlyArray.range(1, 2) - const values2 = ReadonlyArray.range(3, 4) + const values1 = Array.range(1, 2) + const values2 = Array.range(3, 4) yield* $(Queue.offerAll(queue, values1)) const fiber = yield* $(Queue.offerAll(queue, values2), Effect.fork) yield* $(waitForSize(queue, 4)) @@ -266,47 +266,47 @@ describe("Queue", () => { it.effect("offerAll with takeAll and back pressure, check ordering", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(64)) - const fiber = yield* $(Queue.offerAll(queue, Array.from(Array(128), (_, i) => i + 1)), Effect.fork) + const fiber = yield* $(Queue.offerAll(queue, Array.makeBy(128, (i) => i + 1)), Effect.fork) yield* $(waitForSize(queue, 128)) const result = yield* $(Queue.takeAll(queue)) yield* $(Fiber.interrupt(fiber)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 64)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 64)) })) it.effect("offerAll with pending takers", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(50)) - const takers = yield* $(Effect.forkAll(Array.from({ length: 100 }, () => Queue.take(queue)))) + const takers = yield* $(Effect.forkAll(Array.makeBy(100, () => Queue.take(queue)))) yield* $(waitForSize(queue, -100)) - yield* $(queue.offerAll(Array.from(Array(100), (_, i) => i + 1))) + yield* $(queue.offerAll(Array.makeBy(100, (i) => i + 1))) const result = yield* $(Fiber.join(takers)) const size = yield* $(Queue.size(queue)) assert.strictEqual(size, 0) - assert.deepStrictEqual(result, ReadonlyArray.range(1, 100)) + assert.deepStrictEqual(result, Array.range(1, 100)) })) it.effect("offerAll with pending takers, check ordering", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(256)) - const takers = yield* $(Effect.forkAll(Array.from({ length: 64 }, () => Queue.take(queue)))) + const takers = yield* $(Effect.forkAll(Array.makeBy(64, () => Queue.take(queue)))) yield* $(waitForSize(queue, -64)) - yield* $(Queue.offerAll(queue, Array.from({ length: 128 }, (_, i) => i + 1))) + yield* $(Queue.offerAll(queue, Array.makeBy(128, (i) => i + 1))) const result = yield* $(Fiber.join(takers)) const size = yield* $(Queue.size(queue)) assert.strictEqual(size, 64) - assert.deepStrictEqual(result, ReadonlyArray.range(1, 64)) + assert.deepStrictEqual(result, Array.range(1, 64)) })) it.effect("offerAll with pending takers, check ordering of taker resolution", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(200)) - const takers = yield* $(Effect.forkAll(Array.from({ length: 100 }, () => Queue.take(queue)))) + const takers = yield* $(Effect.forkAll(Array.makeBy(100, () => Queue.take(queue)))) yield* $(waitForSize(queue, -100)) - const fiber = yield* $(Effect.forkAll(Array.from({ length: 100 }, () => Queue.take(queue)))) + const fiber = yield* $(Effect.forkAll(Array.makeBy(100, () => Queue.take(queue)))) yield* $(waitForSize(queue, -200)) - yield* $(Queue.offerAll(queue, Array.from({ length: 100 }, (_, i) => i + 1))) + yield* $(Queue.offerAll(queue, Array.makeBy(100, (i) => i + 1))) const result = yield* $(Fiber.join(takers)) const size = yield* $(Queue.size(queue)) yield* $(Fiber.interrupt(fiber)) assert.strictEqual(size, -100) - assert.deepStrictEqual(result, ReadonlyArray.range(1, 100)) + assert.deepStrictEqual(result, Array.range(1, 100)) })) it.effect("offerAll with take and back pressure", () => Effect.gen(function*($) { @@ -342,23 +342,23 @@ describe("Queue", () => { Effect.gen(function*($) { const queue = yield* $(Queue.bounded(1000)) yield* $(Queue.offer(queue, 1)) - yield* $(Queue.offerAll(queue, ReadonlyArray.range(2, 1000))) + yield* $(Queue.offerAll(queue, Array.range(2, 1000))) yield* $(waitForSize(queue, 1000)) const result = yield* $(Queue.takeAll(queue)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 1000)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 1000)) })) it.effect("offerAll combination of offer, offerAll, take, takeAll", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(32)) yield* $(Queue.offer(queue, 1)) yield* $(Queue.offer(queue, 2)) - yield* $(Queue.offerAll(queue, ReadonlyArray.range(3, 35)), Effect.fork) + yield* $(Queue.offerAll(queue, Array.range(3, 35)), Effect.fork) yield* $(waitForSize(queue, 35)) const result1 = yield* $(Queue.takeAll(queue)) const result2 = yield* $(Queue.take(queue)) const result3 = yield* $(Queue.take(queue)) const result4 = yield* $(Queue.take(queue)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result1), ReadonlyArray.range(1, 32)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result1), Array.range(1, 32)) assert.strictEqual(result2, 33) assert.strictEqual(result3, 34) assert.strictEqual(result4, 35) @@ -366,18 +366,18 @@ describe("Queue", () => { it.effect("parallel takes and sequential offers", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(100)) - const fiber = yield* $(Effect.forkAll(Array.from({ length: 10 }, () => Queue.take(queue)))) + const fiber = yield* $(Effect.forkAll(Array.makeBy(10, () => Queue.take(queue)))) yield* $( - Array.from({ length: 10 }, (_, i) => Queue.offer(queue, i + 1)) + Array.makeBy(10, (i) => Queue.offer(queue, i + 1)) .reduce((acc, curr) => pipe(acc, Effect.zipRight(curr)), Effect.succeed(false)) ) const result = yield* $(Fiber.join(fiber)) - assert.deepStrictEqual(result, ReadonlyArray.range(1, 10)) + assert.deepStrictEqual(result, Array.range(1, 10)) })) it.effect("parallel offers and sequential takes", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(10)) - const fiber = yield* $(Effect.forkAll(Array.from({ length: 10 }, (_, i) => Queue.offer(queue, i + 1)))) + const fiber = yield* $(Effect.forkAll(Array.makeBy(10, (i) => Queue.offer(queue, i + 1)))) yield* $(waitForSize(queue, 10)) const ref = yield* $(Ref.make>([])) yield* $( @@ -387,7 +387,7 @@ describe("Queue", () => { ) const result = yield* $(Ref.get(ref)) yield* $(Fiber.join(fiber)) - assert.deepStrictEqual(result, Array.from({ length: 10 }, (_, i) => i + 1)) + assert.deepStrictEqual(result, Array.makeBy(10, (i) => i + 1)) })) it.effect("sequential offer and take", () => Effect.gen(function*($) { @@ -538,7 +538,7 @@ describe("Queue", () => { yield* $(Queue.offer(queue, 2)) yield* $(Queue.offer(queue, 3)) const result = yield* $(Queue.takeAll(queue)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 3)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 3)) })) it.effect("elements can be enqueued syncroniously when there is space", () => Effect.gen(function*($) { @@ -547,7 +547,7 @@ describe("Queue", () => { Queue.unsafeOffer(queue, 2) Queue.unsafeOffer(queue, 3) const result = yield* $(Queue.takeAll(queue)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 3)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 3)) })) it.effect("takeAll returns all values from an empty queue", () => Effect.gen(function*($) { @@ -571,7 +571,7 @@ describe("Queue", () => { yield* $(waitForSize(queue, 5)) const result1 = yield* $(Queue.takeAll(queue)) const result2 = yield* $(Queue.take(queue)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result1), ReadonlyArray.range(1, 4)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result1), Array.range(1, 4)) assert.strictEqual(result2, 5) })) it.effect("takeBetween returns immediately if there is enough elements", () => @@ -581,7 +581,7 @@ describe("Queue", () => { yield* $(Queue.offer(queue, 2)) yield* $(Queue.offer(queue, 3)) const result = yield* $(Queue.takeBetween(queue, 2, 5)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 3)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 3)) })) it.effect("takeBetween returns an empty list if boundaries are inverted", () => Effect.gen(function*($) { @@ -616,14 +616,14 @@ describe("Queue", () => { const fiber = yield* $(values, Effect.forEach((n) => Queue.offer(queue, n)), Effect.fork) const result = yield* $(Queue.takeBetween(queue, values.length, values.length)) yield* $(Fiber.interrupt(fiber)) - assert.deepStrictEqual(Array.from(result), values) + assert.deepStrictEqual(Array.fromIterable(result), values) })) it.effect("takeN returns immediately if there is enough elements", () => Effect.gen(function*($) { const queue = yield* $(Queue.bounded(100)) yield* $(Queue.offerAll(queue, [1, 2, 3, 4, 5])) const result = yield* $(Queue.takeN(queue, 3)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 3)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 3)) })) it.effect("takeN returns an empty list if a negative number or zero is specified", () => Effect.gen(function*($) { @@ -648,7 +648,7 @@ describe("Queue", () => { yield* $(Queue.offer(queue, 1)) yield* $(Queue.offer(queue, 2)) const result = yield* $(Queue.takeUpTo(queue, 2)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 2)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 2)) })) it.effect("should return an empty collection from an empty queue", () => Effect.gen(function*($) { @@ -670,7 +670,7 @@ describe("Queue", () => { yield* $(Queue.offer(queue, 3)) yield* $(Queue.offer(queue, 4)) const result = yield* $(Queue.takeUpTo(queue, 2)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 2)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 2)) })) it.effect("should handle not enough items", () => Effect.gen(function*($) { @@ -680,7 +680,7 @@ describe("Queue", () => { yield* $(Queue.offer(queue, 3)) yield* $(Queue.offer(queue, 4)) const result = yield* $(Queue.takeUpTo(queue, 10)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 4)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 4)) })) it.effect("should handle taking up to 0 items", () => Effect.gen(function*($) { @@ -718,8 +718,8 @@ describe("Queue", () => { yield* $(Queue.offer(queue, 3)) yield* $(Queue.offer(queue, 4)) const result2 = yield* $(Queue.takeUpTo(queue, 2)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result1), ReadonlyArray.range(1, 2)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result2), ReadonlyArray.range(3, 4)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result1), Array.range(1, 2)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result2), Array.range(3, 4)) })) it.effect("consecutive take up to calls", () => Effect.gen(function*($) { @@ -730,8 +730,8 @@ describe("Queue", () => { yield* $(Queue.offer(queue, 4)) const result1 = yield* $(Queue.takeUpTo(queue, 2)) const result2 = yield* $(Queue.takeUpTo(queue, 2)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result1), ReadonlyArray.range(1, 2)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result2), ReadonlyArray.range(3, 4)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result1), Array.range(1, 2)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result2), Array.range(3, 4)) })) it.effect("does not return back-pressured offers", () => Effect.gen(function*($) { @@ -745,7 +745,7 @@ describe("Queue", () => { yield* $(waitForSize(queue, 5)) const result = yield* $(Queue.takeUpTo(queue, 5)) yield* $(Fiber.interrupt(fiber)) - assert.deepStrictEqual(Chunk.toReadonlyArray(result), ReadonlyArray.range(1, 4)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 4)) })) it.effect("rts - handles falsy values", () => Effect.gen(function*($) { diff --git a/packages/effect/test/Random.test.ts b/packages/effect/test/Random.test.ts index cafa689673..49c0c1ac1d 100644 --- a/packages/effect/test/Random.test.ts +++ b/packages/effect/test/Random.test.ts @@ -1,13 +1,13 @@ -import { Chunk, Effect, Random, ReadonlyArray } from "effect" +import { Array, Chunk, Effect, Random } from "effect" import * as it from "effect-test/utils/extend" import { assert, describe } from "vitest" describe("Random", () => { it.effect("shuffle", () => Effect.gen(function*($) { - const start = ReadonlyArray.range(0, 100) + const start = Array.range(0, 100) const end = yield* $(Random.shuffle(start)) assert.isTrue(Chunk.every(end, (n) => n !== undefined)) - assert.deepStrictEqual(start.sort(), Array.from(end).sort()) + assert.deepStrictEqual(start.sort(), Array.fromIterable(end).sort()) }).pipe(Effect.repeatN(100))) }) diff --git a/packages/effect/test/RateLimiter.test.ts b/packages/effect/test/RateLimiter.test.ts index 2e0354f664..7101e655b9 100644 --- a/packages/effect/test/RateLimiter.test.ts +++ b/packages/effect/test/RateLimiter.test.ts @@ -1,16 +1,4 @@ -import { - Clock, - Deferred, - Effect, - Either, - Fiber, - Function, - Option, - RateLimiter, - ReadonlyArray, - Ref, - TestClock -} from "effect" +import { Array, Clock, Deferred, Effect, Either, Fiber, Function, Option, RateLimiter, Ref, TestClock } from "effect" import * as it from "effect-test/utils/extend" import { assert, describe } from "vitest" @@ -28,7 +16,7 @@ describe("RateLimiter", () => { const now = yield* _(Clock.currentTimeMillis) const fib = yield* _( - Effect.forEach(Array.from(Array(20)), () => rl(Clock.currentTimeMillis).pipe(RateLimiter.withCost(10))).pipe( + Effect.replicateEffect(rl(Clock.currentTimeMillis).pipe(RateLimiter.withCost(10)), 20).pipe( Effect.fork ) ) @@ -105,12 +93,13 @@ describe("RateLimiter", () => { // First 30 calls should trigger in the first 15 seconds // and the next 2 calls should trigger at the 1 minute mark. const fib = yield* _( - Effect.forEach(Array.from(Array(32)), () => rl(Clock.currentTimeMillis)).pipe(Effect.fork) + Effect.replicateEffect(rl(Clock.currentTimeMillis), 32).pipe(Effect.fork) ) const timestamps = yield* _( - Effect.all( - Array.from(Array(60)).map(() => Effect.zipRight(TestClock.adjust("1 seconds"), Clock.currentTimeMillis)) + Effect.replicateEffect( + Effect.zipRight(TestClock.adjust("1 seconds"), Clock.currentTimeMillis), + 60 ) ) @@ -146,7 +135,7 @@ describe("RateLimiter", () => { const deferred = yield* _(Deferred.make()) // Use up all of the available tokens - yield* _(Effect.forEach(ReadonlyArray.range(1, 10), () => limit(Effect.void))) + yield* _(Effect.forEach(Array.range(1, 10), () => limit(Effect.void))) // Make an additional request when there are no tokens available yield* _( @@ -175,10 +164,10 @@ const RateLimiterTestSuite = (algorithm: "fixed-window" | "token-bucket") => { })) const now = yield* _(Clock.currentTimeMillis) const times = yield* _(Effect.forEach( - ReadonlyArray.range(1, 10), + Array.range(1, 10), () => limit(Clock.currentTimeMillis) )) - const result = ReadonlyArray.every(times, (time) => time === now) + const result = Array.every(times, (time) => time === now) assert.isTrue(result) })) @@ -191,19 +180,19 @@ const RateLimiterTestSuite = (algorithm: "fixed-window" | "token-bucket") => { })) const now = yield* _(Clock.currentTimeMillis) const times1 = yield* _(Effect.forEach( - ReadonlyArray.range(1, 5), + Array.range(1, 5), () => limiter(Clock.currentTimeMillis), { concurrency: "unbounded" } )) const fibers = yield* _(Effect.forEach( - ReadonlyArray.range(1, 15), + Array.range(1, 15), () => Effect.fork(limiter(Clock.currentTimeMillis)), { concurrency: "unbounded" } )) yield* _(TestClock.adjust("1 seconds")) const times2 = yield* _(Effect.forEach(fibers, Fiber.join, { concurrency: "unbounded" })) - const times = ReadonlyArray.appendAll(times1, times2) - const result = ReadonlyArray.filter(times, (time) => time === now) + const times = Array.appendAll(times1, times2) + const result = Array.filter(times, (time) => time === now) assert.strictEqual(result.length, 10) })) @@ -251,9 +240,10 @@ const RateLimiterTestSuite = (algorithm: "fixed-window" | "token-bucket") => { const now = yield* _(Clock.currentTimeMillis) const fiber = yield* _( - Effect.forEach(Array.from(Array(20)), () => limit(Clock.currentTimeMillis), { - concurrency: "unbounded" - }), + Effect.replicateEffect( + limit(Clock.currentTimeMillis), + 20 + ), Effect.fork ) diff --git a/packages/effect/test/ReadonlyRecord.test.ts b/packages/effect/test/Record.test.ts similarity index 99% rename from packages/effect/test/ReadonlyRecord.test.ts rename to packages/effect/test/Record.test.ts index 61f2fc6ce2..763acdc15a 100644 --- a/packages/effect/test/ReadonlyRecord.test.ts +++ b/packages/effect/test/Record.test.ts @@ -2,7 +2,7 @@ import * as Either from "effect/Either" import { pipe } from "effect/Function" import * as N from "effect/Number" import * as Option from "effect/Option" -import * as RR from "effect/ReadonlyRecord" +import * as RR from "effect/Record" import { assert, describe, expect, it } from "vitest" const symA = Symbol.for("a") diff --git a/packages/effect/test/Schedule.test.ts b/packages/effect/test/Schedule.test.ts index 58f5c559b0..4870260470 100644 --- a/packages/effect/test/Schedule.test.ts +++ b/packages/effect/test/Schedule.test.ts @@ -1,4 +1,5 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import * as Chunk from "effect/Chunk" import * as Clock from "effect/Clock" @@ -9,7 +10,6 @@ import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" import { constVoid } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import * as Schedule from "effect/Schedule" import * as ScheduleDecision from "effect/ScheduleDecision" @@ -21,7 +21,7 @@ describe("Schedule", () => { it.effect("collect all inputs into a list as long as the condition f holds", () => Effect.gen(function*($) { const result = yield* $(repeat(Schedule.collectWhile((n) => n < 10))) - assert.deepStrictEqual(Array.from(result), ReadonlyArray.range(1, 9)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 9)) })) it.effect("collect all inputs into a list as long as the effectful condition f holds", () => Effect.gen(function*($) { @@ -31,12 +31,12 @@ describe("Schedule", () => { it.effect("collect all inputs into a list until the effectful condition f fails", () => Effect.gen(function*($) { const result = yield* $(repeat(Schedule.collectUntil((n) => n < 10 && n > 1))) - assert.deepStrictEqual(Array.from(result), [1]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [1]) })) it.effect("collect all inputs into a list until the effectful condition f fails", () => Effect.gen(function*($) { const result = yield* $(repeat(Schedule.collectUntilEffect((n) => Effect.succeed(n > 10)))) - assert.deepStrictEqual(Array.from(result), ReadonlyArray.range(1, 10)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 10)) })) it.effect("union composes", () => Effect.gen(function*($) { @@ -47,10 +47,10 @@ describe("Schedule", () => { const wednesdayOrFriday = wednesday.pipe(Schedule.union(friday)) const alsoWednesday = mondayOrWednesday.pipe(Schedule.intersect(wednesdayOrFriday)) const now = yield* $(Effect.sync(() => Date.now())) - const input = ReadonlyArray.range(1, 5) + const input = Array.range(1, 5) const actual = yield* $(alsoWednesday, Schedule.delays, Schedule.run(now, input)) const expected = yield* $(wednesday, Schedule.delays, Schedule.run(now, input)) - assert.deepStrictEqual(Array.from(actual), Array.from(expected)) + assert.deepStrictEqual(Chunk.toReadonlyArray(actual), Chunk.toReadonlyArray(expected)) })) it.effect("either should not wait if neither schedule wants to continue", () => Effect.gen(function*($) { @@ -58,9 +58,9 @@ describe("Schedule", () => { Schedule.union(Schedule.spaced("2 seconds").pipe(Schedule.intersect(Schedule.stop))), Schedule.compose(Schedule.elapsed) ) - const input = Array.from({ length: 4 }, constVoid) + const input = Array.makeBy(4, constVoid) const result = yield* $(runCollect(schedule, input)) - assert.deepStrictEqual(Array.from(result), [Duration.zero]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [Duration.zero]) })) it.effect("perform log for each recurrence of effect", () => Effect.gen(function*($) { @@ -107,7 +107,7 @@ describe("Schedule", () => { const input = Chunk.make(true, false, false, false, false) const result = yield* $(runCollect(schedule.pipe(Schedule.compose(Schedule.elapsed)), input)) const expected = [0, 0, 1, 2, 3].map(Duration.seconds) - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("Schedule.fixed should compute delays correctly", () => Effect.gen(function*($) { @@ -122,9 +122,11 @@ describe("Schedule", () => { Effect.gen(function*($) { const schedule = Schedule.hourOfDay(4).pipe(Schedule.intersect(Schedule.minuteOfHour(20))) const now = yield* $(Effect.sync(() => Date.now())) - const input = ReadonlyArray.range(1, 5) + const input = Array.range(1, 5) const delays = yield* $(Schedule.delays(schedule), Schedule.run(now, input)) - const actual = Array.from(scanLeft(delays, now, (now, delay) => now + Duration.toMillis(delay))).slice(1) + const actual = Chunk.toReadonlyArray(scanLeft(delays, now, (now, delay) => now + Duration.toMillis(delay))).slice( + 1 + ) assert.isTrue(actual.map((n) => new Date(n).getHours()).every((n) => n === 4)) assert.isTrue(actual.map((n) => new Date(n).getMinutes()).every((n) => n === 20)) })) @@ -142,9 +144,9 @@ describe("Schedule", () => { const schedule = Schedule.exponential("1 minutes") const result = yield* $( Clock.currentTimeMillis, - Effect.flatMap((now) => schedule.pipe(Schedule.run(now, Array.from({ length: 5 }, constVoid)))) + Effect.flatMap((now) => schedule.pipe(Schedule.run(now, Array.makeBy(5, constVoid)))) ) - assert.deepStrictEqual(Array.from(result), [ + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [ Duration.minutes(1), Duration.minutes(2), Duration.minutes(4), @@ -157,10 +159,10 @@ describe("Schedule", () => { const schedule = Schedule.recurs(2).pipe(Schedule.intersect(Schedule.exponential("1 minutes"))) const result = yield* $( Clock.currentTimeMillis.pipe( - Effect.flatMap((now) => schedule.pipe(Schedule.run(now, ReadonlyArray.range(1, 10)))) + Effect.flatMap((now) => schedule.pipe(Schedule.run(now, Array.range(1, 10)))) ) ) - assert.deepStrictEqual(Array.from(result), [ + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [ [0, Duration.minutes(1)], [1, Duration.minutes(2)], [2, Duration.minutes(4)] @@ -171,10 +173,10 @@ describe("Schedule", () => { const schedule = Schedule.spaced("1 seconds").pipe(Schedule.upTo("5 seconds")) const result = yield* $( Clock.currentTimeMillis.pipe( - Effect.flatMap((now) => schedule.pipe(Schedule.run(now, ReadonlyArray.range(1, 10)))) + Effect.flatMap((now) => schedule.pipe(Schedule.run(now, Array.range(1, 10)))) ) ) - assert.deepStrictEqual(Array.from(result), [0, 1, 2, 3, 4, 5]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [0, 1, 2, 3, 4, 5]) })) }) describe("repeat an action a single time", () => { @@ -478,44 +480,44 @@ describe("Schedule", () => { it.effect("fibonacci delay", () => Effect.gen(function*($) { const schedule = Schedule.fibonacci("100 millis").pipe(Schedule.compose(Schedule.elapsed)) - const result = yield* $(runCollect(schedule, Array.from({ length: 5 }, constVoid))) + const result = yield* $(runCollect(schedule, Array.makeBy(5, constVoid))) const expected = [0, 100, 200, 400, 700].map(Duration.millis) - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("linear delay", () => Effect.gen(function*($) { const schedule = Schedule.linear("100 millis").pipe(Schedule.compose(Schedule.elapsed)) - const result = yield* $(runCollect(schedule, Array.from({ length: 5 }, constVoid))) + const result = yield* $(runCollect(schedule, Array.makeBy(5, constVoid))) const expected = [0, 100, 300, 600, 1000].map(Duration.millis) - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("spaced delay", () => Effect.gen(function*($) { const schedule = Schedule.spaced("100 millis").pipe(Schedule.compose(Schedule.elapsed)) - const result = yield* $(runCollect(schedule, Array.from({ length: 5 }, constVoid))) + const result = yield* $(runCollect(schedule, Array.makeBy(5, constVoid))) const expected = [0, 100, 200, 300, 400].map(Duration.millis) - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("fixed delay", () => Effect.gen(function*($) { const schedule = Schedule.fixed("100 millis").pipe(Schedule.compose(Schedule.elapsed)) - const result = yield* $(runCollect(schedule, Array.from({ length: 5 }, constVoid))) + const result = yield* $(runCollect(schedule, Array.makeBy(5, constVoid))) const expected = [0, 100, 200, 300, 400].map(Duration.millis) - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("fixed delay with zero delay", () => Effect.gen(function*($) { const schedule = Schedule.fixed(Duration.zero).pipe(Schedule.compose(Schedule.elapsed)) - const result = yield* $(runCollect(schedule, Array.from({ length: 5 }, constVoid))) - const expected = Array.from({ length: 5 }, () => Duration.zero) - assert.deepStrictEqual(Array.from(result), expected) + const result = yield* $(runCollect(schedule, Array.makeBy(5, constVoid))) + const expected = Array.makeBy(5, () => Duration.zero) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("windowed", () => Effect.gen(function*($) { const schedule = Schedule.windowed("100 millis").pipe(Schedule.compose(Schedule.elapsed)) - const result = yield* $(runCollect(schedule, Array.from({ length: 5 }, constVoid))) + const result = yield* $(runCollect(schedule, Array.makeBy(5, constVoid))) const expected = [0, 100, 200, 300, 400].map(Duration.millis) - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("modified linear delay", () => Effect.gen(function*($) { @@ -523,23 +525,23 @@ describe("Schedule", () => { Schedule.modifyDelayEffect((_, duration) => Effect.succeed(duration.pipe(Duration.times(2)))), Schedule.compose(Schedule.elapsed) ) - const result = yield* $(runCollect(schedule, Array.from({ length: 5 }, constVoid))) + const result = yield* $(runCollect(schedule, Array.makeBy(5, constVoid))) const expected = [0, 200, 600, 1200, 2000].map(Duration.millis) - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("exponential delay with default factor", () => Effect.gen(function*($) { const schedule = Schedule.exponential("100 millis").pipe(Schedule.compose(Schedule.elapsed)) - const result = yield* $(runCollect(schedule, Array.from({ length: 5 }, constVoid))) + const result = yield* $(runCollect(schedule, Array.makeBy(5, constVoid))) const expected = [0, 100, 300, 700, 1500].map(Duration.millis) - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("exponential delay with other factor", () => Effect.gen(function*($) { const schedule = Schedule.exponential("100 millis", 3).pipe(Schedule.compose(Schedule.elapsed)) - const result = yield* $(runCollect(schedule, Array.from({ length: 5 }, constVoid))) + const result = yield* $(runCollect(schedule, Array.makeBy(5, constVoid))) const expected = [0, 100, 400, 1300, 4000].map(Duration.millis) - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("fromDelays", () => Effect.gen(function*($) { @@ -550,9 +552,9 @@ describe("Schedule", () => { "19 seconds" ) const schedule = delays.pipe(Schedule.compose(Schedule.elapsed)) - const result = yield* $(runCollect(schedule, Array.from({ length: 5 }, constVoid))) + const result = yield* $(runCollect(schedule, Array.makeBy(5, constVoid))) const expected = [0, 4, 11, 23, 42].map(Duration.seconds) - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), expected) })) it.effect("retry a failed action 2 times and call `ensuring` should run the specified finalizer as soon as the schedule is complete", () => Effect.gen(function*($) { @@ -578,7 +580,7 @@ describe("Schedule", () => { const schedule = Schedule.cron("30 4 5,15 * WED") yield* $( TestClock.currentTimeMillis, - Effect.tap((instant) => Ref.update(ref, ReadonlyArray.append(format(instant)))), + Effect.tap((instant) => Ref.update(ref, Array.append(format(instant)))), Effect.repeat(schedule), Effect.fork ) @@ -728,7 +730,7 @@ describe("Schedule", () => { yield* $(TestClock.adjust("2 minutes")) const result = yield* $(Ref.get(ref)) const expected = [5, 25, 30, 50, 70, 90, 110] - assert.deepStrictEqual(Array.from(result), expected) + assert.deepStrictEqual(result, expected) })) it.effect("throw IllegalArgumentException on invalid `second` argument of `secondOfMinute`", () => Effect.gen(function*($) { @@ -819,7 +821,7 @@ const checkDelays = ( > => { return Effect.gen(function*($) { const now = yield* $(Effect.sync(() => Date.now())) - const input = ReadonlyArray.range(1, 5) + const input = Array.range(1, 5) const actual = yield* $(schedule, Schedule.run(now, input)) const expected = yield* $(Schedule.delays(schedule), Schedule.run(now, input)) return [actual, expected] as const @@ -835,7 +837,7 @@ const checkRepetitions = (schedule: Schedule.Schedule) > => { return Effect.gen(function*($) { const now = yield* $(Effect.sync(() => Date.now())) - const input = ReadonlyArray.range(1, 5) + const input = Array.range(1, 5) const actual = yield* $(schedule, Schedule.run(now, input)) const expected = yield* $(Schedule.repetitions(schedule), Schedule.run(now, input)) return [actual, expected] as const @@ -955,7 +957,7 @@ const runManuallyLoop = ( // TODO(Mike/Max): remove if added to `effect` const scanLeft = (self: Chunk.Chunk, b: B, f: (b: B, a: A) => B): Chunk.Chunk => { const len = self.length - const out = new Array(len + 1) + const out = Array.allocate(len + 1) as Array out[0] = b for (let i = 0; i < len; i++) { out[i + 1] = f(out[i], self.pipe(Chunk.unsafeGet(i))) diff --git a/packages/effect/test/ScopedCache.test.ts b/packages/effect/test/ScopedCache.test.ts index a6e3cd7db6..0a79586887 100644 --- a/packages/effect/test/ScopedCache.test.ts +++ b/packages/effect/test/ScopedCache.test.ts @@ -1,6 +1,7 @@ import * as ObservableResource from "effect-test/utils/cache/ObservableResource" import * as WatchableLookup from "effect-test/utils/cache/WatchableLookup" import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import * as Chunk from "effect/Chunk" import * as Context from "effect/Context" @@ -12,7 +13,6 @@ import * as Fiber from "effect/Fiber" import { dual, identity, pipe } from "effect/Function" import * as Hash from "effect/Hash" import * as HashMap from "effect/HashMap" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import * as Schedule from "effect/Schedule" import * as Scope from "effect/Scope" @@ -48,7 +48,7 @@ describe("ScopedCache", () => { Effect.flatMap((cache) => pipe( Effect.forEach( - ReadonlyArray.map(ReadonlyArray.range(1, capacity), (n) => (n / 2) | 0), + Array.map(Array.range(1, capacity), (n) => (n / 2) | 0), (n) => Effect.scoped(Effect.zipRight(cache.get(n), Effect.void)), { concurrency: "unbounded", discard: true } ), @@ -69,7 +69,7 @@ describe("ScopedCache", () => { const capacity = 100 const observablesResources = yield* $( Effect.forEach( - ReadonlyArray.range(0, capacity - 1), + Array.range(0, capacity - 1), () => ObservableResource.makeVoid() ) ) @@ -81,7 +81,7 @@ describe("ScopedCache", () => { yield* $(Effect.scoped(Effect.gen(function*($) { const cache = yield* $(scopedCache) yield* $(Effect.forEach( - ReadonlyArray.range(0, capacity - 1), + Array.range(0, capacity - 1), (n) => Effect.scoped(Effect.zipRight(cache.get(n), Effect.void)), { concurrency: "unbounded", discard: true } )) @@ -92,7 +92,7 @@ describe("ScopedCache", () => { yield* $(Effect.forEach( pipe( observablesResources, - ReadonlyArray.filter((_, index) => index !== 42) + Array.filter((_, index) => index !== 42) ), (observableResource) => observableResource.assertAcquiredOnceAndNotCleaned() )) @@ -131,7 +131,7 @@ describe("ScopedCache", () => { const capacity = 100 const observablesResources = yield* $( Effect.forEach( - ReadonlyArray.range(0, capacity - 1), + Array.range(0, capacity - 1), () => ObservableResource.makeVoid() ) ) @@ -143,14 +143,14 @@ describe("ScopedCache", () => { yield* $(Effect.scoped(Effect.gen(function*($) { const cache = yield* $(scopedCache) yield* $(Effect.forEach( - ReadonlyArray.range(0, capacity - 1), + Array.range(0, capacity - 1), (n) => Effect.scoped(Effect.zipRight(cache.get(n), Effect.void)), { concurrency: "unbounded", discard: true } )) yield* $(cache.invalidateAll) const contains = yield* $( Effect.forEach( - ReadonlyArray.range(0, capacity - 1), + Array.range(0, capacity - 1), (n) => Effect.scoped(cache.contains(n)), { concurrency: "unbounded" } ), @@ -199,11 +199,11 @@ describe("ScopedCache", () => { const cache = yield* $(scopedCache) const actual = yield* $( Effect.forEach( - ReadonlyArray.range(1, 10), + Array.range(1, 10), (n) => Effect.scoped(Effect.flatMap(cache.get(n), Effect.succeed)) ) ) - const expected = ReadonlyArray.map(ReadonlyArray.range(1, 10), hash(salt)) + const expected = Array.map(Array.range(1, 10), hash(salt)) expect(actual).toEqual(expected) }))) }) @@ -222,13 +222,13 @@ describe("ScopedCache", () => { const cache = yield* $(scopedCache) const actual = yield* $( Effect.forEach( - ReadonlyArray.range(1, 10), + Array.range(1, 10), (n) => Effect.scoped(Effect.flatMap(cache.get(n), Effect.succeed)), { concurrency: "unbounded" } ) ) - const expected = ReadonlyArray.map(ReadonlyArray.range(1, 10), hash(salt)) - expect(Array.from(actual)).toEqual(Array.from(expected)) + const expected = Array.map(Array.range(1, 10), hash(salt)) + expect(actual).toEqual(expected) }))) }) return Effect.runPromise(program) @@ -246,13 +246,13 @@ describe("ScopedCache", () => { const cache = yield* $(scopedCache) const actual = yield* $( Effect.forEach( - ReadonlyArray.range(1, 10), + Array.range(1, 10), (n) => Effect.scoped(Effect.flatMap(cache.get(n), Effect.succeed)) ) ) - const expected = ReadonlyArray.map(ReadonlyArray.range(1, 10), hash(salt)) + const expected = Array.map(Array.range(1, 10), hash(salt)) const cacheStats = yield* $(cache.cacheStats) - expect(Array.from(actual)).toEqual(Array.from(expected)) + expect(actual).toEqual(expected) expect(cacheStats.size).toBe(5) }))) }) @@ -453,7 +453,7 @@ describe("ScopedCache", () => { const cache = yield* $(scopedCache) yield* $( Effect.forEach( - ReadonlyArray.range(0, numCreatedKey - 1), + Array.range(0, numCreatedKey - 1), (key) => Effect.scoped(Effect.asVoid(cache.get(key))), { discard: true } ) @@ -461,17 +461,17 @@ describe("ScopedCache", () => { const createdResources = yield* $(watchableLookup.createdResources()) const cleanedAssertions = numCreatedKey - cacheSize - 1 const oldestResourceCleaned = cleanedAssertions <= 0 - ? ReadonlyArray.empty() + ? Array.empty() : pipe( - ReadonlyArray.range(0, numCreatedKey - cacheSize - 1), - ReadonlyArray.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))), - ReadonlyArray.map((resource) => resource.assertAcquiredOnceAndCleaned()) + Array.range(0, numCreatedKey - cacheSize - 1), + Array.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))), + Array.map((resource) => resource.assertAcquiredOnceAndCleaned()) ) yield* $(Effect.all(oldestResourceCleaned, { discard: true })) const newestResourceNotCleanedYet = pipe( - ReadonlyArray.range(numCreatedKey - cacheSize, numCreatedKey - 1), - ReadonlyArray.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))), - ReadonlyArray.map((resource) => resource.assertAcquiredOnceAndNotCleaned()) + Array.range(numCreatedKey - cacheSize, numCreatedKey - 1), + Array.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))), + Array.map((resource) => resource.assertAcquiredOnceAndNotCleaned()) ) yield* $(Effect.all(newestResourceNotCleanedYet, { discard: true })) }))) @@ -701,7 +701,7 @@ describe("ScopedCache", () => { yield* $(Effect.scoped(Effect.gen(function*($) { const cache = yield* $(scopedCache) const count0 = yield* $(cache.size) - yield* $(Effect.forEach(ReadonlyArray.range(1, capacity), (key) => cache.refresh(key), { discard: true })) + yield* $(Effect.forEach(Array.range(1, capacity), (key) => cache.refresh(key), { discard: true })) const count1 = yield* $(cache.size) expect(count0).toBe(0) expect(count1).toBe(capacity) @@ -724,24 +724,24 @@ describe("ScopedCache", () => { yield* $(Effect.scoped(Effect.gen(function*($) { const cache = yield* $(scopedCache) yield* $(Effect.forEach( - ReadonlyArray.range(0, numCreatedKey - 1), + Array.range(0, numCreatedKey - 1), (key) => cache.refresh(key), { discard: true } )) const createdResources = yield* $(watchableLookup.createdResources()) const cleanedAssertions = numCreatedKey - cacheSize - 1 const oldestResourceCleaned = cleanedAssertions <= 0 - ? ReadonlyArray.empty() + ? Array.empty() : pipe( - ReadonlyArray.range(0, numCreatedKey - cacheSize - 1), - ReadonlyArray.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))), - ReadonlyArray.map((resource) => resource.assertAcquiredOnceAndCleaned()) + Array.range(0, numCreatedKey - cacheSize - 1), + Array.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))), + Array.map((resource) => resource.assertAcquiredOnceAndCleaned()) ) yield* $(Effect.all(oldestResourceCleaned, { discard: true })) const newestResourceNotCleanedYet = pipe( - ReadonlyArray.range(numCreatedKey - cacheSize, numCreatedKey - 1), - ReadonlyArray.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))), - ReadonlyArray.map((resource) => resource.assertAcquiredOnceAndNotCleaned()) + Array.range(numCreatedKey - cacheSize, numCreatedKey - 1), + Array.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))), + Array.map((resource) => resource.assertAcquiredOnceAndNotCleaned()) ) yield* $(Effect.all(newestResourceNotCleanedYet, { discard: true })) }))) diff --git a/packages/effect/test/Stream/environment.test.ts b/packages/effect/test/Stream/environment.test.ts index 3691919cce..245401ecbd 100644 --- a/packages/effect/test/Stream/environment.test.ts +++ b/packages/effect/test/Stream/environment.test.ts @@ -1,11 +1,11 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Chunk from "effect/Chunk" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import { pipe } from "effect/Function" import * as Layer from "effect/Layer" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Stream from "effect/Stream" import type * as Tracer from "effect/Tracer" import { assert, describe, expect } from "vitest" @@ -29,7 +29,7 @@ describe("Stream", () => { Stream.provideContext(context), Stream.runCollect ) - assert.deepStrictEqual(Array.from(result), [{ string: "test" }]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [{ string: "test" }]) })) it.effect("contextWith", () => @@ -126,7 +126,7 @@ describe("Stream", () => { Stream.map((s) => s.string), Stream.runCollect ) - assert.deepStrictEqual(Array.from(result), ["test"]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), ["test"]) })) it.effect("provideServiceStream", () => @@ -139,7 +139,7 @@ describe("Stream", () => { Stream.map((s) => s.string), Stream.runCollect ) - assert.deepStrictEqual(Array.from(result), ["test"]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), ["test"]) })) it.effect("serviceWith", () => @@ -149,7 +149,7 @@ describe("Stream", () => { Stream.provideLayer(Layer.succeed(StringService, { string: "test" })), Stream.runCollect ) - assert.deepStrictEqual(Array.from(result), ["test"]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), ["test"]) })) it.effect("serviceWithEffect", () => @@ -159,7 +159,7 @@ describe("Stream", () => { Stream.provideLayer(Layer.succeed(StringService, { string: "test" })), Stream.runCollect ) - assert.deepStrictEqual(Array.from(result), ["test"]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), ["test"]) })) it.effect("serviceWithStream", () => @@ -169,7 +169,7 @@ describe("Stream", () => { Stream.provideLayer(Layer.succeed(StringService, { string: "test" })), Stream.runCollect ) - assert.deepStrictEqual(Array.from(result), ["test"]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), ["test"]) })) it.effect("deep provide", () => @@ -208,11 +208,11 @@ describe("Stream", () => { ) expect(spans.length).toEqual(3) expect(pipe( - ReadonlyArray.map(spans, (s) => s.parent), - ReadonlyArray.getSomes, - ReadonlyArray.filter((s): s is Tracer.Span => s._tag === "Span"), - ReadonlyArray.map((s) => s.name) + Array.map(spans, (s) => s.parent), + Array.getSomes, + Array.filter((s): s is Tracer.Span => s._tag === "Span"), + Array.map((s) => s.name) )).toEqual(["span", "span", "span"]) - expect(ReadonlyArray.map(spans, (s) => s.name)).toEqual(["span.1", "span.2", "span.3"]) + expect(Array.map(spans, (s) => s.name)).toEqual(["span.1", "span.2", "span.3"]) })) }) diff --git a/packages/effect/test/Stream/scanning.test.ts b/packages/effect/test/Stream/scanning.test.ts index 0d2bef0f22..3bbbce9c9b 100644 --- a/packages/effect/test/Stream/scanning.test.ts +++ b/packages/effect/test/Stream/scanning.test.ts @@ -1,8 +1,8 @@ import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Chunk from "effect/Chunk" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Stream from "effect/Stream" import { assert, describe } from "vitest" @@ -17,12 +17,12 @@ describe("Stream", () => { Effect.map((chunk) => pipe( Chunk.toReadonlyArray(chunk), - ReadonlyArray.scan(0, (acc, curr) => acc + curr) + Array.scan(0, (acc, curr) => acc + curr) ) ) ) })) - assert.deepStrictEqual(Array.from(result1), Array.from(result2)) + assert.deepStrictEqual(Chunk.toReadonlyArray(result1), result2) })) it.effect("scanReduce", () => @@ -33,6 +33,6 @@ describe("Stream", () => { Stream.scanReduce((acc, curr) => acc + curr), Stream.runCollect ) - assert.deepStrictEqual(Array.from(result), [1, 3, 6, 10, 15]) + assert.deepStrictEqual(Chunk.toReadonlyArray(result), [1, 3, 6, 10, 15]) })) }) diff --git a/packages/effect/test/TMap.test.ts b/packages/effect/test/TMap.test.ts index 9e680b6f40..8fd8daec7a 100644 --- a/packages/effect/test/TMap.test.ts +++ b/packages/effect/test/TMap.test.ts @@ -1,5 +1,6 @@ import { equivalentElements } from "effect-test/utils/equals" import * as it from "effect-test/utils/extend" +import * as Array from "effect/Array" import * as Chunk from "effect/Chunk" import * as Effect from "effect/Effect" import * as Equal from "effect/Equal" @@ -7,7 +8,6 @@ import * as Exit from "effect/Exit" import { pipe } from "effect/Function" import * as Hash from "effect/Hash" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as STM from "effect/STM" import * as TMap from "effect/TMap" import * as fc from "fast-check" @@ -26,7 +26,7 @@ class HashContainer implements Equal.Equal { const mapEntriesArb: fc.Arbitrary> = fc.uniqueArray(fc.char()) .chain((keys) => fc.uniqueArray(fc.integer()) - .map((values) => pipe(keys, ReadonlyArray.zip(values))) + .map((values) => pipe(keys, Array.zip(values))) ) describe("TMap", () => { @@ -118,8 +118,8 @@ describe("TMap", () => { ) const result = await Effect.runPromise(STM.commit(transaction)) const keys = entries.map((entry) => entry[0]) - assert.lengthOf(pipe(result, ReadonlyArray.differenceWith(equivalentElements())(keys)), 0) - assert.lengthOf(pipe(keys, ReadonlyArray.differenceWith(equivalentElements())(result)), 0) + assert.lengthOf(pipe(result, Array.differenceWith(equivalentElements())(keys)), 0) + assert.lengthOf(pipe(keys, Array.differenceWith(equivalentElements())(result)), 0) }))) it.effect("merge", () => @@ -208,7 +208,7 @@ describe("TMap", () => { const a = yield* $(pipe(map, TMap.has("a"))) const aa = yield* $(pipe(map, TMap.has("aa"))) const aaa = yield* $(pipe(map, TMap.has("aaa"))) - return [Array.from(removed), a, aa, aaa] as const + return [removed, a, aa, aaa] as const }) const result = yield* $(STM.commit(transaction)) assert.deepStrictEqual(result, [[["aaa", 3], ["aa", 2]], true, false, false]) @@ -236,7 +236,7 @@ describe("TMap", () => { const a = yield* $(pipe(map, TMap.has("a"))) const aa = yield* $(pipe(map, TMap.has("aa"))) const aaa = yield* $(pipe(map, TMap.has("aaa"))) - return [Array.from(removed), a, aa, aaa] as const + return [removed, a, aa, aaa] as const }) const result = yield* $(STM.commit(transaction)) assert.deepStrictEqual(result, [[["aaa", 3], ["a", 1]], false, true, false]) @@ -280,7 +280,7 @@ describe("TMap", () => { it.effect("set - add many keys with negative hash codes", () => Effect.gen(function*($) { - const entries = Array.from({ length: 1_000 }, (_, i) => i + 1) + const entries = Array.makeBy(1_000, (i) => i + 1) .map((i) => [new HashContainer(i), i] as const) const transaction = pipe( TMap.empty(), @@ -288,8 +288,8 @@ describe("TMap", () => { STM.flatMap(TMap.toArray) ) const result = yield* $(STM.commit(transaction)) - assert.lengthOf(pipe(result, ReadonlyArray.differenceWith(equivalentElements())(entries)), 0) - assert.lengthOf(pipe(entries, ReadonlyArray.differenceWith(equivalentElements())(result)), 0) + assert.lengthOf(pipe(result, Array.differenceWith(equivalentElements())(entries)), 0) + assert.lengthOf(pipe(entries, Array.differenceWith(equivalentElements())(result)), 0) })) it.effect("setIfAbsent", () => @@ -302,8 +302,8 @@ describe("TMap", () => { ) const result = yield* $(STM.commit(transaction)) const expected = [["a", 1], ["b", 2]] - assert.lengthOf(pipe(result, ReadonlyArray.differenceWith(equivalentElements())(expected)), 0) - assert.lengthOf(pipe(expected, ReadonlyArray.differenceWith(equivalentElements())(result)), 0) + assert.lengthOf(pipe(result, Array.differenceWith(equivalentElements())(expected)), 0) + assert.lengthOf(pipe(expected, Array.differenceWith(equivalentElements())(result)), 0) })) it.effect("size", () => @@ -324,8 +324,8 @@ describe("TMap", () => { ) const result = await Effect.runPromise(STM.commit(transaction)) expect(Chunk.isChunk(result)).toBe(true) - assert.lengthOf(pipe(Array.from(result), ReadonlyArray.differenceWith(equivalentElements())(entries)), 0) - assert.lengthOf(pipe(entries, ReadonlyArray.differenceWith(equivalentElements())(Array.from(result))), 0) + assert.lengthOf(pipe(Chunk.toReadonlyArray(result), Array.differenceWith(equivalentElements())(entries)), 0) + assert.lengthOf(pipe(entries, Array.differenceWith(equivalentElements())(Chunk.toReadonlyArray(result))), 0) }))) it.it("toReadonlyArray - collect all elements", () => @@ -335,8 +335,8 @@ describe("TMap", () => { STM.flatMap(TMap.toArray) ) const result = await Effect.runPromise(STM.commit(transaction)) - assert.lengthOf(pipe(result, ReadonlyArray.differenceWith(equivalentElements())(entries)), 0) - assert.lengthOf(pipe(entries, ReadonlyArray.differenceWith(equivalentElements())(result)), 0) + assert.lengthOf(pipe(result, Array.differenceWith(equivalentElements())(entries)), 0) + assert.lengthOf(pipe(entries, Array.differenceWith(equivalentElements())(result)), 0) }))) it.it("toMap - collect all elements", () => @@ -346,8 +346,8 @@ describe("TMap", () => { STM.flatMap(TMap.toMap) ) const result = await Effect.runPromise(STM.commit(transaction)) - assert.lengthOf(pipe(Array.from(result), ReadonlyArray.differenceWith(equivalentElements())(entries)), 0) - assert.lengthOf(pipe(entries, ReadonlyArray.differenceWith(equivalentElements())(Array.from(result))), 0) + assert.lengthOf(pipe(Array.fromIterable(result), Array.differenceWith(equivalentElements())(entries)), 0) + assert.lengthOf(pipe(entries, Array.differenceWith(equivalentElements())(Array.fromIterable(result))), 0) }))) it.effect("transform", () => @@ -359,8 +359,8 @@ describe("TMap", () => { ) const result = yield* $(STM.commit(transaction)) const expected = [["b", 2], ["bb", 4], ["bbb", 6]] - assert.lengthOf(pipe(result, ReadonlyArray.differenceWith(equivalentElements())(expected)), 0) - assert.lengthOf(pipe(expected, ReadonlyArray.differenceWith(equivalentElements())(result)), 0) + assert.lengthOf(pipe(result, Array.differenceWith(equivalentElements())(expected)), 0) + assert.lengthOf(pipe(expected, Array.differenceWith(equivalentElements())(result)), 0) })) it.effect("transform - handles keys with negative hash codes", () => @@ -372,8 +372,8 @@ describe("TMap", () => { ) const result = yield* $(STM.commit(transaction)) const expected = [[new HashContainer(2), 2], [new HashContainer(4), 4], [new HashContainer(6), 6]] - assert.lengthOf(pipe(result, ReadonlyArray.differenceWith(equivalentElements())(expected)), 0) - assert.lengthOf(pipe(expected, ReadonlyArray.differenceWith(equivalentElements())(result)), 0) + assert.lengthOf(pipe(result, Array.differenceWith(equivalentElements())(expected)), 0) + assert.lengthOf(pipe(expected, Array.differenceWith(equivalentElements())(result)), 0) })) it.effect("transform - and shrink", () => @@ -396,8 +396,8 @@ describe("TMap", () => { ) const result = yield* $(STM.commit(transaction)) const expected = [["b", 2], ["bb", 4], ["bbb", 6]] - assert.lengthOf(pipe(result, ReadonlyArray.differenceWith(equivalentElements())(expected)), 0) - assert.lengthOf(pipe(expected, ReadonlyArray.differenceWith(equivalentElements())(result)), 0) + assert.lengthOf(pipe(result, Array.differenceWith(equivalentElements())(expected)), 0) + assert.lengthOf(pipe(expected, Array.differenceWith(equivalentElements())(result)), 0) })) it.effect("transformSTM - and shrink", () => @@ -420,8 +420,8 @@ describe("TMap", () => { ) const result = yield* $(STM.commit(transaction)) const expected = [["a", 2], ["aa", 4], ["aaa", 6]] - assert.lengthOf(pipe(result, ReadonlyArray.differenceWith(equivalentElements())(expected)), 0) - assert.lengthOf(pipe(expected, ReadonlyArray.differenceWith(equivalentElements())(result)), 0) + assert.lengthOf(pipe(result, Array.differenceWith(equivalentElements())(expected)), 0) + assert.lengthOf(pipe(expected, Array.differenceWith(equivalentElements())(result)), 0) })) it.effect("transformValues - parallel", () => @@ -433,10 +433,7 @@ describe("TMap", () => { STM.commit, Effect.repeatN(999) ) - yield* $(Effect.all(Array.from({ length: 2 }, () => effect), { - concurrency: "unbounded", - discard: true - })) + yield* $(Effect.replicateEffect(effect, 2)) const result = yield* $(pipe(map, TMap.get("a"))) assert.deepStrictEqual(result, Option.some(2_000)) })) @@ -450,8 +447,8 @@ describe("TMap", () => { ) const result = yield* $(STM.commit(transaction)) const expected = [["a", 2], ["aa", 4], ["aaa", 6]] - assert.lengthOf(pipe(result, ReadonlyArray.differenceWith(equivalentElements())(expected)), 0) - assert.lengthOf(pipe(expected, ReadonlyArray.differenceWith(equivalentElements())(result)), 0) + assert.lengthOf(pipe(result, Array.differenceWith(equivalentElements())(expected)), 0) + assert.lengthOf(pipe(expected, Array.differenceWith(equivalentElements())(result)), 0) })) it.effect("updateWith", () => @@ -476,14 +473,14 @@ describe("TMap", () => { ) const result = await Effect.runPromise(STM.commit(transaction)) const values = entries.map((entry) => entry[1]) - assert.lengthOf(pipe(Array.from(result), ReadonlyArray.differenceWith(equivalentElements())(values)), 0) - assert.lengthOf(pipe(values, ReadonlyArray.differenceWith(equivalentElements())(result)), 0) + assert.lengthOf(pipe(result, Array.differenceWith(equivalentElements())(values)), 0) + assert.lengthOf(pipe(values, Array.differenceWith(equivalentElements())(result)), 0) }))) it.effect("avoid issues due to race conditions (ZIO Issue #4648)", () => Effect.gen(function*($) { - const keys = ReadonlyArray.range(0, 10) - const map = yield* $(TMap.fromIterable(ReadonlyArray.map(keys, (n, i) => [n, i]))) + const keys = Array.range(0, 10) + const map = yield* $(TMap.fromIterable(Array.map(keys, (n, i) => [n, i]))) const result = yield* $(pipe( Effect.forEach(keys, (key) => pipe( diff --git a/packages/effect/test/TPriorityQueue.test.ts b/packages/effect/test/TPriorityQueue.test.ts index aaca3f7d12..22a3c60537 100644 --- a/packages/effect/test/TPriorityQueue.test.ts +++ b/packages/effect/test/TPriorityQueue.test.ts @@ -1,11 +1,11 @@ import { equivalentElements } from "effect-test/utils/equals" import * as it from "effect-test/utils/extend" +import * as RA from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as number from "effect/Number" import * as Option from "effect/Option" import * as Order from "effect/Order" -import * as RA from "effect/ReadonlyArray" import * as STM from "effect/STM" import * as TPriorityQueue from "effect/TPriorityQueue" import * as fc from "fast-check" diff --git a/packages/effect/test/TPubSub.test.ts b/packages/effect/test/TPubSub.test.ts index a2e36460c7..e4bd8ef7ec 100644 --- a/packages/effect/test/TPubSub.test.ts +++ b/packages/effect/test/TPubSub.test.ts @@ -1,10 +1,10 @@ import * as it from "effect-test/utils/extend" +import * as RA from "effect/Array" import * as Deferred from "effect/Deferred" import * as Effect from "effect/Effect" import * as Fiber from "effect/Fiber" import { pipe } from "effect/Function" import * as number from "effect/Number" -import * as RA from "effect/ReadonlyArray" import * as STM from "effect/STM" import * as TPubSub from "effect/TPubSub" import * as TQueue from "effect/TQueue" diff --git a/packages/experimental/examples/redis/resolver.ts b/packages/experimental/examples/redis/resolver.ts index b8bfc911f9..bfee55a140 100644 --- a/packages/experimental/examples/redis/resolver.ts +++ b/packages/experimental/examples/redis/resolver.ts @@ -3,7 +3,7 @@ import { persisted } from "@effect/experimental/RequestResolver" import * as TimeToLive from "@effect/experimental/TimeToLive" import { runMain } from "@effect/platform-node/NodeRuntime" import { Schema } from "@effect/schema" -import { Effect, Exit, PrimaryKey, ReadonlyArray, RequestResolver } from "effect" +import { Array, Effect, Exit, PrimaryKey, RequestResolver } from "effect" class User extends Schema.Class("User")({ id: Schema.Number, @@ -33,7 +33,7 @@ Effect.gen(function*(_) { ) const users = yield* _( - Effect.forEach(ReadonlyArray.range(1, 5), (id) => Effect.request(new GetUserById({ id }), resolver), { + Effect.forEach(Array.range(1, 5), (id) => Effect.request(new GetUserById({ id }), resolver), { batching: true }) ) diff --git a/packages/experimental/src/Machine.ts b/packages/experimental/src/Machine.ts index f09dad13bc..39c190f6d2 100644 --- a/packages/experimental/src/Machine.ts +++ b/packages/experimental/src/Machine.ts @@ -4,6 +4,7 @@ import type * as ParseResult from "@effect/schema/ParseResult" import * as Schema from "@effect/schema/Schema" import * as Serializable from "@effect/schema/Serializable" +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import * as Context from "effect/Context" import * as Deferred from "effect/Deferred" @@ -21,7 +22,6 @@ import { pipeArguments } from "effect/Pipeable" import * as PubSub from "effect/PubSub" import * as Queue from "effect/Queue" import * as Readable from "effect/Readable" -import * as ReadonlyArray from "effect/ReadonlyArray" import type { Request } from "effect/Request" import type * as Schedule from "effect/Schedule" import type * as Scope from "effect/Scope" @@ -703,7 +703,7 @@ export const boot = < )), decodeRequest: Schema.decodeUnknown( Schema.Union( - ...ReadonlyArray.filter( + ...Array.filter( procedures.public, Procedure.isSerializable ).map((p) => p.schema) diff --git a/packages/experimental/src/Persistence/Lmdb.ts b/packages/experimental/src/Persistence/Lmdb.ts index f176164111..09a8eebc4b 100644 --- a/packages/experimental/src/Persistence/Lmdb.ts +++ b/packages/experimental/src/Persistence/Lmdb.ts @@ -1,11 +1,11 @@ /** * @since 1.0.0 */ +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { identity } from "effect/Function" import * as Layer from "effect/Layer" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Lmdb from "lmdb" import * as Persistence from "../Persistence.js" import * as TimeToLive from "../TimeToLive.js" @@ -51,7 +51,7 @@ export const make = (options: Lmdb.RootDatabaseOptionsWithPath) => try: () => store.getMany(keys), catch: (error) => Persistence.PersistenceBackingError.make("getMany", error) }), - ReadonlyArray.map((value, i) => valueToOption(keys[i], value)) + Array.map((value, i) => valueToOption(keys[i], value)) ), set: (key, value, ttl) => Effect.tryPromise({ diff --git a/packages/experimental/src/RequestResolver.ts b/packages/experimental/src/RequestResolver.ts index 213f55443b..bb60741a18 100644 --- a/packages/experimental/src/RequestResolver.ts +++ b/packages/experimental/src/RequestResolver.ts @@ -2,6 +2,7 @@ * @since 1.0.0 */ import type * as Serializable from "@effect/schema/Serializable" +import * as Array from "effect/Array" import * as Deferred from "effect/Deferred" import type * as Duration from "effect/Duration" import * as Effect from "effect/Effect" @@ -10,7 +11,6 @@ import { dual, pipe } from "effect/Function" import * as Option from "effect/Option" import type * as PrimaryKey from "effect/PrimaryKey" import * as Queue from "effect/Queue" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Ref from "effect/Ref" import * as Request from "effect/Request" import * as RequestResolver from "effect/RequestResolver" @@ -59,8 +59,8 @@ export const dataLoader = dual< Queue.shutdown ) ) - const batch = yield* _(Ref.make(ReadonlyArray.empty>())) - const takeOne = Effect.flatMap(Queue.take(queue), (item) => Ref.updateAndGet(batch, ReadonlyArray.append(item))) + const batch = yield* _(Ref.make(Array.empty>())) + const takeOne = Effect.flatMap(Queue.take(queue), (item) => Ref.updateAndGet(batch, Array.append(item))) const takeRest = takeOne.pipe( Effect.repeat({ until: (items) => @@ -69,7 +69,7 @@ export const dataLoader = dual< }), Effect.timeout(options.window), Effect.ignore, - Effect.zipRight(Ref.getAndSet(batch, ReadonlyArray.empty())) + Effect.zipRight(Ref.getAndSet(batch, Array.empty())) ) yield* _( @@ -163,7 +163,7 @@ export const persisted: { const partition = (requests: ReadonlyArray) => storage.getMany(requests as any).pipe( Effect.map( - ReadonlyArray.partitionMap((_, i) => + Array.partitionMap((_, i) => Option.match(_, { onNone: () => Either.left(requests[i]), onSome: (_) => Either.right([requests[i], _] as const) diff --git a/packages/experimental/test/RequestResolver.test.ts b/packages/experimental/test/RequestResolver.test.ts index b54e557707..28fe2567a4 100644 --- a/packages/experimental/test/RequestResolver.test.ts +++ b/packages/experimental/test/RequestResolver.test.ts @@ -6,7 +6,7 @@ import { FileSystem, KeyValueStore } from "@effect/platform" import { NodeContext } from "@effect/platform-node" import { Schema } from "@effect/schema" import * as it from "@effect/vitest" -import { Effect, Exit, Layer, PrimaryKey, ReadonlyArray, Request, RequestResolver, TestClock } from "effect" +import { Array, Effect, Exit, Layer, PrimaryKey, Request, RequestResolver, TestClock } from "effect" import { assert, describe } from "vitest" class User extends Schema.Class("User")({ @@ -51,14 +51,14 @@ describe("RequestResolver", () => { }) const persisted = yield* _(RequestResolverX.persisted(baseResolver, storeId)) let users = yield* _( - Effect.forEach(ReadonlyArray.range(1, 5), (id) => Effect.request(new MyRequest({ id }), persisted), { + Effect.forEach(Array.range(1, 5), (id) => Effect.request(new MyRequest({ id }), persisted), { batching: true }) ) assert.strictEqual(count, 5) assert.strictEqual(users.length, 5) users = yield* _( - Effect.forEach(ReadonlyArray.range(1, 5), (id) => Effect.request(new MyRequest({ id }), persisted), { + Effect.forEach(Array.range(1, 5), (id) => Effect.request(new MyRequest({ id }), persisted), { batching: true }) ) @@ -68,7 +68,7 @@ describe("RequestResolver", () => { // ttl let results = yield* _( Effect.forEach( - ReadonlyArray.range(-1, 3), + Array.range(-1, 3), (id) => Effect.exit(Effect.request(new TTLRequest({ id }), persisted)), { batching: true @@ -82,7 +82,7 @@ describe("RequestResolver", () => { results = yield* _( Effect.forEach( - ReadonlyArray.range(-1, 3), + Array.range(-1, 3), (id) => Effect.exit(Effect.request(new TTLRequest({ id }), persisted)), { batching: true @@ -96,7 +96,7 @@ describe("RequestResolver", () => { results = yield* _( Effect.forEach( - ReadonlyArray.range(-1, 3), + Array.range(-1, 3), (id) => Effect.exit(Effect.request(new TTLRequest({ id }), persisted)), { batching: true @@ -110,7 +110,7 @@ describe("RequestResolver", () => { results = yield* _( Effect.forEach( - ReadonlyArray.range(-1, 3), + Array.range(-1, 3), (id) => Effect.exit(Effect.request(new TTLRequest({ id }), persisted)), { batching: true @@ -126,7 +126,7 @@ describe("RequestResolver", () => { yield* _(store.clear) users = yield* _( - Effect.forEach(ReadonlyArray.range(1, 5), (id) => Effect.request(new MyRequest({ id }), persisted), { + Effect.forEach(Array.range(1, 5), (id) => Effect.request(new MyRequest({ id }), persisted), { batching: true }) ) diff --git a/packages/opentelemetry/src/internal/metrics.ts b/packages/opentelemetry/src/internal/metrics.ts index 38fbe9ff2b..d7b5d891b0 100644 --- a/packages/opentelemetry/src/internal/metrics.ts +++ b/packages/opentelemetry/src/internal/metrics.ts @@ -12,6 +12,7 @@ import type { MetricReader } from "@opentelemetry/sdk-metrics" import { AggregationTemporality, DataPointType, InstrumentType } from "@opentelemetry/sdk-metrics" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import type { LazyArg } from "effect/Function" import * as Layer from "effect/Layer" @@ -20,7 +21,6 @@ import type * as MetricKey from "effect/MetricKey" import * as MetricKeyType from "effect/MetricKeyType" import * as MetricState from "effect/MetricState" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Resource from "../Resource.js" const sdkName = "@effect/opentelemetry/Metrics" @@ -51,7 +51,7 @@ export class MetricProducerImpl implements MetricProducer { for (let i = 0, len = snapshot.length; i < len; i++) { const { metricKey, metricState } = snapshot[i] - const attributes = ReadonlyArray.reduce(metricKey.tags, {}, (acc: Record, label) => { + const attributes = Array.reduce(metricKey.tags, {}, (acc: Record, label) => { acc[label.key] = label.value return acc }) @@ -96,8 +96,8 @@ export class MetricProducerImpl implements MetricProducer { } else if (MetricState.isHistogramState(metricState)) { const size = metricState.buckets.length const buckets = { - boundaries: Array(size - 1), - counts: Array(size) + boundaries: Array.allocate(size - 1) as Array, + counts: Array.allocate(size) as Array } let i = 0 let prev = 0 diff --git a/packages/platform-bun/src/internal/http/server.ts b/packages/platform-bun/src/internal/http/server.ts index 82b5b74e8c..06bb0a104b 100644 --- a/packages/platform-bun/src/internal/http/server.ts +++ b/packages/platform-bun/src/internal/http/server.ts @@ -26,7 +26,7 @@ import { pipe } from "effect/Function" import * as Inspectable from "effect/Inspectable" import * as Layer from "effect/Layer" import * as Option from "effect/Option" -import type { ReadonlyRecord } from "effect/ReadonlyRecord" +import type { ReadonlyRecord } from "effect/Record" import type * as Scope from "effect/Scope" import * as Stream from "effect/Stream" import { Readable } from "node:stream" diff --git a/packages/platform-node-shared/test/CommandExecutor.test.ts b/packages/platform-node-shared/test/CommandExecutor.test.ts index 74b0900a3f..31c24459db 100644 --- a/packages/platform-node-shared/test/CommandExecutor.test.ts +++ b/packages/platform-node-shared/test/CommandExecutor.test.ts @@ -6,6 +6,7 @@ import type * as CommandExecutor from "@effect/platform/CommandExecutor" import { SystemError } from "@effect/platform/Error" import * as FileSystem from "@effect/platform/FileSystem" import * as Path from "@effect/platform/Path" +import * as Array from "effect/Array" import * as Chunk from "effect/Chunk" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" @@ -14,7 +15,6 @@ import { pipe } from "effect/Function" import * as Layer from "effect/Layer" import * as Option from "effect/Option" import * as Order from "effect/Order" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Stream from "effect/Stream" import { describe, expect, it } from "vitest" @@ -48,7 +48,7 @@ describe("Command", () => { runPromise(Effect.gen(function*(_) { const command = Command.make("echo", "-n", "1\n2\n3") const result = yield* _(Stream.runCollect(Command.streamLines(command))) - expect(Array.from(result)).toEqual(["1", "2", "3"]) + expect(Chunk.toReadonlyArray(result)).toEqual(["1", "2", "3"]) }))) it("should work with a Stream directly", () => @@ -61,7 +61,7 @@ describe("Command", () => { Stream.splitLines, Stream.runCollect ) - expect(Array.from(result)).toEqual(["1", "2", "3"]) + expect(Chunk.toReadonlyArray(result)).toEqual(["1", "2", "3"]) }))) it("should fail when trying to run a command that does not exist", () => @@ -377,7 +377,7 @@ describe("Command", () => { Command.runInShell("/bin/bash") ) const lines = yield* _(Command.lines(command)) - expect(ReadonlyArray.sort(files, Order.string)).toEqual(ReadonlyArray.sort(lines, Order.string)) + expect(Array.sort(files, Order.string)).toEqual(Array.sort(lines, Order.string)) }).pipe(Effect.scoped) )) }) diff --git a/packages/platform-node-shared/test/Stream.test.ts b/packages/platform-node-shared/test/Stream.test.ts index c1ae52f3e6..e334f8441f 100644 --- a/packages/platform-node-shared/test/Stream.test.ts +++ b/packages/platform-node-shared/test/Stream.test.ts @@ -1,5 +1,5 @@ import * as NodeStream from "@effect/platform-node-shared/NodeStream" -import { Channel, Chunk, ReadonlyArray, Stream } from "effect" +import { Array, Channel, Chunk, Stream } from "effect" import * as Effect from "effect/Effect" import { Duplex, Readable, Transform } from "stream" import { assert, describe, it } from "vitest" @@ -163,6 +163,6 @@ describe("Stream", () => { Stream.decodeText(), Stream.runCollect ) - assert.strictEqual(Chunk.join(items, ""), ReadonlyArray.range(0, 10000).join("")) + assert.strictEqual(Chunk.join(items, ""), Array.range(0, 10000).join("")) }).pipe(Effect.runPromise)) }) diff --git a/packages/platform-node/src/internal/http/server.ts b/packages/platform-node/src/internal/http/server.ts index 9c4c54190e..114f58e936 100644 --- a/packages/platform-node/src/internal/http/server.ts +++ b/packages/platform-node/src/internal/http/server.ts @@ -21,7 +21,7 @@ import * as FiberSet from "effect/FiberSet" import { type LazyArg } from "effect/Function" import * as Layer from "effect/Layer" import * as Option from "effect/Option" -import type { ReadonlyRecord } from "effect/ReadonlyRecord" +import type { ReadonlyRecord } from "effect/Record" import * as Scope from "effect/Scope" import * as Stream from "effect/Stream" import * as Http from "node:http" diff --git a/packages/platform/src/Command.ts b/packages/platform/src/Command.ts index 84ef8d0bd6..b552ad1253 100644 --- a/packages/platform/src/Command.ts +++ b/packages/platform/src/Command.ts @@ -1,12 +1,12 @@ /** * @since 1.0.0 */ +import type { NonEmptyReadonlyArray } from "effect/Array" import type { Effect } from "effect/Effect" import type { HashMap } from "effect/HashMap" import type { Inspectable } from "effect/Inspectable" import type { Option } from "effect/Option" import type { Pipeable } from "effect/Pipeable" -import type { NonEmptyReadonlyArray } from "effect/ReadonlyArray" import type { Scope } from "effect/Scope" import type { Sink } from "effect/Sink" import type { Stream } from "effect/Stream" diff --git a/packages/platform/src/Http/Cookies.ts b/packages/platform/src/Http/Cookies.ts index bddf8fb200..930bd67db2 100644 --- a/packages/platform/src/Http/Cookies.ts +++ b/packages/platform/src/Http/Cookies.ts @@ -8,7 +8,7 @@ import * as Inspectable from "effect/Inspectable" import * as Option from "effect/Option" import { type Pipeable, pipeArguments } from "effect/Pipeable" import * as Predicate from "effect/Predicate" -import * as ReadonlyRecord from "effect/ReadonlyRecord" +import * as Record from "effect/Record" import type * as Types from "effect/Types" import { TypeIdError } from "../Error.js" @@ -36,7 +36,7 @@ export const isCookies = (u: unknown): u is Cookies => Predicate.hasProperty(u, */ export interface Cookies extends Pipeable, Inspectable.Inspectable { readonly [TypeId]: TypeId - readonly cookies: ReadonlyRecord.ReadonlyRecord + readonly cookies: Record.ReadonlyRecord } /** @@ -103,7 +103,7 @@ const Proto: Omit = { toJSON(this: Cookies) { return { _id: "@effect/platform/Http/Cookies", - cookies: ReadonlyRecord.map(this.cookies, (cookie) => cookie.toJSON()) + cookies: Record.map(this.cookies, (cookie) => cookie.toJSON()) } }, pipe() { @@ -117,7 +117,7 @@ const Proto: Omit = { * @since 1.0.0 * @category constructors */ -export const fromReadonlyRecord = (cookies: ReadonlyRecord.ReadonlyRecord): Cookies => { +export const fromReadonlyRecord = (cookies: Record.ReadonlyRecord): Cookies => { const self = Object.create(Proto) self.cookies = cookies return self @@ -299,7 +299,7 @@ export const empty: Cookies = fromIterable([]) * @since 1.0.0 * @category refinements */ -export const isEmpty = (self: Cookies): boolean => ReadonlyRecord.isEmptyRecord(self.cookies) +export const isEmpty = (self: Cookies): boolean => Record.isEmptyRecord(self.cookies) // eslint-disable-next-line no-control-regex const fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/ @@ -385,7 +385,7 @@ export const setCookie: { } = dual( 2, (self: Cookies, cookie: Cookie) => - fromReadonlyRecord(ReadonlyRecord.set( + fromReadonlyRecord(Record.set( self.cookies, cookie.name, cookie @@ -442,7 +442,7 @@ export const remove: { self: Cookies, name: string ): Cookies -} = dual(2, (self: Cookies, name: string) => fromReadonlyRecord(ReadonlyRecord.remove(self.cookies, name))) +} = dual(2, (self: Cookies, name: string) => fromReadonlyRecord(Record.remove(self.cookies, name))) /** * Add a cookie to a Cookies object @@ -467,7 +467,7 @@ export const set: { (self: Cookies, name: string, value: string, options?: Cookie["options"]) => Either.map( makeCookie(name, value, options), - (cookie) => fromReadonlyRecord(ReadonlyRecord.set(self.cookies, name, cookie)) + (cookie) => fromReadonlyRecord(Record.set(self.cookies, name, cookie)) ) ) @@ -492,7 +492,7 @@ export const unsafeSet: { } = dual( (args) => isCookies(args[0]), (self: Cookies, name: string, value: string, options?: Cookie["options"]) => - fromReadonlyRecord(ReadonlyRecord.set( + fromReadonlyRecord(Record.set( self.cookies, name, unsafeMakeCookie(name, value, options) diff --git a/packages/platform/src/Http/Headers.ts b/packages/platform/src/Http/Headers.ts index b0a94710d3..6a05d267c2 100644 --- a/packages/platform/src/Http/Headers.ts +++ b/packages/platform/src/Http/Headers.ts @@ -2,11 +2,11 @@ * @since 1.0.0 */ import * as Schema from "@effect/schema/Schema" +import * as Array from "effect/Array" import { dual, identity } from "effect/Function" import type * as Option from "effect/Option" import * as Predicate from "effect/Predicate" -import * as ReadonlyArray from "effect/ReadonlyArray" -import * as ReadonlyRecord from "effect/ReadonlyRecord" +import * as Record from "effect/Record" import * as Secret from "effect/Secret" import * as String from "effect/String" @@ -43,15 +43,15 @@ export interface Headers { */ export const schemaFromSelf: Schema.Schema = Schema.declare(isHeaders, { identifier: "Headers", - equivalence: () => ReadonlyRecord.getEquivalence(String.Equivalence) + equivalence: () => Record.getEquivalence(String.Equivalence) }) /** * @since 1.0.0 * @category schemas */ -export const schema: Schema.Schema>> = - Schema.transform( +export const schema: Schema.Schema>> = Schema + .transform( Schema.Record(Schema.String, Schema.Union(Schema.String, Schema.Array(Schema.String))), schemaFromSelf, { decode: (record) => fromInput(record), encode: identity } @@ -62,7 +62,7 @@ export const schema: Schema.Schema | undefined> + | Record.ReadonlyRecord | undefined> | Iterable /** @@ -79,12 +79,12 @@ export const fromInput: (input?: Input) => Headers = (input) => { if (input === undefined) { return empty } else if (Symbol.iterator in input) { - return ReadonlyRecord.fromEntries(ReadonlyArray.map( - ReadonlyArray.fromIterable(input), + return Record.fromEntries(Array.map( + Array.fromIterable(input), ([k, v]) => [k.toLowerCase(), v] as const )) as Headers } - return ReadonlyRecord.fromEntries( + return Record.fromEntries( Object.entries(input).map(([k, v]) => [ k.toLowerCase(), @@ -98,7 +98,7 @@ export const fromInput: (input?: Input) => Headers = (input) => { * @since 1.0.0 * @category constructors */ -export const unsafeFromRecord = (input: ReadonlyRecord.ReadonlyRecord): Headers => input as Headers +export const unsafeFromRecord = (input: Record.ReadonlyRecord): Headers => input as Headers /** * @since 1.0.0 @@ -110,7 +110,7 @@ export const has: { } = dual< (key: string) => (self: Headers) => boolean, (self: Headers, key: string) => boolean ->(2, (self, key) => ReadonlyRecord.has(self as Record, key.toLowerCase())) +>(2, (self, key) => Record.has(self as Record, key.toLowerCase())) /** * @since 1.0.0 @@ -122,7 +122,7 @@ export const get: { } = dual< (key: string) => (self: Headers) => Option.Option, (self: Headers, key: string) => Option.Option ->(2, (self, key) => ReadonlyRecord.get(self as Record, key.toLowerCase())) +>(2, (self, key) => Record.get(self as Record, key.toLowerCase())) /** * @since 1.0.0 diff --git a/packages/platform/src/Http/ServerRequest.ts b/packages/platform/src/Http/ServerRequest.ts index 70880e5761..3e8c3aa179 100644 --- a/packages/platform/src/Http/ServerRequest.ts +++ b/packages/platform/src/Http/ServerRequest.ts @@ -8,7 +8,7 @@ import type { Channel } from "effect/Channel" import type { Chunk } from "effect/Chunk" import type * as Context from "effect/Context" import type * as Effect from "effect/Effect" -import type { ReadonlyRecord } from "effect/ReadonlyRecord" +import type { ReadonlyRecord } from "effect/Record" import type * as Scope from "effect/Scope" import type * as Stream from "effect/Stream" import type * as FileSystem from "../FileSystem.js" diff --git a/packages/platform/src/Http/UrlParams.ts b/packages/platform/src/Http/UrlParams.ts index 615558c4bd..8edb5afe52 100644 --- a/packages/platform/src/Http/UrlParams.ts +++ b/packages/platform/src/Http/UrlParams.ts @@ -4,10 +4,10 @@ import type { ParseOptions } from "@effect/schema/AST" import type * as ParseResult from "@effect/schema/ParseResult" import * as Schema from "@effect/schema/Schema" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { dual } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" /** * @since 1.0.0 @@ -27,9 +27,9 @@ export type Input = Readonly> | Iterable { if (Symbol.iterator in input) { - return ReadonlyArray.fromIterable(input) + return Array.fromIterable(input) } - return ReadonlyArray.fromIterable(Object.entries(input)) + return Array.fromIterable(Object.entries(input)) } /** @@ -59,7 +59,7 @@ export const getAll: { (key: string) => (self: UrlParams) => ReadonlyArray, (self: UrlParams, key: string) => ReadonlyArray >(2, (self, key) => - ReadonlyArray.reduce(self, [] as Array, (acc, [k, value]) => { + Array.reduce(self, [] as Array, (acc, [k, value]) => { if (k === key) { acc.push(value) } @@ -78,7 +78,7 @@ export const getFirst: { (self: UrlParams, key: string) => Option.Option >(2, (self, key) => Option.map( - ReadonlyArray.findFirst( + Array.findFirst( self, ([k]) => k === key ), @@ -97,7 +97,7 @@ export const getLast: { (self: UrlParams, key: string) => Option.Option >(2, (self, key) => Option.map( - ReadonlyArray.findLast( + Array.findLast( self, ([k]) => k === key ), @@ -115,8 +115,8 @@ export const set: { (key: string, value: string) => (self: UrlParams) => UrlParams, (self: UrlParams, key: string, value: string) => UrlParams >(3, (self, key, value) => - ReadonlyArray.append( - ReadonlyArray.filter(self, ([k]) => k !== key), + Array.append( + Array.filter(self, ([k]) => k !== key), [key, value] )) @@ -133,8 +133,8 @@ export const setAll: { >(2, (self, input) => { const toSet = fromInput(input) const keys = toSet.map(([k]) => k) - return ReadonlyArray.appendAll( - ReadonlyArray.filter(self, ([k]) => keys.includes(k)), + return Array.appendAll( + Array.filter(self, ([k]) => keys.includes(k)), toSet ) }) @@ -150,7 +150,7 @@ export const append: { (key: string, value: string) => (self: UrlParams) => UrlParams, (self: UrlParams, key: string, value: string) => UrlParams >(3, (self, key, value) => - ReadonlyArray.append( + Array.append( self, [key, value] )) @@ -166,7 +166,7 @@ export const appendAll: { (input: Input) => (self: UrlParams) => UrlParams, (self: UrlParams, input: Input) => UrlParams >(2, (self, input) => - ReadonlyArray.appendAll( + Array.appendAll( self, fromInput(input) )) @@ -181,7 +181,7 @@ export const remove: { } = dual< (key: string) => (self: UrlParams) => UrlParams, (self: UrlParams, key: string) => UrlParams ->(2, (self, key) => ReadonlyArray.filter(self, ([k]) => k !== key)) +>(2, (self, key) => Array.filter(self, ([k]) => k !== key)) /** * @since 1.0.0 @@ -197,7 +197,7 @@ export const makeUrl = (url: string, params: UrlParams, onError: (e: unknown) Effect.try({ try: () => { const urlInstance = new URL(url, baseUrl()) - ReadonlyArray.forEach(params, ([key, value]) => { + Array.forEach(params, ([key, value]) => { if (value !== undefined) { urlInstance.searchParams.append(key, value) } diff --git a/packages/platform/src/PlatformConfigProvider.ts b/packages/platform/src/PlatformConfigProvider.ts index 538696fb55..3b03b34aab 100644 --- a/packages/platform/src/PlatformConfigProvider.ts +++ b/packages/platform/src/PlatformConfigProvider.ts @@ -1,6 +1,7 @@ /** * @since 1.0.0 */ +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import type * as Config from "effect/Config" import * as ConfigError from "effect/ConfigError" @@ -12,7 +13,6 @@ import * as Effect from "effect/Effect" import * as Either from "effect/Either" import * as HashSet from "effect/HashSet" import * as Layer from "effect/Layer" -import * as ReadonlyArray from "effect/ReadonlyArray" import { isPlatformError, type PlatformError } from "./Error.js" import * as FileSystem from "./FileSystem.js" import * as Path from "./Path.js" @@ -31,7 +31,7 @@ export const fromFileTree = (options?: { const rootDirectory = options?.rootDirectory ?? "/" const parseConfig = (primitive: Config.Config.Primitive) => (value: string) => - Either.map(primitive.parse(value.trim()), ReadonlyArray.of) + Either.map(primitive.parse(value.trim()), Array.of) const readConfig = (filePath: string, primitive: Config.Config.Primitive) => Effect.flatMap( diff --git a/packages/platform/src/internal/command.ts b/packages/platform/src/internal/command.ts index c5fbd84b5f..d9df1a21e7 100644 --- a/packages/platform/src/internal/command.ts +++ b/packages/platform/src/internal/command.ts @@ -1,3 +1,4 @@ +import type * as ReadonlyArray from "effect/Array" import * as Chunk from "effect/Chunk" import * as Effect from "effect/Effect" import { dual } from "effect/Function" @@ -5,7 +6,6 @@ import * as HashMap from "effect/HashMap" import * as Inspectable from "effect/Inspectable" import * as Option from "effect/Option" import { pipeArguments } from "effect/Pipeable" -import type * as ReadonlyArray from "effect/ReadonlyArray" import type { Scope } from "effect/Scope" import * as Stream from "effect/Stream" import type * as Command from "../Command.js" diff --git a/packages/platform/src/internal/http/multiplex.ts b/packages/platform/src/internal/http/multiplex.ts index b318870efd..da06a565e7 100644 --- a/packages/platform/src/internal/http/multiplex.ts +++ b/packages/platform/src/internal/http/multiplex.ts @@ -1,8 +1,8 @@ +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import * as Effectable from "effect/Effectable" import { dual } from "effect/Function" import * as Inspectable from "effect/Inspectable" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as App from "../../Http/App.js" import type * as Multiplex from "../../Http/Multiplex.js" import * as Error from "../../Http/ServerError.js" @@ -72,7 +72,7 @@ export const make = ( apps: Iterable< readonly [predicate: (request: ServerRequest.ServerRequest) => Effect.Effect, app: App.Default] > -): Multiplex.Multiplex => new MultiplexImpl(ReadonlyArray.fromIterable(apps)) +): Multiplex.Multiplex => new MultiplexImpl(Array.fromIterable(apps)) /** @internal */ export const add = dual< diff --git a/packages/platform/src/internal/http/serverRequest.ts b/packages/platform/src/internal/http/serverRequest.ts index c3e4535233..a08dc2f9b8 100644 --- a/packages/platform/src/internal/http/serverRequest.ts +++ b/packages/platform/src/internal/http/serverRequest.ts @@ -6,7 +6,7 @@ import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as Inspectable from "effect/Inspectable" import * as Option from "effect/Option" -import type { ReadonlyRecord } from "effect/ReadonlyRecord" +import type { ReadonlyRecord } from "effect/Record" import type * as Scope from "effect/Scope" import * as Stream from "effect/Stream" import type * as FileSystem from "../../FileSystem.js" diff --git a/packages/platform/src/internal/worker.ts b/packages/platform/src/internal/worker.ts index 475818cba5..75a77d2388 100644 --- a/packages/platform/src/internal/worker.ts +++ b/packages/platform/src/internal/worker.ts @@ -1,5 +1,6 @@ import * as Schema from "@effect/schema/Schema" import * as Serializable from "@effect/schema/Serializable" +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import * as Channel from "effect/Channel" import * as Chunk from "effect/Chunk" @@ -13,7 +14,6 @@ import * as Layer from "effect/Layer" import * as Option from "effect/Option" import * as Pool from "effect/Pool" import * as Queue from "effect/Queue" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Schedule from "effect/Schedule" import type * as Scope from "effect/Scope" import * as Stream from "effect/Stream" @@ -240,7 +240,7 @@ export const makeManager = Effect.gen(function*(_) { const executeEffect = (request: I) => Effect.acquireUseRelease( executeAcquire(request), - ([, queue]) => Effect.flatMap(Queue.take(queue), Exit.map(ReadonlyArray.unsafeGet(0))), + ([, queue]) => Effect.flatMap(Queue.take(queue), Exit.map(Array.unsafeGet(0))), executeRelease ) diff --git a/packages/printer-ansi/src/internal/ansi.ts b/packages/printer-ansi/src/internal/ansi.ts index a8d3246327..11008de072 100644 --- a/packages/printer-ansi/src/internal/ansi.ts +++ b/packages/printer-ansi/src/internal/ansi.ts @@ -1,8 +1,8 @@ import * as Monoid from "@effect/typeclass/Monoid" import * as Semigroup from "@effect/typeclass/Semigroup" +import * as Array from "effect/Array" import { dual } from "effect/Function" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as Ansi from "../Ansi.js" import type * as Color from "../Color.js" import * as InternalColor from "./color.js" @@ -222,16 +222,16 @@ export const bgWhiteBright: Ansi.Ansi = bgColorBright(InternalColor.white) // ----------------------------------------------------------------------------- /** @internal */ -export const beep: Ansi.Ansi = make({ commands: ReadonlyArray.of(BEL) }) +export const beep: Ansi.Ansi = make({ commands: Array.of(BEL) }) /** @internal */ export const cursorTo = (column: number, row?: number): Ansi.Ansi => { if (row === undefined) { const command = `${ESC}${Math.max(column + 1, 0)}G` - return make({ commands: ReadonlyArray.of(command) }) + return make({ commands: Array.of(command) }) } const command = `${ESC}${row + 1}${SEP}${Math.max(column + 1, 0)}H` - return make({ commands: ReadonlyArray.of(command) }) + return make({ commands: Array.of(command) }) } /** @internal */ @@ -249,53 +249,53 @@ export const cursorMove = (column: number, row: number = 0): Ansi.Ansi => { if (column < 0) { command += `${ESC}${-column}D` } - return make({ commands: ReadonlyArray.of(command) }) + return make({ commands: Array.of(command) }) } /** @internal */ export const cursorUp = (lines: number = 1): Ansi.Ansi => { const command = `${ESC}${lines}A` - return make({ commands: ReadonlyArray.of(command) }) + return make({ commands: Array.of(command) }) } /** @internal */ export const cursorDown = (lines: number = 1): Ansi.Ansi => { const command = `${ESC}${lines}B` - return make({ commands: ReadonlyArray.of(command) }) + return make({ commands: Array.of(command) }) } /** @internal */ export const cursorForward = (columns: number = 1): Ansi.Ansi => { const command = `${ESC}${columns}C` - return make({ commands: ReadonlyArray.of(command) }) + return make({ commands: Array.of(command) }) } /** @internal */ export const cursorBackward = (columns: number = 1): Ansi.Ansi => { const command = `${ESC}${columns}D` - return make({ commands: ReadonlyArray.of(command) }) + return make({ commands: Array.of(command) }) } /** @internal */ -export const cursorLeft: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}G`) }) +export const cursorLeft: Ansi.Ansi = make({ commands: Array.of(`${ESC}G`) }) /** @internal */ -export const cursorSavePosition: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}s`) }) +export const cursorSavePosition: Ansi.Ansi = make({ commands: Array.of(`${ESC}s`) }) /** @internal */ -export const cursorRestorePosition: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}u`) }) +export const cursorRestorePosition: Ansi.Ansi = make({ commands: Array.of(`${ESC}u`) }) /** @internal */ -export const cursorNextLine = (rows: number = 1): Ansi.Ansi => make({ commands: ReadonlyArray.of(`${ESC}${rows}E`) }) +export const cursorNextLine = (rows: number = 1): Ansi.Ansi => make({ commands: Array.of(`${ESC}${rows}E`) }) /** @internal */ -export const cursorPrevLine = (rows: number = 1): Ansi.Ansi => make({ commands: ReadonlyArray.of(`${ESC}${rows}F`) }) +export const cursorPrevLine = (rows: number = 1): Ansi.Ansi => make({ commands: Array.of(`${ESC}${rows}F`) }) /** @internal */ -export const cursorHide: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}?25l`) }) +export const cursorHide: Ansi.Ansi = make({ commands: Array.of(`${ESC}?25l`) }) /** @internal */ -export const cursorShow: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}?25h`) }) +export const cursorShow: Ansi.Ansi = make({ commands: Array.of(`${ESC}?25h`) }) /** @internal */ export const eraseLines = (rows: number): Ansi.Ansi => { @@ -306,26 +306,26 @@ export const eraseLines = (rows: number): Ansi.Ansi => { if (rows > 0) { command += `${ESC}G` } - return make({ commands: ReadonlyArray.of(command) }) + return make({ commands: Array.of(command) }) } /** @internal */ -export const eraseEndLine: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}K`) }) +export const eraseEndLine: Ansi.Ansi = make({ commands: Array.of(`${ESC}K`) }) /** @internal */ -export const eraseStartLine: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}1K`) }) +export const eraseStartLine: Ansi.Ansi = make({ commands: Array.of(`${ESC}1K`) }) /** @internal */ -export const eraseLine: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}2K`) }) +export const eraseLine: Ansi.Ansi = make({ commands: Array.of(`${ESC}2K`) }) /** @internal */ -export const eraseDown: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}J`) }) +export const eraseDown: Ansi.Ansi = make({ commands: Array.of(`${ESC}J`) }) /** @internal */ -export const eraseUp: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}1J`) }) +export const eraseUp: Ansi.Ansi = make({ commands: Array.of(`${ESC}1J`) }) /** @internal */ -export const eraseScreen: Ansi.Ansi = make({ commands: ReadonlyArray.of(`${ESC}2J`) }) +export const eraseScreen: Ansi.Ansi = make({ commands: Array.of(`${ESC}2J`) }) // ----------------------------------------------------------------------------- // Destructors @@ -352,7 +352,7 @@ const combineInternal = (self: AnsiImpl, that: AnsiImpl): Ansi.Ansi => AnsiSemig const stringifyInternal = (self: AnsiImpl): string => { const displaySequence = SGR.toEscapeSequence( - ReadonlyArray.getSomes([ + Array.getSomes([ Option.some(SGR.reset), self.foreground, self.background, @@ -362,6 +362,6 @@ const stringifyInternal = (self: AnsiImpl): string => { self.underlined ]) ) - const commandSequence = ReadonlyArray.join(self.commands, "") + const commandSequence = Array.join(self.commands, "") return `${displaySequence}${commandSequence}` } diff --git a/packages/printer/README.md b/packages/printer/README.md index 627a3d736c..61b186b86f 100644 --- a/packages/printer/README.md +++ b/packages/printer/README.md @@ -51,8 +51,8 @@ First, let's setup the imports we need: ```ts import * as Doc from "@effect/printer/Doc" import * as Render from "@effect/printer/Render" -import { pipe } from "@effect/data/Function" -import * as ReadonlyArray from "@effect/data/ReadonlyArray" +import * as Array from "effect/Array" +import { pipe } from "effect/Function" ``` Next, we intersperse the `"->"` character between our types and add a leading `"::"` character: @@ -60,13 +60,12 @@ Next, we intersperse the `"->"` character between our types and add a leading `" ```ts const prettyTypes = (types: ReadonlyArray): Doc.Doc => { const symbolDocuments = pipe( - ReadonlyArray.makeBy(types.length - 1, () => Doc.text("->")), - ReadonlyArray.prepend(Doc.text("::")) + Array.makeBy(types.length - 1, () => Doc.text("->")), + Array.prepend(Doc.text("::")) ) const typeDocuments = types.map(Doc.text) const documents = pipe( - - ReadonlyArray.zipWith( + Array.zipWith( symbolDocuments, typeDocuments, (left, right) => Doc.catWithSpace(left, right) diff --git a/packages/printer/examples/main.ts b/packages/printer/examples/main.ts index 54a27fe223..8bd2ed255b 100644 --- a/packages/printer/examples/main.ts +++ b/packages/printer/examples/main.ts @@ -1,14 +1,14 @@ import * as Doc from "@effect/printer/Doc" +import * as Array from "effect/Array" import { pipe } from "effect/Function" -import * as ReadonlyArray from "effect/ReadonlyArray" const prettyTypes = (types: ReadonlyArray): Doc.Doc => { const symbolDocuments = pipe( - ReadonlyArray.makeBy(types.length - 1, () => Doc.text("->")), - ReadonlyArray.prepend(Doc.text("::")) + Array.makeBy(types.length - 1, () => Doc.text("->")), + Array.prepend(Doc.text("::")) ) const typeDocuments = types.map(Doc.text) - const documents = ReadonlyArray.zipWith( + const documents = Array.zipWith( symbolDocuments, typeDocuments, (left, right) => Doc.catWithSpace(left, right) diff --git a/packages/printer/src/internal/doc.ts b/packages/printer/src/internal/doc.ts index 90fb912283..210b3c7a85 100644 --- a/packages/printer/src/internal/doc.ts +++ b/packages/printer/src/internal/doc.ts @@ -2,12 +2,12 @@ import * as covariant from "@effect/typeclass/Covariant" import type * as invariant from "@effect/typeclass/Invariant" import type * as monoid from "@effect/typeclass/Monoid" import type * as semigroup from "@effect/typeclass/Semigroup" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import * as Equal from "effect/Equal" import { dual, pipe } from "effect/Function" import * as Hash from "effect/Hash" import { pipeArguments } from "effect/Pipeable" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as Doc from "../Doc.js" import type * as Flatten from "../Flatten.js" import type * as PageWidth from "../PageWidth.js" @@ -342,9 +342,9 @@ export const concatWith = dual< f: (left: Doc.Doc, right: Doc.Doc) => Doc.Doc ) => Doc.Doc >(2, (docs, f) => - ReadonlyArray.matchRight(ReadonlyArray.fromIterable(docs), { + Array.matchRight(Array.fromIterable(docs), { onEmpty: () => empty, - onNonEmpty: (init, last) => ReadonlyArray.reduceRight(init, last, (curr, acc) => f(acc, curr)) + onNonEmpty: (init, last) => Array.reduceRight(init, last, (curr, acc) => f(acc, curr)) })) /** @internal */ @@ -492,17 +492,17 @@ export const encloseSep = dual< right: Doc.Doc, sep: Doc.Doc ) => { - const documents = ReadonlyArray.fromIterable(docs) - if (ReadonlyArray.isEmptyReadonlyArray(documents)) { + const documents = Array.fromIterable(docs) + if (Array.isEmptyReadonlyArray(documents)) { return cat(left, right) } if (documents.length === 1) { return cat(left, cat(documents[0]!, right)) } const xs = pipe( - ReadonlyArray.makeBy(documents.length - 1, () => sep), - ReadonlyArray.prepend(left), - ReadonlyArray.zipWith(documents, (left: Doc.Doc, right) => cat(left, right)) + Array.makeBy(documents.length - 1, () => sep), + Array.prepend(left), + Array.zipWith(documents, (left: Doc.Doc, right) => cat(left, right)) ) return cat(cats(xs), right) }) @@ -748,8 +748,8 @@ const alterAnnotationsSafe = ( } case "Annotated": { return Effect.map(alterAnnotationsSafe(self.doc, f), (doc) => - ReadonlyArray.reduceRight( - ReadonlyArray.fromIterable(f(self.annotation)), + Array.reduceRight( + Array.fromIterable(f(self.annotation)), doc, (doc, b) => annotate(doc, b) )) @@ -882,8 +882,8 @@ export const punctuate = dual< (punctuator: Doc.Doc) => (docs: Iterable>) => ReadonlyArray>, (docs: Iterable>, punctuator: Doc.Doc) => ReadonlyArray> >(2, (docs, punctuator) => { - const documents = ReadonlyArray.fromIterable(docs) - return ReadonlyArray.map(documents, (x, i) => documents.length - 1 === i ? x : cat(x, punctuator)) + const documents = Array.fromIterable(docs) + return Array.map(documents, (x, i) => documents.length - 1 === i ? x : cat(x, punctuator)) }) /** @internal */ diff --git a/packages/printer/src/internal/docTree.ts b/packages/printer/src/internal/docTree.ts index 7a2d8b24bd..5f7f9bb295 100644 --- a/packages/printer/src/internal/docTree.ts +++ b/packages/printer/src/internal/docTree.ts @@ -2,12 +2,12 @@ import * as covariant from "@effect/typeclass/Covariant" import type * as invariant from "@effect/typeclass/Invariant" import type * as monoid from "@effect/typeclass/Monoid" import type * as semigroup from "@effect/typeclass/Semigroup" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import * as Equal from "effect/Equal" import { dual, pipe } from "effect/Function" import * as Hash from "effect/Hash" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as DocStream from "../DocStream.js" import type * as DocTree from "../DocTree.js" import * as doc from "./doc.js" @@ -202,8 +202,8 @@ const alterAnnotationsSafe = ( return Effect.succeed(line(self.indentation)) } case "AnnotationTree": { - return ReadonlyArray.reduce( - ReadonlyArray.fromIterable(f(self.annotation)), + return Array.reduce( + Array.fromIterable(f(self.annotation)), Effect.suspend(() => alterAnnotationsSafe(self.tree, f)), (acc, b) => Effect.map(acc, annotation(b)) ) @@ -255,7 +255,7 @@ const foldMapSafe = ( ) } case "ConcatTree": { - if (ReadonlyArray.isEmptyReadonlyArray(self.trees)) { + if (Array.isEmptyReadonlyArray(self.trees)) { return Effect.succeed(M.empty) } return Effect.map( @@ -263,7 +263,7 @@ const foldMapSafe = ( (trees) => { const head = trees[0] const tail = trees.slice(1) - return ReadonlyArray.reduce(tail, head, M.combine) + return Array.reduce(tail, head, M.combine) } ) } @@ -321,12 +321,12 @@ const renderSimplyDecoratedSafe = ( ) } case "ConcatTree": { - if (ReadonlyArray.isEmptyReadonlyArray(self.trees)) { + if (Array.isEmptyReadonlyArray(self.trees)) { return Effect.succeed(M.empty) } const head = self.trees[0] const tail = self.trees.slice(1) - return ReadonlyArray.reduce( + return Array.reduce( tail, Effect.suspend(() => renderSimplyDecoratedSafe(head, M, renderText, renderAnnotation)), (acc, tree) => @@ -499,8 +499,8 @@ const imap = covariant.imap(map) /** @internal */ export const getSemigroup = (_: void): semigroup.Semigroup> => { return { - combine: (self, that) => concat(ReadonlyArray.make(self, that)), - combineMany: (self, trees) => concat(ReadonlyArray.fromIterable([self, ...trees])) + combine: (self, that) => concat(Array.make(self, that)), + combineMany: (self, trees) => concat(Array.fromIterable([self, ...trees])) } } @@ -508,9 +508,9 @@ export const getSemigroup = (_: void): semigroup.Semigroup export const getMonoid = (_: void): monoid.Monoid> => { return { empty, - combine: (self, that) => concat(ReadonlyArray.make(self, that)), - combineMany: (self, trees) => concat(ReadonlyArray.fromIterable([self, ...trees])), - combineAll: (trees) => concat(ReadonlyArray.fromIterable(trees)) + combine: (self, that) => concat(Array.make(self, that)), + combineMany: (self, trees) => concat(Array.fromIterable([self, ...trees])), + combineAll: (trees) => concat(Array.fromIterable(trees)) } } diff --git a/packages/printer/test/docTree.test.ts b/packages/printer/test/docTree.test.ts index 9106ddba5d..5cfcb35c14 100644 --- a/packages/printer/test/docTree.test.ts +++ b/packages/printer/test/docTree.test.ts @@ -2,9 +2,9 @@ import * as Doc from "@effect/printer/Doc" import * as DocStream from "@effect/printer/DocStream" import * as DocTree from "@effect/printer/DocTree" import * as Layout from "@effect/printer/Layout" +import * as Array from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as String from "effect/String" import { describe, expect, it } from "vitest" @@ -173,7 +173,7 @@ describe.concurrent("DocTree", () => { } const head = tree.trees[0] const tail = tree.trees.slice(1) - return ReadonlyArray.reduce( + return Array.reduce( tail, Effect.suspend(() => renderTreeSafe(head)), (acc, tree) => diff --git a/packages/rpc-http/examples/router.ts b/packages/rpc-http/examples/router.ts index 51b6e00d02..6954131984 100644 --- a/packages/rpc-http/examples/router.ts +++ b/packages/rpc-http/examples/router.ts @@ -2,13 +2,13 @@ import { NodeHttpServer, NodeRuntime } from "@effect/platform-node" import * as Http from "@effect/platform/HttpServer" import { Router, Rpc } from "@effect/rpc" import { HttpRouter } from "@effect/rpc-http" -import { Effect, Layer, ReadonlyArray, Stream } from "effect" +import { Array, Effect, Layer, Stream } from "effect" import { createServer } from "http" import { GetUser, GetUserIds, User, UserId } from "./schema.js" // Implement the RPC server router const router = Router.make( - Rpc.stream(GetUserIds, () => Stream.fromIterable(ReadonlyArray.makeBy(1000, UserId))), + Rpc.stream(GetUserIds, () => Stream.fromIterable(Array.makeBy(1000, UserId))), Rpc.effect(GetUser, ({ id }) => Effect.succeed(new User({ id, name: "John Doe" }))) ) diff --git a/packages/rpc/src/Resolver.ts b/packages/rpc/src/Resolver.ts index a8315aced6..3eedd44db5 100644 --- a/packages/rpc/src/Resolver.ts +++ b/packages/rpc/src/Resolver.ts @@ -5,11 +5,11 @@ import * as Headers from "@effect/platform/Http/Headers" import type { ParseError } from "@effect/schema/ParseResult" import * as Schema from "@effect/schema/Schema" import * as Serializable from "@effect/schema/Serializable" +import * as Array from "effect/Array" import * as Cause from "effect/Cause" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import { dual, pipe } from "effect/Function" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Request from "effect/Request" import * as RequestResolver from "effect/RequestResolver" import * as Stream from "effect/Stream" @@ -32,7 +32,7 @@ export const make = ( const getDecodeChunk = withRequestTag((req) => Schema.decodeUnknown(Schema.Chunk(Serializable.exitSchema(req)))) return RequestResolver.makeBatched((requests: Array>) => { - const [effectRequests, streamRequests] = ReadonlyArray.partition( + const [effectRequests, streamRequests] = Array.partition( requests, (_): _ is Rpc.Request => StreamRequestTypeId in _.request ) diff --git a/packages/rpc/src/Rpc.ts b/packages/rpc/src/Rpc.ts index 459111a76c..8ab398ba02 100644 --- a/packages/rpc/src/Rpc.ts +++ b/packages/rpc/src/Rpc.ts @@ -13,7 +13,7 @@ import { globalValue } from "effect/GlobalValue" import { type Pipeable, pipeArguments } from "effect/Pipeable" import * as Predicate from "effect/Predicate" import type * as PrimaryKey from "effect/PrimaryKey" -import type * as ReadonlyRecord from "effect/ReadonlyRecord" +import type * as Record from "effect/Record" import type * as EffectRequest from "effect/Request" import type * as RequestResolver from "effect/RequestResolver" import type { Scope } from "effect/Scope" @@ -310,7 +310,7 @@ export const annotateHeaders: { * @since 1.0.0 * @category headers */ -export const schemaHeaders = , A>( +export const schemaHeaders = , A>( schema: Schema.Schema ): Effect.Effect => { const decode = Schema.decodeUnknown(schema) diff --git a/packages/rpc/test/Router.test.ts b/packages/rpc/test/Router.test.ts index d491580e1d..915fb1b709 100644 --- a/packages/rpc/test/Router.test.ts +++ b/packages/rpc/test/Router.test.ts @@ -4,11 +4,11 @@ import * as Router from "@effect/rpc/Router" import * as Rpc from "@effect/rpc/Rpc" import { Schema } from "@effect/schema" import * as S from "@effect/schema/Schema" +import * as Array from "effect/Array" import * as Chunk from "effect/Chunk" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import { flow, pipe } from "effect/Function" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Stream from "effect/Stream" import { assert, describe, expect, it, test } from "vitest" @@ -129,9 +129,9 @@ const handlerArray = (u: ReadonlyArray) => }))).pipe( Stream.runCollect, Effect.map(flow( - ReadonlyArray.fromIterable, - ReadonlyArray.map(([, response]) => response), - ReadonlyArray.filter((_): _ is S.ExitEncoded => Array.isArray(_) === false) + Array.fromIterable, + Array.map(([, response]) => response), + Array.filter((_): _ is S.ExitEncoded => Array.isArray(_) === false) )) ) const handlerEffectArray = (u: ReadonlyArray) => @@ -142,7 +142,7 @@ const handlerEffectArray = (u: ReadonlyArray) => sampled: true, headers: {} }))).pipe( - Effect.map(ReadonlyArray.filter((_): _ is S.ExitEncoded => Array.isArray(_) === false)) + Effect.map(Array.filter((_): _ is S.ExitEncoded => Array.isArray(_) === false)) ) const resolver = Resolver.make(handler)() const resolverEffect = ResolverNoStream.make(handlerEffect)() diff --git a/packages/schema/benchmark/union.ts b/packages/schema/benchmark/union.ts index 3bc9545ea0..59e03a4112 100644 --- a/packages/schema/benchmark/union.ts +++ b/packages/schema/benchmark/union.ts @@ -1,7 +1,7 @@ import type { ParseOptions } from "@effect/schema/AST" import * as ParseResult from "@effect/schema/ParseResult" import * as S from "@effect/schema/Schema" -import * as RA from "effect/ReadonlyArray" +import * as RA from "effect/Array" import { Bench } from "tinybench" import { z } from "zod" diff --git a/packages/schema/src/AST.ts b/packages/schema/src/AST.ts index fb5209b750..6493ca8a86 100644 --- a/packages/schema/src/AST.ts +++ b/packages/schema/src/AST.ts @@ -2,6 +2,7 @@ * @since 1.0.0 */ +import * as Array from "effect/Array" import type { Effect } from "effect/Effect" import { dual, identity } from "effect/Function" import { globalValue } from "effect/GlobalValue" @@ -10,7 +11,6 @@ import * as Number from "effect/Number" import * as Option from "effect/Option" import * as Order from "effect/Order" import * as Predicate from "effect/Predicate" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as regexp from "effect/RegExp" import type { Concurrency } from "effect/Types" import * as errors_ from "./internal/errors.js" @@ -55,7 +55,7 @@ export type AST = * @category annotations * @since 1.0.0 */ -export type BrandAnnotation = ReadonlyArray.NonEmptyReadonlyArray +export type BrandAnnotation = Array.NonEmptyReadonlyArray /** * @category annotations @@ -127,7 +127,7 @@ export const DescriptionAnnotationId = Symbol.for("@effect/schema/annotation/Des * @category annotations * @since 1.0.0 */ -export type ExamplesAnnotation = ReadonlyArray.NonEmptyReadonlyArray +export type ExamplesAnnotation = Array.NonEmptyReadonlyArray /** * @category annotations @@ -1003,7 +1003,7 @@ export class TemplateLiteral implements Annotated { spans: ReadonlyArray, annotations: Annotations = {} ): TemplateLiteral | Literal => - ReadonlyArray.isNonEmptyReadonlyArray(spans) ? + Array.isNonEmptyReadonlyArray(spans) ? new TemplateLiteral(head, spans, annotations) : new Literal(head) @@ -1013,7 +1013,7 @@ export class TemplateLiteral implements Annotated { readonly _tag = "TemplateLiteral" private constructor( readonly head: string, - readonly spans: ReadonlyArray.NonEmptyReadonlyArray, + readonly spans: Array.NonEmptyReadonlyArray, readonly annotations: Annotations = {} ) {} /** @@ -1120,7 +1120,7 @@ export class TupleType implements Annotated { const formatTuple = (ast: TupleType): string => { const formattedElements = ast.elements.map(String) .join(", ") - return ReadonlyArray.matchLeft(ast.rest, { + return Array.matchLeft(ast.rest, { onEmpty: () => `readonly [${formattedElements}]`, onNonEmpty: (head, tail) => { const formattedHead = String(head) @@ -1336,7 +1336,7 @@ export type Members = readonly [A, A, ...Array] const removeNevers = (candidates: ReadonlyArray): Array => candidates.filter((ast) => !(ast === neverKeyword)) -const sortCandidates = ReadonlyArray.sort( +const sortCandidates = Array.sort( Order.mapInput(Number.Order, (ast: AST) => { switch (ast._tag) { case "AnyKeyword": @@ -1365,7 +1365,7 @@ const literalMap = { /** @internal */ export const flatten = (candidates: ReadonlyArray): Array => - ReadonlyArray.flatMap(candidates, (ast) => isUnion(ast) ? flatten(ast.types) : [ast]) + Array.flatMap(candidates, (ast) => isUnion(ast) ? flatten(ast.types) : [ast]) /** @internal */ export const unify = (candidates: ReadonlyArray): Array => { @@ -1905,7 +1905,7 @@ export const getPropertyKeyIndexedAccess = (ast: AST, name: PropertyKey): Proper break } case "TypeLiteral": { - const ops = ReadonlyArray.findFirst(ast.propertySignatures, (ps) => ps.name === name) + const ops = Array.findFirst(ast.propertySignatures, (ps) => ps.name === name) if (Option.isSome(ops)) { return ops.value } else { @@ -1963,7 +1963,7 @@ const getPropertyKeys = (ast: AST): Array => { return getPropertyKeys(ast.f()) case "Union": return ast.types.slice(1).reduce( - (out: Array, ast) => ReadonlyArray.intersection(out, getPropertyKeys(ast)), + (out: Array, ast) => Array.intersection(out, getPropertyKeys(ast)), getPropertyKeys(ast.types[0]) ) case "Transformation": @@ -2041,7 +2041,7 @@ export const pick = (ast: AST, keys: ReadonlyArray): TypeLiteral | return new Transformation( pick(ast.from, fromKeys), pick(ast.to, keys), - ReadonlyArray.isNonEmptyReadonlyArray(ts) ? + Array.isNonEmptyReadonlyArray(ts) ? new TypeLiteralTransformation(ts) : composeTransformation ) @@ -2080,7 +2080,7 @@ export const partial = (ast: AST, options?: { readonly exact: true }): AST => { case "TupleType": return new TupleType( ast.elements.map((e) => new Element(exact ? e.type : orUndefined(e.type), true)), - ReadonlyArray.match(ast.rest, { + Array.match(ast.rest, { onEmpty: () => ast.rest, onNonEmpty: (rest) => [Union.make([...rest, undefinedKeyword])] }), @@ -2280,13 +2280,13 @@ const createJSONIdentifierAnnotation = (annotated: Annotated): Annotations | und }) function changeMap( - as: ReadonlyArray.NonEmptyReadonlyArray, + as: Array.NonEmptyReadonlyArray, f: (a: A) => A -): ReadonlyArray.NonEmptyReadonlyArray +): Array.NonEmptyReadonlyArray function changeMap(as: ReadonlyArray, f: (a: A) => A): ReadonlyArray function changeMap(as: ReadonlyArray, f: (a: A) => A): ReadonlyArray { let changed = false - const out: Array = new Array(as.length) + const out = Array.allocate(as.length) as Array for (let i = 0; i < as.length; i++) { const a = as[i] const fa = f(a) @@ -2387,11 +2387,11 @@ export const getCardinality = (ast: AST): number => { } } -const sortPropertySignatures = ReadonlyArray.sort( +const sortPropertySignatures = Array.sort( Order.mapInput(Number.Order, (ps: PropertySignature) => getCardinality(ps.type)) ) -const sortIndexSignatures = ReadonlyArray.sort( +const sortIndexSignatures = Array.sort( Order.mapInput(Number.Order, (is: IndexSignature) => { switch (getParameterBase(is.parameter)._tag) { case "StringKeyword": @@ -2471,11 +2471,11 @@ export const getParameterBase = ( } } -const equalsTemplateLiteralSpan = ReadonlyArray.getEquivalence((self, that) => +const equalsTemplateLiteralSpan = Array.getEquivalence((self, that) => self.type._tag === that.type._tag && self.literal === that.literal ) -const equalsEnums = ReadonlyArray.getEquivalence((self, that) => +const equalsEnums = Array.getEquivalence((self, that) => that[0] === self[0] && that[1] === self[1] ) @@ -2512,7 +2512,7 @@ const equals = (self: AST, that: AST) => { } } -const intersection = ReadonlyArray.intersectionWith(equals) +const intersection = Array.intersectionWith(equals) const _keyof = (ast: AST): Array => { switch (ast._tag) { diff --git a/packages/schema/src/Arbitrary.ts b/packages/schema/src/Arbitrary.ts index 1a63c42831..704415c722 100644 --- a/packages/schema/src/Arbitrary.ts +++ b/packages/schema/src/Arbitrary.ts @@ -2,9 +2,9 @@ * @since 1.0.0 */ +import * as Array from "effect/Array" import * as Option from "effect/Option" import * as Predicate from "effect/Predicate" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as AST from "./AST.js" import * as FastCheck from "./FastCheck.js" import * as errors_ from "./internal/errors.js" @@ -211,7 +211,7 @@ const go = (ast: AST.AST, options: Options): LazyArbitrary => { // --------------------------------------------- // handle rest element // --------------------------------------------- - if (ReadonlyArray.isNonEmptyReadonlyArray(rest)) { + if (Array.isNonEmptyReadonlyArray(rest)) { const [head, ...tail] = rest const arb = head(fc) const constraints = options.constraints diff --git a/packages/schema/src/ArrayFormatter.ts b/packages/schema/src/ArrayFormatter.ts index 5f22326938..f56e4ba588 100644 --- a/packages/schema/src/ArrayFormatter.ts +++ b/packages/schema/src/ArrayFormatter.ts @@ -2,8 +2,8 @@ * @since 1.0.0 */ +import * as Array from "effect/Array" import * as Effect from "effect/Effect" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as ParseResult from "./ParseResult.js" import * as TreeFormatter from "./TreeFormatter.js" @@ -76,19 +76,19 @@ const go = ( return go(e, path) } }), - ReadonlyArray.flatten + Array.flatten )) case "TupleType": return getArray(e, path, () => Effect.map( Effect.forEach(e.errors, (index) => go(index.error, [...path, index.index])), - ReadonlyArray.flatten + Array.flatten )) case "TypeLiteral": return getArray(e, path, () => Effect.map( Effect.forEach(e.errors, (key) => go(key.error, [...path, key.key])), - ReadonlyArray.flatten + Array.flatten )) case "Transformation": case "Refinement": diff --git a/packages/schema/src/Equivalence.ts b/packages/schema/src/Equivalence.ts index 90ee179ea5..a60acb6b68 100644 --- a/packages/schema/src/Equivalence.ts +++ b/packages/schema/src/Equivalence.ts @@ -2,11 +2,11 @@ * @since 1.0.0 */ +import * as Array from "effect/Array" import * as Equal from "effect/Equal" import * as Equivalence from "effect/Equivalence" import * as Option from "effect/Option" import * as Predicate from "effect/Predicate" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as AST from "./AST.js" import * as errors_ from "./internal/errors.js" import * as util_ from "./internal/util.js" @@ -104,7 +104,7 @@ const go = (ast: AST.AST): Equivalence.Equivalence => { // --------------------------------------------- // handle rest element // --------------------------------------------- - if (ReadonlyArray.isNonEmptyReadonlyArray(rest)) { + if (Array.isNonEmptyReadonlyArray(rest)) { const [head, ...tail] = rest for (; i < len - tail.length; i++) { if (!head(a[i], b[i])) { diff --git a/packages/schema/src/JSONSchema.ts b/packages/schema/src/JSONSchema.ts index 73ba56cc65..71edd03bd2 100644 --- a/packages/schema/src/JSONSchema.ts +++ b/packages/schema/src/JSONSchema.ts @@ -4,7 +4,7 @@ import * as Option from "effect/Option" import * as Predicate from "effect/Predicate" -import * as ReadonlyRecord from "effect/ReadonlyRecord" +import * as Record from "effect/Record" import * as AST from "./AST.js" import type * as Schema from "./Schema.js" @@ -219,7 +219,7 @@ export const make = (schema: Schema.Schema): JsonSchema7Root = delete $defs[id] } } - if (!ReadonlyRecord.isEmptyRecord($defs)) { + if (!Record.isEmptyRecord($defs)) { out.$defs = $defs } return out @@ -248,7 +248,7 @@ const empty = (): JsonSchema7 => ({ const $schema = "http://json-schema.org/draft-07/schema#" const getMeta = (annotated: AST.Annotated) => - ReadonlyRecord.getSomes({ + Record.getSomes({ description: AST.getDescriptionAnnotation(annotated), title: AST.getTitleAnnotation(annotated), examples: AST.getExamplesAnnotation(annotated), @@ -299,7 +299,7 @@ const go = (ast: AST.AST, $defs: Record, handleIdentifier: if (Option.isSome(identifier)) { const id = identifier.value const out = { $ref: get$ref(id) } - if (!ReadonlyRecord.has($defs, id)) { + if (!Record.has($defs, id)) { $defs[id] = out $defs[id] = go(ast, $defs, false) } diff --git a/packages/schema/src/ParseResult.ts b/packages/schema/src/ParseResult.ts index e86b034f5c..8f0c4e0d2c 100644 --- a/packages/schema/src/ParseResult.ts +++ b/packages/schema/src/ParseResult.ts @@ -2,6 +2,7 @@ * @since 1.0.0 */ +import * as Array from "effect/Array" import { TaggedError } from "effect/Data" import * as Effect from "effect/Effect" import * as Either from "effect/Either" @@ -11,7 +12,6 @@ import { globalValue } from "effect/GlobalValue" import * as Inspectable from "effect/Inspectable" import * as Option from "effect/Option" import * as Predicate from "effect/Predicate" -import * as ReadonlyArray from "effect/ReadonlyArray" import type { Concurrency, Mutable } from "effect/Types" import * as AST from "./AST.js" import * as util_ from "./internal/util.js" @@ -81,7 +81,7 @@ export class TupleType { constructor( readonly ast: AST.TupleType, readonly actual: unknown, - readonly errors: ReadonlyArray.NonEmptyReadonlyArray, + readonly errors: Array.NonEmptyReadonlyArray, readonly output: ReadonlyArray = [] ) {} } @@ -114,7 +114,7 @@ export class TypeLiteral { constructor( readonly ast: AST.TypeLiteral, readonly actual: unknown, - readonly errors: ReadonlyArray.NonEmptyReadonlyArray, + readonly errors: Array.NonEmptyReadonlyArray, readonly output: { readonly [x: string]: unknown } = {} ) {} } @@ -254,7 +254,7 @@ export class Union { constructor( readonly ast: AST.Union, readonly actual: unknown, - readonly errors: ReadonlyArray.NonEmptyReadonlyArray + readonly errors: Array.NonEmptyReadonlyArray ) {} } @@ -1023,7 +1023,7 @@ const go = (ast: AST.AST, isDecoding: boolean): Parser => { // --------------------------------------------- // handle rest element // --------------------------------------------- - if (ReadonlyArray.isNonEmptyReadonlyArray(rest)) { + if (Array.isNonEmptyReadonlyArray(rest)) { const [head, ...tail] = rest for (; i < len - tail.length; i++) { const te = head(input[i], options) @@ -1119,15 +1119,15 @@ const go = (ast: AST.AST, isDecoding: boolean): Parser => { // compute result // --------------------------------------------- const computeResult = ({ es, output }: State) => - ReadonlyArray.isNonEmptyArray(es) ? + Array.isNonEmptyArray(es) ? Either.left(new TupleType(ast, input, sortByIndex(es), sortByIndex(output))) : Either.right(sortByIndex(output)) if (queue && queue.length > 0) { const cqueue = queue return Effect.suspend(() => { const state: State = { - es: Array.from(es), - output: Array.from(output) + es: Array.copy(es), + output: Array.copy(output) } return Effect.flatMap( Effect.forEach(cqueue, (f) => f(state), { concurrency, batching, discard: true }), @@ -1339,14 +1339,14 @@ const go = (ast: AST.AST, isDecoding: boolean): Parser => { // compute result // --------------------------------------------- const computeResult = ({ es, output }: State) => - ReadonlyArray.isNonEmptyArray(es) ? + Array.isNonEmptyArray(es) ? Either.left(new TypeLiteral(ast, input, sortByIndex(es), output)) : Either.right(output) if (queue && queue.length > 0) { const cqueue = queue return Effect.suspend(() => { const state: State = { - es: Array.from(es), + es: Array.copy(es), output: Object.assign({}, output) } return Effect.flatMap( @@ -1471,7 +1471,7 @@ const go = (ast: AST.AST, isDecoding: boolean): Parser => { // compute result // --------------------------------------------- const computeResult = (es: State["es"]) => - ReadonlyArray.isNonEmptyArray(es) ? + Array.isNonEmptyArray(es) ? es.length === 1 && es[0][1]._tag === "Type" ? Either.left(es[0][1]) : Either.left(new Union(ast, input, sortByIndex(es))) : @@ -1481,7 +1481,7 @@ const go = (ast: AST.AST, isDecoding: boolean): Parser => { if (queue && queue.length > 0) { const cqueue = queue return Effect.suspend(() => { - const state: State = { es: Array.from(es) } + const state: State = { es: Array.copy(es) } return Effect.flatMap( Effect.forEach(cqueue, (f) => f(state), { concurrency, batching, discard: true }), () => { @@ -1630,8 +1630,8 @@ const handleForbidden = ( } function sortByIndex( - es: ReadonlyArray.NonEmptyArray<[number, T]> -): ReadonlyArray.NonEmptyArray + es: Array.NonEmptyArray<[number, T]> +): Array.NonEmptyArray function sortByIndex(es: Array<[number, T]>): Array function sortByIndex(es: Array<[number, any]>): any { return es.sort(([a], [b]) => a > b ? 1 : a < b ? -1 : 0).map(([_, a]) => a) diff --git a/packages/schema/src/Pretty.ts b/packages/schema/src/Pretty.ts index d1d011a527..a1a12a3fd4 100644 --- a/packages/schema/src/Pretty.ts +++ b/packages/schema/src/Pretty.ts @@ -1,8 +1,8 @@ /** * @since 1.0.0 */ +import * as Array from "effect/Array" import * as Option from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as AST from "./AST.js" import * as errors_ from "./internal/errors.js" import * as util_ from "./internal/util.js" @@ -116,7 +116,7 @@ export const match: AST.Match> = { // --------------------------------------------- // handle rest element // --------------------------------------------- - if (ReadonlyArray.isNonEmptyReadonlyArray(rest)) { + if (Array.isNonEmptyReadonlyArray(rest)) { const [head, ...tail] = rest for (; i < input.length - tail.length; i++) { output.push(head(input[i])) @@ -175,7 +175,7 @@ export const match: AST.Match> = { } } - return ReadonlyArray.isNonEmptyReadonlyArray(output) ? "{ " + output.join(", ") + " }" : "{}" + return Array.isNonEmptyReadonlyArray(output) ? "{ " + output.join(", ") + " }" : "{}" } }, "Union": (ast, go) => { diff --git a/packages/schema/src/Schema.ts b/packages/schema/src/Schema.ts index 9a8b599996..cd18af8d63 100644 --- a/packages/schema/src/Schema.ts +++ b/packages/schema/src/Schema.ts @@ -2,6 +2,7 @@ * @since 1.0.0 */ +import * as array_ from "effect/Array" import * as bigDecimal_ from "effect/BigDecimal" import * as bigInt_ from "effect/BigInt" import * as boolean_ from "effect/Boolean" @@ -28,7 +29,6 @@ import type * as Order from "effect/Order" import type { Pipeable } from "effect/Pipeable" import { pipeArguments } from "effect/Pipeable" import * as Predicate from "effect/Predicate" -import * as ReadonlyArray from "effect/ReadonlyArray" import * as Request from "effect/Request" import * as secret_ from "effect/Secret" import * as sortedSet_ from "effect/SortedSet" @@ -524,17 +524,16 @@ export const make = (ast: AST.AST): Schema => new * @category api interface * @since 1.0.0 */ -export interface Literal> +export interface Literal> extends Annotable, Literals[number]> { readonly literals: Readonly } -class LiteralImpl> - extends SchemaImpl +class LiteralImpl> extends SchemaImpl implements Literal { - static ast = >( + static ast = >( literals: Literals ): AST.AST => { return AST.isMembers(literals) @@ -555,7 +554,7 @@ class LiteralImpl>( +export function Literal>( ...literals: Literals ): Literal export function Literal(): Never @@ -565,7 +564,7 @@ export function Literal>( export function Literal>( ...literals: Literals ): Schema | Never { - return ReadonlyArray.isNonEmptyReadonlyArray(literals) ? new LiteralImpl(literals) : Never + return array_.isNonEmptyReadonlyArray(literals) ? new LiteralImpl(literals) : Never } /** @@ -585,7 +584,7 @@ export function Literal>( * @since 1.0.0 */ export const pickLiteral = - >(...literals: L) => + >(...literals: L) => (_schema: Schema): Literal<[...L]> => Literal(...literals) /** @@ -638,7 +637,7 @@ export const TemplateLiteral = }>> => { let types: ReadonlyArray = getTemplateLiterals(head.ast) for (const span of tail) { - types = ReadonlyArray.flatMap( + types = array_.flatMap( types, (a) => getTemplateLiterals(span.ast).map((b) => combineTemplateLiterals(a, b)) ) @@ -658,7 +657,7 @@ const combineTemplateLiterals = ( if (AST.isLiteral(b)) { return AST.TemplateLiteral.make( a.head, - ReadonlyArray.modifyNonEmptyLast( + array_.modifyNonEmptyLast( a.spans, (span) => new AST.TemplateLiteralSpan(span.type, span.literal + String(b.literal)) ) @@ -666,8 +665,8 @@ const combineTemplateLiterals = ( } return AST.TemplateLiteral.make( a.head, - ReadonlyArray.appendAll( - ReadonlyArray.modifyNonEmptyLast( + array_.appendAll( + array_.modifyNonEmptyLast( a.spans, (span) => new AST.TemplateLiteralSpan(span.type, span.literal + String(b.head)) ), @@ -686,7 +685,7 @@ const getTemplateLiterals = ( case "StringKeyword": return [AST.TemplateLiteral.make("", [new AST.TemplateLiteralSpan(ast, "")])] case "Union": - return ReadonlyArray.flatMap(ast.types, getTemplateLiterals) + return array_.flatMap(ast.types, getTemplateLiterals) default: throw new Error(`unsupported template literal span (${ast})`) } @@ -1048,7 +1047,7 @@ export function Union>( ): Schema, Schema.Encoded, Schema.Context> | Never { return AST.isMembers(members) ? new UnionImpl(members) - : ReadonlyArray.isNonEmptyReadonlyArray(members) + : array_.isNonEmptyReadonlyArray(members) ? members[0] as any : Never } @@ -1250,7 +1249,7 @@ export interface Tuple extends TupleType + Rest extends array_.NonEmptyReadonlyArray >(elements: Elements, ...rest: Rest): TupleType export function Tuple(...elements: Elements): Tuple export function Tuple(...args: ReadonlyArray): any { @@ -1948,7 +1947,7 @@ export declare namespace IndexSignature { /** * @since 1.0.0 */ - export type NonEmptyRecords = ReadonlyArray.NonEmptyReadonlyArray + export type NonEmptyRecords = array_.NonEmptyReadonlyArray /** * @since 1.0.0 @@ -2082,7 +2081,7 @@ class TypeLiteralImpl< pss.push(new AST.PropertySignature(key, field.ast, false, true)) } } - if (ReadonlyArray.isNonEmptyReadonlyArray(transformations)) { + if (array_.isNonEmptyReadonlyArray(transformations)) { const issFrom: Array = [] const issTo: Array = [] for (const r of records) { @@ -2437,8 +2436,8 @@ const intersectUnionMembers = ( ys: ReadonlyArray, path: ReadonlyArray ): Array => - ReadonlyArray.flatMap(xs, (x) => - ReadonlyArray.flatMap(ys, (y) => { + array_.flatMap(xs, (x) => + array_.flatMap(ys, (y) => { if (AST.isUnion(x)) { return intersectUnionMembers(x.types, AST.isUnion(y) ? y.types : [y], path) } else if (AST.isUnion(y)) { @@ -3521,7 +3520,7 @@ export const split = (separator: string): Schema, string> transform( $String, $Array($String), - { decode: string_.split(separator), encode: ReadonlyArray.join(separator) } + { decode: string_.split(separator), encode: array_.join(separator) } ) /** @@ -4693,7 +4692,7 @@ export const Uint8ArrayFromSelf: Schema = declare( identifier: "Uint8ArrayFromSelf", pretty: (): pretty_.Pretty => (u8arr) => `new Uint8Array(${JSON.stringify(Array.from(u8arr))})`, arbitrary: (): LazyArbitrary => (fc) => fc.uint8Array(), - equivalence: (): Equivalence.Equivalence => ReadonlyArray.getEquivalence(Equal.equals) as any + equivalence: (): Equivalence.Equivalence => array_.getEquivalence(Equal.equals) as any } ) @@ -4875,7 +4874,7 @@ export const head = (self: Schema, I, R>): Schema [], onSome: ReadonlyArray.of }) } + { decode: array_.head, encode: option_.match({ onNone: () => [], onSome: array_.of }) } ) /** @@ -4902,7 +4901,7 @@ export const headOrElse: { : fallback ? ParseResult.succeed(fallback()) : ParseResult.fail(new ParseResult.Type(ast, as)), - encode: (a) => ParseResult.succeed(ReadonlyArray.of(a)) + encode: (a) => ParseResult.succeed(array_.of(a)) } ) ) @@ -5436,7 +5435,7 @@ const readonlyMapEquivalence = ( key: Equivalence.Equivalence, value: Equivalence.Equivalence ): Equivalence.Equivalence> => { - const arrayEquivalence = ReadonlyArray.getEquivalence( + const arrayEquivalence = array_.getEquivalence( Equivalence.make<[K, V]>(([ka, va], [kb, vb]) => key(ka, kb) && value(va, vb)) ) return Equivalence.make((a, b) => arrayEquivalence(Array.from(a.entries()), Array.from(b.entries()))) @@ -5586,7 +5585,7 @@ const readonlySetPretty = (item: pretty_.Pretty): pretty_.Pretty( item: Equivalence.Equivalence ): Equivalence.Equivalence> => { - const arrayEquivalence = ReadonlyArray.getEquivalence(item) + const arrayEquivalence = array_.getEquivalence(item) return Equivalence.make((a, b) => arrayEquivalence(Array.from(a.values()), Array.from(b.values()))) } @@ -7167,7 +7166,7 @@ const hashSetPretty = (item: pretty_.Pretty): pretty_.Pretty( item: Equivalence.Equivalence ): Equivalence.Equivalence> => { - const arrayEquivalence = ReadonlyArray.getEquivalence(item) + const arrayEquivalence = array_.getEquivalence(item) return Equivalence.make((a, b) => arrayEquivalence(Array.from(a), Array.from(b))) } @@ -7264,7 +7263,7 @@ const hashMapEquivalence = ( key: Equivalence.Equivalence, value: Equivalence.Equivalence ): Equivalence.Equivalence> => { - const arrayEquivalence = ReadonlyArray.getEquivalence( + const arrayEquivalence = array_.getEquivalence( Equivalence.make<[K, V]>(([ka, va], [kb, vb]) => key(ka, kb) && value(va, vb)) ) return Equivalence.make((a, b) => arrayEquivalence(Array.from(a), Array.from(b))) @@ -7353,7 +7352,7 @@ const listPretty = (item: pretty_.Pretty): pretty_.Pretty> = const listEquivalence = ( item: Equivalence.Equivalence ): Equivalence.Equivalence> => { - const arrayEquivalence = ReadonlyArray.getEquivalence(item) + const arrayEquivalence = array_.getEquivalence(item) return Equivalence.make((a, b) => arrayEquivalence(Array.from(a), Array.from(b))) } diff --git a/packages/sql-sqlite-node/test/Resolver.test.ts b/packages/sql-sqlite-node/test/Resolver.test.ts index 13cf76cdfe..b5d595bae2 100644 --- a/packages/sql-sqlite-node/test/Resolver.test.ts +++ b/packages/sql-sqlite-node/test/Resolver.test.ts @@ -3,7 +3,7 @@ import { NodeFileSystem } from "@effect/platform-node" import * as Schema from "@effect/schema/Schema" import * as Sql from "@effect/sql-sqlite-node" import { assert, describe, it } from "@effect/vitest" -import { Effect, Option, ReadonlyArray } from "effect" +import { Array, Effect, Option } from "effect" const makeClient = Effect.gen(function*(_) { const fs = yield* _(FileSystem.FileSystem) @@ -17,7 +17,7 @@ const seededClient = Effect.gen(function*(_) { const sql = yield* _(makeClient) yield* _(sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`) yield* _( - Effect.forEach(ReadonlyArray.range(1, 100), (id) => sql`INSERT INTO test ${sql.insert({ id, name: `name${id}` })}`) + Effect.forEach(Array.range(1, 100), (id) => sql`INSERT INTO test ${sql.insert({ id, name: `name${id}` })}`) ) return sql }) diff --git a/packages/sql/src/Migrator.ts b/packages/sql/src/Migrator.ts index 4c82a9c9cb..dc30401eed 100644 --- a/packages/sql/src/Migrator.ts +++ b/packages/sql/src/Migrator.ts @@ -2,12 +2,12 @@ * @since 1.0.0 */ import { FileSystem } from "@effect/platform/FileSystem" +import * as Array from "effect/Array" import * as Data from "effect/Data" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" import * as Order from "effect/Order" -import * as ReadonlyArray from "effect/ReadonlyArray" import type { Client } from "./Client.js" import type { SqlError } from "./Error.js" @@ -278,15 +278,15 @@ export const fromGlob = ( ): Loader => pipe( Object.keys(migrations), - ReadonlyArray.filterMap((_) => Option.fromNullable(_.match(/^(?:.*\/)?(\d+)_([^.]+)\.(js|ts)$/))), - ReadonlyArray.map( + Array.filterMap((_) => Option.fromNullable(_.match(/^(?:.*\/)?(\d+)_([^.]+)\.(js|ts)$/))), + Array.map( ([key, id, name]): ResolvedMigration => [ Number(id), name, Effect.promise(() => migrations[key]()) ] ), - ReadonlyArray.sort(migrationOrder), + Array.sort(migrationOrder), Effect.succeed ) @@ -297,15 +297,15 @@ export const fromGlob = ( export const fromBabelGlob = (migrations: Record): Loader => pipe( Object.keys(migrations), - ReadonlyArray.filterMap((_) => Option.fromNullable(_.match(/^_(\d+)_([^.]+?)(Js|Ts)?$/))), - ReadonlyArray.map( + Array.filterMap((_) => Option.fromNullable(_.match(/^_(\d+)_([^.]+?)(Js|Ts)?$/))), + Array.map( ([key, id, name]): ResolvedMigration => [ Number(id), name, Effect.succeed(migrations[key]) ] ), - ReadonlyArray.sort(migrationOrder), + Array.sort(migrationOrder), Effect.succeed ) diff --git a/packages/typeclass/src/data/ReadonlyArray.ts b/packages/typeclass/src/data/Array.ts similarity index 68% rename from packages/typeclass/src/data/ReadonlyArray.ts rename to packages/typeclass/src/data/Array.ts index 9614993192..79e86ce2dc 100644 --- a/packages/typeclass/src/data/ReadonlyArray.ts +++ b/packages/typeclass/src/data/Array.ts @@ -4,11 +4,11 @@ * @since 1.0.0 */ +import * as ArrayInstances from "effect/Array" import type { Either } from "effect/Either" import { dual } from "effect/Function" import type { Kind, TypeLambda } from "effect/HKT" import type { Option } from "effect/Option" -import * as ReadonlyArray from "effect/ReadonlyArray" import type * as applicative from "../Applicative.js" import type * as chainable from "../Chainable.js" import * as covariant from "../Covariant.js" @@ -29,17 +29,17 @@ import * as semiProduct from "../SemiProduct.js" import type * as traversable from "../Traversable.js" import type * as traversableFilterable from "../TraversableFilterable.js" -const of = ReadonlyArray.of +const of = ArrayInstances.of -const map = ReadonlyArray.map +const map = ArrayInstances.map -const imap = covariant.imap(map) +const imap = covariant.imap(map) -const flatMap = ReadonlyArray.flatMap +const flatMap = ArrayInstances.flatMap const product = (self: ReadonlyArray, that: ReadonlyArray): ReadonlyArray<[A, B]> => { - if (ReadonlyArray.isEmptyReadonlyArray(self) || ReadonlyArray.isEmptyReadonlyArray(that)) { - return ReadonlyArray.empty() + if (ArrayInstances.isEmptyReadonlyArray(self) || ArrayInstances.isEmptyReadonlyArray(that)) { + return ArrayInstances.empty() } const out: Array<[A, B]> = [] for (let i = 0; i < self.length; i++) { @@ -50,7 +50,7 @@ const product = (self: ReadonlyArray, that: ReadonlyArray): Readonly return out } -const productMany = semiProduct.productMany(map, product) +const productMany = semiProduct.productMany(map, product) const traverse = (F: applicative.Applicative): { ( @@ -64,7 +64,7 @@ const traverse = (F: applicative.Applicative): { dual(2, ( self: Iterable, f: (a: A, i: number) => Kind - ): Kind> => F.productAll(ReadonlyArray.fromIterable(self).map(f))) + ): Kind> => F.productAll(ArrayInstances.fromIterable(self).map(f))) const traversePartitionMap = ( F: applicative.Applicative @@ -81,7 +81,7 @@ const traversePartitionMap = ( self: ReadonlyArray, f: (a: A) => Kind> ): Kind, Array]> => { - return F.map(traverse(F)(self, f), ReadonlyArray.separate) + return F.map(traverse(F)(self, f), ArrayInstances.separate) }) const traverseFilterMap = ( @@ -99,14 +99,14 @@ const traverseFilterMap = ( self: ReadonlyArray, f: (a: A) => Kind> ): Kind> => { - return F.map(traverse(F)(self, f), ReadonlyArray.getSomes) + return F.map(traverse(F)(self, f), ArrayInstances.getSomes) }) /** * @category instances * @since 1.0.0 */ -export const Of: of_.Of = { +export const Of: of_.Of = { of } @@ -114,7 +114,7 @@ export const Of: of_.Of = { * @category instances * @since 1.0.0 */ -export const Covariant: covariant.Covariant = { +export const Covariant: covariant.Covariant = { imap, map } @@ -123,7 +123,7 @@ export const Covariant: covariant.Covariant = { +export const Invariant: invariant.Invariant = { imap } @@ -131,7 +131,7 @@ export const Invariant: invariant.Invariant = { +export const Pointed: pointed.Pointed = { of, imap, map @@ -141,7 +141,7 @@ export const Pointed: pointed.Pointed = { * @category instances * @since 1.0.0 */ -export const FlatMap: flatMap_.FlatMap = { +export const FlatMap: flatMap_.FlatMap = { flatMap } @@ -149,7 +149,7 @@ export const FlatMap: flatMap_.FlatMap = * @category instances * @since 1.0.0 */ -export const Chainable: chainable.Chainable = { +export const Chainable: chainable.Chainable = { imap, map, flatMap @@ -159,16 +159,16 @@ export const Chainable: chainable.Chainable = { - partitionMap: ReadonlyArray.partitionMap, - filterMap: ReadonlyArray.filterMap +export const Filterable: filterable.Filterable = { + partitionMap: ArrayInstances.partitionMap, + filterMap: ArrayInstances.filterMap } /** * @category instances * @since 1.0.0 */ -export const Traversable: traversable.Traversable = { +export const Traversable: traversable.Traversable = { traverse: traverse as any } @@ -176,7 +176,7 @@ export const Traversable: traversable.Traversable = { +export const SemiProduct: semiProduct.SemiProduct = { imap, product, productMany @@ -187,7 +187,7 @@ export const SemiProduct: semiProduct.SemiProduct = { imap, map, @@ -199,15 +199,15 @@ export const SemiApplicative: semiApplicative.SemiApplicative< * @category instances * @since 1.0.0 */ -export const Product: product_.Product = { +export const Product: product_.Product = { of, imap, product, productMany, productAll: (collection) => { - const arrays = ReadonlyArray.fromIterable(collection) - return ReadonlyArray.isEmptyReadonlyArray(arrays) ? - ReadonlyArray.empty() : + const arrays = ArrayInstances.fromIterable(collection) + return ArrayInstances.isEmptyReadonlyArray(arrays) ? + ArrayInstances.empty() : SemiProduct.productMany(arrays[0], arrays.slice(1)) } } @@ -216,7 +216,7 @@ export const Product: product_.Product = * @category instances * @since 1.0.0 */ -export const Applicative: applicative.Applicative = { +export const Applicative: applicative.Applicative = { imap, of, map, @@ -229,7 +229,7 @@ export const Applicative: applicative.Applicative = { +export const Monad: monad.Monad = { imap, of, map, @@ -240,8 +240,8 @@ export const Monad: monad.Monad = { * @category instances * @since 1.0.0 */ -export const Foldable: foldable.Foldable = { - reduce: ReadonlyArray.reduce +export const Foldable: foldable.Foldable = { + reduce: ArrayInstances.reduce } /** @@ -249,7 +249,7 @@ export const Foldable: foldable.Foldable * @since 1.0.0 */ export const TraversableFilterable: traversableFilterable.TraversableFilterable< - ReadonlyArray.ReadonlyArrayTypeLambda + ArrayInstances.ReadonlyArrayTypeLambda > = { traversePartitionMap: traversePartitionMap as any, traverseFilterMap: traverseFilterMap as any diff --git a/packages/typeclass/src/data/Identity.ts b/packages/typeclass/src/data/Identity.ts index 5c6690dd14..2f0ff948a6 100644 --- a/packages/typeclass/src/data/Identity.ts +++ b/packages/typeclass/src/data/Identity.ts @@ -1,9 +1,9 @@ /** * @since 1.0.0 */ +import * as readonlyArray from "effect/Array" import { dual, identity } from "effect/Function" import type { Kind, TypeLambda } from "effect/HKT" -import * as readonlyArray from "effect/ReadonlyArray" import type * as applicative from "../Applicative.js" import type * as chainable from "../Chainable.js" import * as covariant from "../Covariant.js" diff --git a/packages/typeclass/src/data/ReadonlyRecord.ts b/packages/typeclass/src/data/Record.ts similarity index 62% rename from packages/typeclass/src/data/ReadonlyRecord.ts rename to packages/typeclass/src/data/Record.ts index be3f8ad8bf..5a3fe0fb39 100644 --- a/packages/typeclass/src/data/ReadonlyRecord.ts +++ b/packages/typeclass/src/data/Record.ts @@ -1,11 +1,11 @@ /** * @since 1.0.0 */ -import type { Either } from "effect/Either" +import type { Either as RecordInstances } from "effect/Either" import { dual } from "effect/Function" import type { Kind, TypeLambda } from "effect/HKT" import type { Option } from "effect/Option" -import * as ReadonlyRecord from "effect/ReadonlyRecord" +import * as Record from "effect/Record" import type * as applicative from "../Applicative.js" import * as covariant from "../Covariant.js" import type * as filterable from "../Filterable.js" @@ -38,47 +38,47 @@ const traversePartitionMap = ( F: applicative.Applicative ): { ( - f: (a: A) => Kind> + f: (a: A) => Kind> ): ( - self: ReadonlyRecord.ReadonlyRecord + self: Record.ReadonlyRecord ) => Kind< F, R, O, E, [ - Record, B>, - Record, C> + Record, B>, + Record, C> ] > ( - self: ReadonlyRecord.ReadonlyRecord, - f: (a: A) => Kind> + self: Record.ReadonlyRecord, + f: (a: A) => Kind> ): Kind< F, R, O, E, [ - Record, B>, - Record, C> + Record, B>, + Record, C> ] > } => dual(2, ( - self: ReadonlyRecord.ReadonlyRecord, - f: (a: A) => Kind> + self: Record.ReadonlyRecord, + f: (a: A) => Kind> ): Kind< F, R, O, E, [ - Record, B>, - Record, C> + Record, B>, + Record, C> ] > => { - return F.map(traverse(F)(self, f), ReadonlyRecord.separate) + return F.map(traverse(F)(self, f), Record.separate) }) const traverseFilterMap = ( @@ -87,38 +87,36 @@ const traverseFilterMap = ( ( f: (a: A) => Kind> ): ( - self: ReadonlyRecord.ReadonlyRecord - ) => Kind, B>> + self: Record.ReadonlyRecord + ) => Kind, B>> ( - self: ReadonlyRecord.ReadonlyRecord, + self: Record.ReadonlyRecord, f: (a: A) => Kind> - ): Kind, B>> + ): Kind, B>> } => dual(2, ( - self: ReadonlyRecord.ReadonlyRecord, + self: Record.ReadonlyRecord, f: (a: A) => Kind> - ): Kind, B>> => { - return F.map(traverse(F)(self, f), ReadonlyRecord.getSomes) + ): Kind, B>> => { + return F.map(traverse(F)(self, f), Record.getSomes) }) -const _map: covariant.Covariant>["map"] = ReadonlyRecord.map +const _map: covariant.Covariant>["map"] = Record.map -const _imap = covariant.imap>(_map) +const _imap = covariant.imap>(_map) -const _partitionMap: filterable.Filterable>["partitionMap"] = - ReadonlyRecord.partitionMap +const _partitionMap: filterable.Filterable>["partitionMap"] = Record.partitionMap -const _filterMap: filterable.Filterable>["filterMap"] = - ReadonlyRecord.filterMap +const _filterMap: filterable.Filterable>["filterMap"] = Record.filterMap -const _traverse: traversable.Traversable>["traverse"] = traverse +const _traverse: traversable.Traversable>["traverse"] = traverse const _traversePartitionMap: traversableFilterable.TraversableFilterable< - ReadonlyRecord.ReadonlyRecordTypeLambda + Record.ReadonlyRecordTypeLambda >["traversePartitionMap"] = traversePartitionMap const _traverseFilterMap: traversableFilterable.TraversableFilterable< - ReadonlyRecord.ReadonlyRecordTypeLambda + Record.ReadonlyRecordTypeLambda >["traverseFilterMap"] = traverseFilterMap /** @@ -126,7 +124,7 @@ const _traverseFilterMap: traversableFilterable.TraversableFilterable< * @since 1.0.0 */ export const getCovariant = (): covariant.Covariant< - ReadonlyRecord.ReadonlyRecordTypeLambda + Record.ReadonlyRecordTypeLambda > => ({ imap: _imap, map: _map @@ -143,7 +141,7 @@ export const Covariant = getCovariant() * @since 1.0.0 */ export const getInvariant = (): invariant.Invariant< - ReadonlyRecord.ReadonlyRecordTypeLambda + Record.ReadonlyRecordTypeLambda > => ({ imap: _imap }) @@ -159,7 +157,7 @@ export const Invariant = getInvariant() * @since 1.0.0 */ export const getFilterable = (): filterable.Filterable< - ReadonlyRecord.ReadonlyRecordTypeLambda + Record.ReadonlyRecordTypeLambda > => ({ partitionMap: _partitionMap, filterMap: _filterMap @@ -176,7 +174,7 @@ export const Filterable = getFilterable() * @since 1.0.0 */ export const getTraversable = (): traversable.Traversable< - ReadonlyRecord.ReadonlyRecordTypeLambda + Record.ReadonlyRecordTypeLambda > => ({ traverse: _traverse }) @@ -192,7 +190,7 @@ export const Traversable = getTraversable() * @since 1.0.0 */ export const getTraversableFilterable = (): traversableFilterable.TraversableFilterable< - ReadonlyRecord.ReadonlyRecordTypeLambda + Record.ReadonlyRecordTypeLambda > => ({ traversePartitionMap: _traversePartitionMap, traverseFilterMap: _traverseFilterMap diff --git a/packages/typeclass/test/Bicovariant.test.ts b/packages/typeclass/test/Bicovariant.test.ts index f40d6b5cac..d65b421c0f 100644 --- a/packages/typeclass/test/Bicovariant.test.ts +++ b/packages/typeclass/test/Bicovariant.test.ts @@ -1,6 +1,6 @@ import * as _ from "@effect/typeclass/Bicovariant" +import * as ArrayInstances from "@effect/typeclass/data/Array" import * as EitherInstances from "@effect/typeclass/data/Either" -import * as ReadonlyArrayInstances from "@effect/typeclass/data/ReadonlyArray" import * as E from "effect/Either" import { pipe } from "effect/Function" import { describe, it } from "vitest" @@ -22,7 +22,7 @@ describe.concurrent("Bicovariant", () => { }) it("bimapComposition", () => { - const bimap = _.bimapComposition(ReadonlyArrayInstances.Covariant, EitherInstances.Bicovariant) + const bimap = _.bimapComposition(ArrayInstances.Covariant, EitherInstances.Bicovariant) const f = (s: string) => s.length const g = (n: number) => n * 2 U.deepStrictEqual(bimap([E.right(1), E.right(2), E.left("eee")], f, g), [ diff --git a/packages/typeclass/test/Covariant.test.ts b/packages/typeclass/test/Covariant.test.ts index 57dc43d028..9fa8a941b2 100644 --- a/packages/typeclass/test/Covariant.test.ts +++ b/packages/typeclass/test/Covariant.test.ts @@ -1,6 +1,6 @@ import * as _ from "@effect/typeclass/Covariant" +import * as ArrayInstances from "@effect/typeclass/data/Array" import * as OptionInstances from "@effect/typeclass/data/Option" -import * as ReadonlyArrayInstances from "@effect/typeclass/data/ReadonlyArray" import { pipe } from "effect/Function" import * as O from "effect/Option" import { describe, it } from "vitest" @@ -9,7 +9,7 @@ import * as U from "./util.js" describe.concurrent("Covariant", () => { it("mapComposition", () => { - const map = _.mapComposition(ReadonlyArrayInstances.Covariant, ReadonlyArrayInstances.Covariant) + const map = _.mapComposition(ArrayInstances.Covariant, ArrayInstances.Covariant) const f = (a: string) => a + "!" U.deepStrictEqual(map([], f), []) U.deepStrictEqual(map([[]], f), [[]]) diff --git a/packages/typeclass/test/Filterable.test.ts b/packages/typeclass/test/Filterable.test.ts index 06ecb3ff73..178969a0d6 100644 --- a/packages/typeclass/test/Filterable.test.ts +++ b/packages/typeclass/test/Filterable.test.ts @@ -1,5 +1,5 @@ +import * as ArrayInstances from "@effect/typeclass/data/Array" import * as OptionInstances from "@effect/typeclass/data/Option" -import * as ReadonlyArrayInstances from "@effect/typeclass/data/ReadonlyArray" import * as _ from "@effect/typeclass/Filterable" import * as E from "effect/Either" import { pipe } from "effect/Function" @@ -10,7 +10,7 @@ import * as U from "./util.js" describe.concurrent("Filterable", () => { it("filterMapComposition", () => { const filterMap = _.filterMapComposition( - ReadonlyArrayInstances.Covariant, + ArrayInstances.Covariant, OptionInstances.Filterable ) const f = (s: string) => s.length > 1 ? O.some(s.length) : O.none() @@ -22,7 +22,7 @@ describe.concurrent("Filterable", () => { it("partitionMapComposition", () => { const partitionMap = _.partitionMapComposition( - ReadonlyArrayInstances.Covariant, + ArrayInstances.Covariant, OptionInstances.Filterable ) const f = (s: string) => s.length > 1 ? E.right(s.length) : E.left(s + "!") @@ -33,7 +33,7 @@ describe.concurrent("Filterable", () => { }) it("filter", () => { - const filter = _.filter(ReadonlyArrayInstances.Filterable) + const filter = _.filter(ArrayInstances.Filterable) const f = filter((n: number) => n > 0) U.deepStrictEqual(pipe([], f), []) U.deepStrictEqual(pipe([1], f), [1]) @@ -42,7 +42,7 @@ describe.concurrent("Filterable", () => { }) it("partition", () => { - const partition = _.partition(ReadonlyArrayInstances.Filterable) + const partition = _.partition(ArrayInstances.Filterable) const f = partition((n: number) => n > 0) U.deepStrictEqual(pipe([], f), [[], []]) U.deepStrictEqual(pipe([1], f), [[], [1]]) @@ -51,7 +51,7 @@ describe.concurrent("Filterable", () => { }) it("compact", () => { - const compact = _.compact(ReadonlyArrayInstances.Filterable) + const compact = _.compact(ArrayInstances.Filterable) assert.deepStrictEqual(compact([]), []) assert.deepStrictEqual(compact([O.some(1), O.some(2), O.some(3)]), [ 1, @@ -65,7 +65,7 @@ describe.concurrent("Filterable", () => { }) it("separate", () => { - const separate = _.separate(ReadonlyArrayInstances.Filterable) + const separate = _.separate(ArrayInstances.Filterable) U.deepStrictEqual(pipe([], separate), [[], []]) U.deepStrictEqual(pipe([E.right(1), E.left("e"), E.right(2)], separate), [ ["e"], diff --git a/packages/typeclass/test/Foldable.test.ts b/packages/typeclass/test/Foldable.test.ts index d3e629a1e3..14456de523 100644 --- a/packages/typeclass/test/Foldable.test.ts +++ b/packages/typeclass/test/Foldable.test.ts @@ -1,6 +1,6 @@ +import * as ArrayInstances from "@effect/typeclass/data/Array" import * as NumberInstances from "@effect/typeclass/data/Number" import * as OptionInstances from "@effect/typeclass/data/Option" -import * as ReadonlyArrayInstances from "@effect/typeclass/data/ReadonlyArray" import * as Foldable from "@effect/typeclass/Foldable" import { pipe } from "effect/Function" import * as O from "effect/Option" @@ -10,8 +10,8 @@ import * as U from "./util.js" describe.concurrent("Foldable", () => { it("reduceComposition", () => { const reduce = Foldable.reduceComposition( - ReadonlyArrayInstances.Foldable, - ReadonlyArrayInstances.Foldable + ArrayInstances.Foldable, + ArrayInstances.Foldable ) const f = (b: string, a: string) => b + a U.deepStrictEqual(reduce([], "-", f), "-") @@ -32,12 +32,12 @@ describe.concurrent("Foldable", () => { }) it("combineMap", () => { - const combineMap = Foldable.combineMap(ReadonlyArrayInstances.Foldable) + const combineMap = Foldable.combineMap(ArrayInstances.Foldable) U.deepStrictEqual(combineMap(NumberInstances.MonoidSum)([1, 2, 3], U.double), 12) }) it("reduceKind", () => { - const reduceKind = Foldable.reduceKind(ReadonlyArrayInstances.Foldable)(OptionInstances.Monad) + const reduceKind = Foldable.reduceKind(ArrayInstances.Foldable)(OptionInstances.Monad) U.deepStrictEqual(reduceKind([], "-", () => O.none()), O.some("-")) U.deepStrictEqual(reduceKind(["a"], "-", () => O.none()), O.none()) U.deepStrictEqual( @@ -51,7 +51,7 @@ describe.concurrent("Foldable", () => { }) it("coproductMapKind", () => { - const coproductMapKind = Foldable.coproductMapKind(ReadonlyArrayInstances.Foldable)( + const coproductMapKind = Foldable.coproductMapKind(ArrayInstances.Foldable)( OptionInstances.Alternative ) U.deepStrictEqual(pipe([], coproductMapKind(() => O.none())), O.none()) diff --git a/packages/typeclass/test/Of.test.ts b/packages/typeclass/test/Of.test.ts index a4d249d2f4..6822faea05 100644 --- a/packages/typeclass/test/Of.test.ts +++ b/packages/typeclass/test/Of.test.ts @@ -1,7 +1,7 @@ import * as OptionInstances from "@effect/typeclass/data/Option" import * as _ from "@effect/typeclass/Of" +import * as RA from "effect/Array" import * as O from "effect/Option" -import * as RA from "effect/ReadonlyArray" import { describe, it } from "vitest" import * as U from "./util.js" diff --git a/packages/typeclass/test/SemiProduct.test.ts b/packages/typeclass/test/SemiProduct.test.ts index ad4e6cfcde..5a51a380f3 100644 --- a/packages/typeclass/test/SemiProduct.test.ts +++ b/packages/typeclass/test/SemiProduct.test.ts @@ -1,7 +1,7 @@ +import * as ArrayInstances from "@effect/typeclass/data/Array" import * as NumberInstances from "@effect/typeclass/data/Number" import * as OptionInstances from "@effect/typeclass/data/Option" import * as PredicateInstances from "@effect/typeclass/data/Predicate" -import * as ReadonlyArrayInstances from "@effect/typeclass/data/ReadonlyArray" import * as StringInstances from "@effect/typeclass/data/String" import * as of_ from "@effect/typeclass/Of" import * as semiApplicative from "@effect/typeclass/SemiApplicative" @@ -82,10 +82,10 @@ describe.concurrent("SemiProduct", () => { U.deepStrictEqual(actual, expected) } - assertSameResult(ReadonlyArrayInstances.SemiApplicative)([])([]) - assertSameResult(ReadonlyArrayInstances.SemiApplicative)([])([1, 2, 3]) - assertSameResult(ReadonlyArrayInstances.SemiApplicative)([[4]])([1, 2, 3]) - assertSameResult(ReadonlyArrayInstances.SemiApplicative)([[4, 5, 6], [7, 8], [9, 10, 11]])([ + assertSameResult(ArrayInstances.SemiApplicative)([])([]) + assertSameResult(ArrayInstances.SemiApplicative)([])([1, 2, 3]) + assertSameResult(ArrayInstances.SemiApplicative)([[4]])([1, 2, 3]) + assertSameResult(ArrayInstances.SemiApplicative)([[4, 5, 6], [7, 8], [9, 10, 11]])([ 1, 2, 3 @@ -95,7 +95,7 @@ describe.concurrent("SemiProduct", () => { describe.concurrent("productComposition", () => { it("ReadonlyArray", () => { const product = _.productComposition( - ReadonlyArrayInstances.SemiApplicative, + ArrayInstances.SemiApplicative, OptionInstances.SemiProduct ) U.deepStrictEqual(product([], [O.none()]), []) @@ -124,7 +124,7 @@ describe.concurrent("SemiProduct", () => { describe.concurrent("productManyComposition", () => { it("ReadonlyArray", () => { const productMany = _.productManyComposition( - ReadonlyArrayInstances.SemiApplicative, + ArrayInstances.SemiApplicative, OptionInstances.SemiProduct ) expect(productMany([O.some(1), O.none()], [])).toEqual([ diff --git a/packages/typeclass/test/Traversable.test.ts b/packages/typeclass/test/Traversable.test.ts index 4c109538b1..6d3372fc7a 100644 --- a/packages/typeclass/test/Traversable.test.ts +++ b/packages/typeclass/test/Traversable.test.ts @@ -1,5 +1,5 @@ +import * as ArrayInstances from "@effect/typeclass/data/Array" import * as OptionInstances from "@effect/typeclass/data/Option" -import * as ReadonlyArrayInstances from "@effect/typeclass/data/ReadonlyArray" import * as Traversable from "@effect/typeclass/Traversable" import { pipe } from "effect/Function" import * as O from "effect/Option" @@ -9,8 +9,8 @@ import * as U from "./util.js" describe.concurrent("Traversable", () => { it("traverseComposition", () => { const traverse = Traversable.traverseComposition( - ReadonlyArrayInstances.Traversable, - ReadonlyArrayInstances.Traversable + ArrayInstances.Traversable, + ArrayInstances.Traversable )(OptionInstances.Applicative) U.deepStrictEqual( traverse([[1, 2], [3]], (a) => (a > 0 ? O.some(a) : O.none())), @@ -23,7 +23,7 @@ describe.concurrent("Traversable", () => { }) it("sequence", () => { - const sequence = Traversable.sequence(ReadonlyArrayInstances.Traversable)( + const sequence = Traversable.sequence(ArrayInstances.Traversable)( OptionInstances.Applicative ) U.deepStrictEqual(sequence([O.some(1), O.some(2)]), O.some([1, 2])) @@ -31,7 +31,7 @@ describe.concurrent("Traversable", () => { }) it("traverseTap", () => { - const traverseTap = Traversable.traverseTap(ReadonlyArrayInstances.Traversable)( + const traverseTap = Traversable.traverseTap(ArrayInstances.Traversable)( OptionInstances.Applicative ) U.deepStrictEqual( diff --git a/packages/typeclass/test/TraversableFilterable.test.ts b/packages/typeclass/test/TraversableFilterable.test.ts index f70bc28d19..3508311f17 100644 --- a/packages/typeclass/test/TraversableFilterable.test.ts +++ b/packages/typeclass/test/TraversableFilterable.test.ts @@ -1,5 +1,5 @@ +import * as ArrayInstances from "@effect/typeclass/data/Array" import * as OptionInstances from "@effect/typeclass/data/Option" -import * as ReadonlyArrayInstances from "@effect/typeclass/data/ReadonlyArray" import * as _ from "@effect/typeclass/TraversableFilterable" import * as E from "effect/Either" import * as O from "effect/Option" @@ -12,9 +12,9 @@ describe.concurrent("TraversableFilterable", () => { self: ReadonlyArray, f: (a: A) => O.Option> ) => O.Option<[ReadonlyArray, ReadonlyArray]> = _.traversePartitionMap({ - ...ReadonlyArrayInstances.Traversable, - ...ReadonlyArrayInstances.Covariant, - ...ReadonlyArrayInstances.Filterable + ...ArrayInstances.Traversable, + ...ArrayInstances.Covariant, + ...ArrayInstances.Filterable })(OptionInstances.Applicative) const f = (s: string) => s.length > 1 ? O.some(E.right(s)) : s.length > 0 ? O.some(E.left(s)) : O.none() expect(traversePartitionMap([], f)).toEqual(O.some([[], []])) @@ -30,8 +30,8 @@ describe.concurrent("TraversableFilterable", () => { self: ReadonlyArray, f: (a: A) => O.Option> ) => O.Option> = _.traverseFilterMap({ - ...ReadonlyArrayInstances.Traversable, - ...ReadonlyArrayInstances.Filterable + ...ArrayInstances.Traversable, + ...ArrayInstances.Filterable })(OptionInstances.Applicative) const f = (s: string) => s.length > 1 ? O.some(O.some(s)) : s.length > 0 ? O.some(O.none()) : O.none() assert.deepStrictEqual(traverseFilterMap([], f), O.some([])) @@ -47,7 +47,7 @@ describe.concurrent("TraversableFilterable", () => { it("traverseFilter", () => { const traverseFilter = _.traverseFilter( - ReadonlyArrayInstances.TraversableFilterable + ArrayInstances.TraversableFilterable )(OptionInstances.Applicative) const f = traverseFilter((s: string) => s.length > 2 ? O.some(false) : s.length > 1 ? O.some(true) : O.none()) U.deepStrictEqual(f([]), O.some([])) @@ -60,7 +60,7 @@ describe.concurrent("TraversableFilterable", () => { it("traversePartition", () => { const traversePartition = _.traversePartition( - ReadonlyArrayInstances.TraversableFilterable + ArrayInstances.TraversableFilterable )(OptionInstances.Applicative) const f = traversePartition((s: string) => s.length > 2 ? O.some(false) : s.length > 1 ? O.some(true) : O.none()) expect(f([])).toEqual(O.some([[], []])) diff --git a/packages/typeclass/test/data/ReadonlyArray.test.ts b/packages/typeclass/test/data/Array.test.ts similarity index 62% rename from packages/typeclass/test/data/ReadonlyArray.test.ts rename to packages/typeclass/test/data/Array.test.ts index 22a4982e13..dc5dc402aa 100644 --- a/packages/typeclass/test/data/ReadonlyArray.test.ts +++ b/packages/typeclass/test/data/Array.test.ts @@ -1,9 +1,9 @@ -import * as ReadonlyArrayInstances from "@effect/typeclass/data/ReadonlyArray" +import * as ArrayInstances from "@effect/typeclass/data/Array" import { describe, expect, it } from "vitest" -describe.concurrent("ReadonlyArray", () => { +describe.concurrent("Array", () => { it("Product.productAll", () => { - const productAll = ReadonlyArrayInstances.Product.productAll + const productAll = ArrayInstances.Product.productAll expect(productAll([])).toEqual([]) expect(productAll([[1, 2, 3]])).toEqual([[1], [2], [3]]) expect(productAll([[1, 2, 3], [4, 5]])).toEqual([[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [ diff --git a/packages/typeclass/test/data/Option.test.ts b/packages/typeclass/test/data/Option.test.ts index 533137e0f9..a727c1d313 100644 --- a/packages/typeclass/test/data/Option.test.ts +++ b/packages/typeclass/test/data/Option.test.ts @@ -1,5 +1,5 @@ +import * as ReadonlyArrayInstances from "@effect/typeclass/data/Array" import * as OptionInstances from "@effect/typeclass/data/Option" -import * as ReadonlyArrayInstances from "@effect/typeclass/data/ReadonlyArray" import { pipe } from "effect/Function" import * as Option from "effect/Option" import { describe, it } from "vitest" diff --git a/packages/typeclass/test/data/ReadonlyRecord.test.ts b/packages/typeclass/test/data/Record.test.ts similarity index 74% rename from packages/typeclass/test/data/ReadonlyRecord.test.ts rename to packages/typeclass/test/data/Record.test.ts index 4d9a091c39..fe5196fa54 100644 --- a/packages/typeclass/test/data/ReadonlyRecord.test.ts +++ b/packages/typeclass/test/data/Record.test.ts @@ -1,11 +1,11 @@ import * as OptionInstances from "@effect/typeclass/data/Option" -import * as ReadonlyRecordInstances from "@effect/typeclass/data/ReadonlyRecord" +import * as RecordInstances from "@effect/typeclass/data/Record" import * as Option from "effect/Option" import { describe, expect, it } from "vitest" -describe.concurrent("ReadonlyRecord", () => { +describe.concurrent("Record", () => { it("traverse (string)", () => { - const traverse = ReadonlyRecordInstances.traverse(OptionInstances.Applicative) + const traverse = RecordInstances.traverse(OptionInstances.Applicative) const stringRecord: Record = { a: 1, b: 2 @@ -18,7 +18,7 @@ describe.concurrent("ReadonlyRecord", () => { }) it("traverse (template literal)", () => { - const traverse = ReadonlyRecordInstances.getTraversable<`a${string}`>().traverse(OptionInstances.Applicative) + const traverse = RecordInstances.getTraversable<`a${string}`>().traverse(OptionInstances.Applicative) const templateLiteralRecord: Record<`a${string}`, number> = { a: 1, ab: 2 @@ -31,7 +31,7 @@ describe.concurrent("ReadonlyRecord", () => { }) it("traverse (symbol)", () => { - const traverse = ReadonlyRecordInstances.traverse(OptionInstances.Applicative) + const traverse = RecordInstances.traverse(OptionInstances.Applicative) const a = Symbol.for("a") const b = Symbol.for("b") const symbolRecord: Record = {