From 8edacca37f8e37c01a63fec332b06d9361efaa7b Mon Sep 17 00:00:00 2001 From: Tim Date: Thu, 18 Apr 2024 13:46:36 +1200 Subject: [PATCH] prevent use of `Array` as import name to solve bundler issues (#2555) --- .changeset/witty-taxis-smell.md | 14 + packages/cli/examples/naval-fate/store.ts | 20 +- 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 | 270 +++++++++--------- packages/cli/src/internal/helpDoc.ts | 12 +- packages/cli/src/internal/helpDoc/span.ts | 6 +- packages/cli/src/internal/options.ts | 260 ++++++++--------- 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/effect/src/Brand.ts | 4 +- packages/effect/src/Cron.ts | 34 +-- packages/effect/src/List.ts | 6 +- packages/effect/src/internal/cause.ts | 4 +- .../effect/src/internal/configProvider.ts | 92 +++--- packages/effect/src/internal/core-effect.ts | 18 +- packages/effect/src/internal/core.ts | 20 +- .../src/internal/differ/readonlyArrayPatch.ts | 12 +- 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/secret.ts | 4 +- packages/effect/src/internal/sink.ts | 4 +- .../effect/src/internal/stm/tPriorityQueue.ts | 22 +- packages/experimental/src/Machine.ts | 4 +- packages/experimental/src/Persistence/Lmdb.ts | 6 +- packages/experimental/src/RequestResolver.ts | 10 +- .../opentelemetry/src/internal/metrics.ts | 8 +- packages/platform/src/Http/Headers.ts | 8 +- packages/platform/src/Http/UrlParams.ts | 28 +- .../platform/src/PlatformConfigProvider.ts | 4 +- .../platform/src/internal/http/multiplex.ts | 4 +- packages/platform/src/internal/worker.ts | 4 +- packages/printer-ansi/src/internal/ansi.ts | 50 ++-- packages/printer/src/internal/doc.ts | 24 +- packages/printer/src/internal/docTree.ts | 24 +- packages/rpc/src/Resolver.ts | 6 +- 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/ParseResult.ts | 30 +- packages/schema/src/Pretty.ts | 6 +- packages/sql/src/Migrator.ts | 14 +- 56 files changed, 742 insertions(+), 728 deletions(-) create mode 100644 .changeset/witty-taxis-smell.md diff --git a/.changeset/witty-taxis-smell.md b/.changeset/witty-taxis-smell.md new file mode 100644 index 0000000000..21aa4eec73 --- /dev/null +++ b/.changeset/witty-taxis-smell.md @@ -0,0 +1,14 @@ +--- +"@effect/opentelemetry": patch +"@effect/experimental": patch +"@effect/printer-ansi": patch +"@effect/platform": patch +"@effect/printer": patch +"effect": patch +"@effect/schema": patch +"@effect/cli": patch +"@effect/rpc": patch +"@effect/sql": patch +--- + +prevent use of `Array` as import name to solve bundler issues diff --git a/packages/cli/examples/naval-fate/store.ts b/packages/cli/examples/naval-fate/store.ts index a156817a25..503a527c39 100644 --- a/packages/cli/examples/naval-fate/store.ts +++ b/packages/cli/examples/naval-fate/store.ts @@ -1,6 +1,6 @@ import * as KeyValueStore from "@effect/platform/KeyValueStore" import * as Schema from "@effect/schema/Schema" -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" @@ -67,8 +67,8 @@ export const make = Effect.gen(function*($) { return yield* $(Effect.fail(new ShipNotFoundError({ name, x, y }))) } const shipAtCoords = pipe( - Array.fromIterable(oldShips.values()), - Array.findFirst((ship) => ship.hasCoordinates(x, y)) + Arr.fromIterable(oldShips.values()), + Arr.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 = Array.findFirst(mines, (mine) => mine.hasCoordinates(x, y)) + const mineAtCoords = Arr.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( - Array.fromIterable(oldShips.values()), - Array.findFirst((ship) => ship.hasCoordinates(x, y)) + Arr.fromIterable(oldShips.values()), + Arr.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 = Array.findFirst(mines, (mine) => mine.hasCoordinates(x, y)) + const mineAtCoords = Arr.findFirst(mines, (mine) => mine.hasCoordinates(x, y)) if (Option.isNone(mineAtCoords)) { const mine = Mine.create(x, y) - const newMines = Array.append(mines, mine) + const newMines = Arr.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 = Array.findFirstIndex(mines, (mine) => mine.hasCoordinates(x, y)) + const mineAtCoords = Arr.findFirstIndex(mines, (mine) => mine.hasCoordinates(x, y)) if (Option.isSome(mineAtCoords)) { - const newMines = Array.remove(mines, mineAtCoords.value) + const newMines = Arr.remove(mines, mineAtCoords.value) yield* $(setMines(newMines)) } }) diff --git a/packages/cli/src/internal/args.ts b/packages/cli/src/internal/args.ts index d377cf0fd6..b14faca179 100644 --- a/packages/cli/src/internal/args.ts +++ b/packages/cli/src/internal/args.ts @@ -3,7 +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 * as Arr from "effect/Array" import type * as Config from "effect/Config" import * as Console from "effect/Console" import * as Effect from "effect/Effect" @@ -160,7 +160,7 @@ export const all: < if (arguments.length === 1) { if (isArgs(arguments[0])) { return map(arguments[0], (x) => [x]) as any - } else if (Array.isArray(arguments[0])) { + } else if (Arr.isArray(arguments[0])) { return allTupled(arguments[0] as Array) as any } else { const entries = Object.entries(arguments[0] as Readonly<{ [K: string]: Args.Args }>) @@ -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 = Array.getSomes([ + const ids = Arr.getSomes([ getIdentifierInternal(self.left as Instruction), getIdentifierInternal(self.right as Instruction) ]) - return Array.match(ids, { + return Arr.match(ids, { onEmpty: () => Option.none(), - onNonEmpty: (ids) => Option.some(Array.join(ids, ", ")) + onNonEmpty: (ids) => Option.some(Arr.join(ids, ", ")) }) } } @@ -637,7 +637,7 @@ const getUsageInternal = (self: Instruction): Usage.Usage => { } case "Single": { return InternalUsage.named( - Array.of(self.name), + Arr.of(self.name), InternalPrimitive.getChoices(self.primitiveType) ) } @@ -743,7 +743,7 @@ const validateInternal = ( } case "Single": { return Effect.suspend(() => { - return Array.matchLeft(args, { + return Arr.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 && Array.isEmptyReadonlyArray(args) + acc.length >= min1 && Arr.isEmptyReadonlyArray(args) ? Effect.succeed([args, acc]) : Effect.fail(failure), - onSuccess: ([args, a]) => loop(args, Array.append(acc, a)) + onSuccess: ([args, a]) => loop(args, Arr.append(acc, a)) })) } - return loop(args, Array.empty()).pipe( + return loop(args, Arr.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(Array.empty()) + return Effect.succeed(Arr.empty()) } case "Single": { const help = getHelpInternal(self) return InternalPrimitive.wizard(self.primitiveType, help).pipe( Effect.zipLeft(Console.log()), Effect.flatMap((input) => { - const args = Array.of(input as string) + const args = Arr.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) => Array.appendAll(left, right) + (left, right) => Arr.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(Array.empty()) - : Ref.make(Array.empty()).pipe( + ? Effect.succeed(Arr.empty()) + : Ref.make(Arr.empty()).pipe( Effect.flatMap((ref) => wizardInternal(self.args as Instruction, config).pipe( - Effect.flatMap((args) => Ref.update(ref, Array.appendAll(args))), + Effect.flatMap((args) => Ref.update(ref, Arr.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(Array.empty()) + ? Effect.succeed(Arr.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(Array.empty()) + ? Effect.succeed(Arr.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 Array.empty() + return Arr.empty() } case "Single": { const description = getShortDescription(self) @@ -1021,19 +1021,19 @@ export const getFishCompletions = (self: Instruction): Array => { InternalPrimitive.getFishCompletions( self.primitiveType as InternalPrimitive.Instruction ), - Array.appendAll( + Arr.appendAll( description.length === 0 - ? Array.empty() - : Array.of(`-d '${description}'`) + ? Arr.empty() + : Arr.of(`-d '${description}'`) ), - Array.join(" "), - Array.of + Arr.join(" "), + Arr.of ) } case "Both": { return pipe( getFishCompletions(self.left as Instruction), - Array.appendAll(getFishCompletions(self.right as Instruction)) + Arr.appendAll(getFishCompletions(self.right as Instruction)) ) } case "Map": @@ -1056,7 +1056,7 @@ export const getZshCompletions = ( ): Array => { switch (self._tag) { case "Empty": { - return Array.empty() + return Arr.empty() } case "Single": { const multiple = state.multiple ? "*" : "" @@ -1067,8 +1067,8 @@ export const getZshCompletions = ( self.primitiveType as InternalPrimitive.Instruction ) return possibleValues.length === 0 - ? Array.empty() - : Array.of(`${multiple}${optional}${self.name}${description}${possibleValues}`) + ? Arr.empty() + : Arr.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 Array.appendAll(left, right) + return Arr.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 535f3723a4..124187b8b2 100644 --- a/packages/cli/src/internal/cliApp.ts +++ b/packages/cli/src/internal/cliApp.ts @@ -1,6 +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 Arr from "effect/Array" import * as Console from "effect/Console" import * as Context from "effect/Context" import * as Effect from "effect/Effect" @@ -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 = Array.appendAll(prefixCommand(self.command), filteredArgs) + const prefixedArgs = Arr.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 Array.matchLeft(directive.leftover, { + return Arr.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, Array.drop(args, 2)] + return [self.executable, Arr.drop(args, 2)] } - const [[runtime, script], optionsAndArgs] = Array.splitAt(args, 2) + const [[runtime, script], optionsAndArgs] = Arr.splitAt(args, 2) return [`${runtime} ${script}`, optionsAndArgs] } @@ -165,8 +165,8 @@ const handleBuiltInOption = ( InternalHelpDoc.h1("USAGE"), pipe( InternalUsage.enumerate(builtIn.usage, config), - Array.map((span) => InternalHelpDoc.p(InternalSpan.concat(InternalSpan.text("$ "), span))), - Array.reduceRight( + Arr.map((span) => InternalHelpDoc.p(InternalSpan.concat(InternalSpan.text("$ "), span))), + Arr.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.fromIterable(InternalCommand.getNames(self.command))[0]! + const command = Arr.fromIterable(InternalCommand.getNames(self.command))[0]! switch (builtIn.shellType) { case "bash": { return InternalCommand.getBashCompletions(self.command, command).pipe( - Effect.flatMap((completions) => Console.log(Array.join(completions, "\n"))) + Effect.flatMap((completions) => Console.log(Arr.join(completions, "\n"))) ) } case "fish": { return InternalCommand.getFishCompletions(self.command, command).pipe( - Effect.flatMap((completions) => Console.log(Array.join(completions, "\n"))) + Effect.flatMap((completions) => Console.log(Arr.join(completions, "\n"))) ) } case "zsh": return InternalCommand.getZshCompletions(self.command, command).pipe( - Effect.flatMap((completions) => Console.log(Array.join(completions, "\n"))) + Effect.flatMap((completions) => Console.log(Arr.join(completions, "\n"))) ) } } @@ -234,7 +234,7 @@ const handleBuiltInOption = ( ) const help = InternalHelpDoc.sequence(header, description) const text = InternalHelpDoc.toAnsiText(help) - const command = Array.fromIterable(InternalCommand.getNames(self.command))[0]! + const command = Arr.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( - Array.drop(args, 1), - Array.prependAll(executable.split(/\s+/)) + Arr.drop(args, 1), + Arr.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 = Array.empty() + let prefix: ReadonlyArray = Arr.empty() while (command !== undefined) { switch (command._tag) { case "Standard": { - prefix = Array.of(command.name) + prefix = Arr.of(command.name) command = undefined break } case "GetUserInput": { - prefix = Array.of(command.name) + prefix = Arr.of(command.name) command = undefined break } @@ -305,21 +305,21 @@ const getWizardPrefix = ( commandLineArgs: ReadonlyArray ): ReadonlyArray => { const subcommands = InternalCommand.getSubcommands(builtIn.command) - const [parentArgs, childArgs] = Array.span( + const [parentArgs, childArgs] = Arr.span( commandLineArgs, (name) => !HashMap.has(subcommands, name) ) - const args = Array.matchLeft(childArgs, { - onEmpty: () => Array.filter(parentArgs, (arg) => arg !== "--wizard"), - onNonEmpty: (head) => Array.append(parentArgs, head) + const args = Arr.matchLeft(childArgs, { + onEmpty: () => Arr.filter(parentArgs, (arg) => arg !== "--wizard"), + onNonEmpty: (head) => Arr.append(parentArgs, head) }) - return Array.appendAll(rootCommand.split(/\s+/), args) + return Arr.appendAll(rootCommand.split(/\s+/), args) } const renderWizardArgs = (args: ReadonlyArray) => { const params = pipe( - Array.filter(args, (param) => param.length > 0), - Array.join(" ") + Arr.filter(args, (param) => param.length > 0), + Arr.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 da03581b11..1ad4c0c44f 100644 --- a/packages/cli/src/internal/command.ts +++ b/packages/cli/src/internal/command.ts @@ -1,7 +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 Arr from "effect/Array" import * as Context from "effect/Context" import * as Effect from "effect/Effect" import * as Effectable from "effect/Effectable" @@ -56,10 +56,10 @@ const parseConfig = (config: Command.Command.Config): Command.Command.ParsedConf | ReadonlyArray | Options.Options | Command.Command.Config> | Command.Command.Config ): Command.Command.ParsedConfigNode { - if (Array.isArray(value)) { + if (Arr.isArray(value)) { return { _tag: "Array", - children: Array.map(value as Array, parseValue) + children: Arr.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 Array.map(node.children, nodeValue) + return Arr.map(node.children, nodeValue) } else { return reconstructConfigTree(node.tree, args, options) } @@ -192,7 +192,7 @@ export const fromDescriptor = dual< handler ?? ((_) => Effect.failSync(() => ValidationError.helpRequested(getDescriptor(self)))), Context.GenericTag( - `@effect/cli/Command/(${Array.fromIterable(InternalDescriptor.getNames(descriptor)).join("|")})` + `@effect/cli/Command/(${Arr.fromIterable(InternalDescriptor.getNames(descriptor)).join("|")})` ) ) return self as any @@ -427,7 +427,7 @@ export const withDescription = dual< /** @internal */ export const withSubcommands = dual< - >>( + >>( subcommands: Subcommand ) => (self: Command.Command) => Command.Command< Name, @@ -453,7 +453,7 @@ export const withSubcommands = dual< R, E, A, - Subcommand extends Array.NonEmptyReadonlyArray> + Subcommand extends Arr.NonEmptyReadonlyArray> >( self: Command.Command, subcommands: Subcommand @@ -479,9 +479,9 @@ export const withSubcommands = dual< >(2, (self, subcommands) => { const command = InternalDescriptor.withSubcommands( self.descriptor, - Array.map(subcommands, (_) => [_.tag, _.descriptor]) + Arr.map(subcommands, (_) => [_.tag, _.descriptor]) ) - const subcommandMap = Array.reduce( + const subcommandMap = Arr.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 1b4fbcc560..ef368b45a6 100644 --- a/packages/cli/src/internal/commandDescriptor.ts +++ b/packages/cli/src/internal/commandDescriptor.ts @@ -2,7 +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 Arr from "effect/Array" import * as Console from "effect/Console" import * as Effect from "effect/Effect" import * as Either from "effect/Either" @@ -99,7 +99,7 @@ export interface Map extends export interface Subcommands extends Op<"Subcommands", { readonly parent: Instruction - readonly children: Array.NonEmptyReadonlyArray + readonly children: Arr.NonEmptyReadonlyArray }> {} @@ -264,7 +264,7 @@ export const withDescription = dual< /** @internal */ export const withSubcommands = dual< < - const Subcommands extends Array.NonEmptyReadonlyArray< + const Subcommands extends Arr.NonEmptyReadonlyArray< readonly [id: unknown, command: Descriptor.Command] > >( @@ -279,7 +279,7 @@ export const withSubcommands = dual< >, < A, - const Subcommands extends Array.NonEmptyReadonlyArray< + const Subcommands extends Arr.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 = Array.map(subcommands, ([id, command]) => map(command, (a) => [id, a])) + op.children = Arr.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 = Array.append(preceding, usage) - const finalUsage = Array.reduce( + const usages = Arr.append(preceding, usage) + const finalUsage = Arr.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 Array.of([finalUsage, description]) + return Arr.of([finalUsage, description]) } case "Map": { return getUsage(command.command, preceding) } case "Subcommands": { const parentUsage = getUsage(command.parent, preceding) - return Option.match(Array.head(parentUsage), { + return Option.match(Arr.head(parentUsage), { onNone: () => - Array.flatMap( + Arr.flatMap( command.children, (child) => getUsage(child, preceding) ), onSome: ([usage]) => { - const childrenUsage = Array.flatMap( + const childrenUsage = Arr.flatMap( command.children, - (child) => getUsage(child, Array.append(preceding, usage)) + (child) => getUsage(child, Arr.append(preceding, usage)) ) - return Array.appendAll(parentUsage, childrenUsage) + return Arr.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 = Array.reduceRight( + const maxUsageLength = Arr.reduceRight( subcommands, 0, (max, [usage]) => Math.max(InternalSpan.size(usage), max) ) - const documents = Array.map(subcommands, ([usage, desc]) => + const documents = Arr.map(subcommands, ([usage, desc]) => InternalHelpDoc.p( InternalSpan.spans([ usage, @@ -412,7 +412,7 @@ const getHelpInternal = (self: Instruction, config: CliConfig.CliConfig): HelpDo desc ]) )) - if (Array.isNonEmptyReadonlyArray(documents)) { + if (Arr.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(Array.flatMap( + printSubcommands(Arr.flatMap( self.children, - (child) => getUsage(child, Array.empty()) + (child) => getUsage(child, Arr.empty()) )) ) ) @@ -435,7 +435,7 @@ const getNamesInternal = (self: Instruction): Array => { switch (self._tag) { case "Standard": case "GetUserInput": { - return Array.of(self.name) + return Arr.of(self.name) } case "Map": { return getNamesInternal(self.command) @@ -456,7 +456,7 @@ const getSubcommandsInternal = ( switch (self._tag) { case "Standard": case "GetUserInput": { - return Array.of([self.name, self]) + return Arr.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) - : Array.flatMap(self.children, (child) => loop(child, true)) + : Arr.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(Array.of(self.name), Option.none()), + InternalUsage.named(Arr.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(Array.of(self.name), Option.none()) + return InternalUsage.named(Arr.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> => - Array.matchLeft(args, { + Arr.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 > => - Array.matchLeft(args, { + Arr.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 = Array.drop(args, 1) + const argsWithoutCommand = Arr.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, - Array.appendAll(commandArgs, forcedCommandArgs), + Arr.appendAll(commandArgs, forcedCommandArgs), config ).pipe( Effect.catchAll((e) => @@ -605,14 +605,14 @@ const parseInternal = ( ValidationError.ValidationError, FileSystem.FileSystem | Path.Path | Terminal.Terminal > => { - if (Array.contains(args, "--help") || Array.contains(args, "-h")) { - return parseBuiltInArgs(Array.make(self.name, "--help")) + if (Arr.contains(args, "--help") || Arr.contains(args, "-h")) { + return parseBuiltInArgs(Arr.make(self.name, "--help")) } - if (Array.contains(args, "--wizard")) { - return parseBuiltInArgs(Array.make(self.name, "--wizard")) + if (Arr.contains(args, "--wizard")) { + return parseBuiltInArgs(Arr.make(self.name, "--wizard")) } - if (Array.contains(args, "--version")) { - return parseBuiltInArgs(Array.make(self.name, "--version")) + if (Arr.contains(args, "--version")) { + return parseBuiltInArgs(Arr.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(Array.drop(args, 1), { + InternalCommandDirective.userDefined(Arr.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] = Array.span( + const [parentArgs, childArgs] = Arr.span( args, - (arg) => !Array.some(subcommands, ([name]) => name === arg) + (arg) => !Arr.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(Array.head(names), () => "") + const parentName = Option.getOrElse(Arr.head(names), () => "") const newDirective = InternalCommandDirective.builtIn(InternalBuiltInOptions.showHelp( InternalUsage.concat( - InternalUsage.named(Array.of(parentName), Option.none()), + InternalUsage.named(Arr.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 Array.isNonEmptyReadonlyArray(childArgs) + return Arr.isNonEmptyReadonlyArray(childArgs) ? Effect.orElse(helpDirectiveForChild, () => helpDirectiveForParent) : helpDirectiveForParent } @@ -746,16 +746,16 @@ const parseInternal = ( return Effect.succeed(directive) } case "UserDefined": { - const args = Array.appendAll(directive.leftover, childArgs) - if (Array.isNonEmptyReadonlyArray(args)) { + const args = Arr.appendAll(directive.leftover, childArgs) + if (Arr.isNonEmptyReadonlyArray(args)) { return parseChildren.pipe(Effect.mapBoth({ onFailure: (err) => { if (InternalValidationError.isCommandMismatch(err)) { - const parentName = Option.getOrElse(Array.head(names), () => "") - const childNames = Array.map(subcommands, ([name]) => `'${name}'`) + const parentName = Option.getOrElse(Arr.head(names), () => "") + const childNames = Arr.map(subcommands, ([name]) => `'${name}'`) const oneOf = childNames.length === 1 ? "" : " one of" const error = InternalHelpDoc.p( - `Invalid subcommand for ${parentName} - use${oneOf} ${Array.join(childNames, ", ")}` + `Invalid subcommand for ${parentName} - use${oneOf} ${Arr.join(childNames, ", ")}` ) return InternalValidationError.commandMismatch(error) } @@ -775,7 +775,7 @@ const parseInternal = ( } }), Effect.catchSome(() => - Array.isEmptyReadonlyArray(args) + Arr.isEmptyReadonlyArray(args) ? Option.some(helpDirectiveForParent) : Option.none() ) @@ -788,8 +788,8 @@ const parseInternal = ( const splitForcedArgs = ( args: ReadonlyArray ): [Array, Array] => { - const [remainingArgs, forcedArgs] = Array.span(args, (str) => str !== "--") - return [remainingArgs, Array.drop(forcedArgs, 1)] + const [remainingArgs, forcedArgs] = Arr.span(args, (str) => str !== "--") + return [remainingArgs, Arr.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( - Array.join(commandLine, " "), + Arr.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, Array.appendAll(options))) + yield* _(Ref.updateAndGet(commandLineRef, Arr.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, Array.appendAll(options))) + yield* _(Ref.updateAndGet(commandLineRef, Arr.appendAll(options))) yield* _(logCurrentCommand) } } @@ -904,12 +904,12 @@ const wizardInternal = ( }) const choices = pipe( getSubcommandsInternal(self), - Array.map(([name], index) => makeChoice(name, index)) + Arr.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, Array.append(name))), + Effect.tap(([name]) => Ref.update(commandLineRef, Arr.append(name))), Effect.zipLeft(Console.log()), Effect.flatMap(([, nextIndex]) => loop(self.children[nextIndex], commandLineRef)) ) @@ -996,7 +996,7 @@ const traverseCommand = ( case "Subcommands": { const parentNames = getNamesInternal(self.parent) const nextSubcommands = getSubcommandsInternal(self) - const nextParentCommands = Array.appendAll(parentCommands, parentNames) + const nextParentCommands = Arr.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, Array.empty(), Array.empty(), 0)).pipe( + return Effect.suspend(() => loop(self, Arr.empty(), Arr.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 = Array.allocate(indent + 1).join(" ") - return Array.map(self, (line) => `${indentation}${line}`) + const indentation = Arr.allocate(indent + 1).join(" ") + return Arr.map(self, (line) => `${indentation}${line}`) }) const getBashCompletionsInternal = ( @@ -1025,7 +1025,7 @@ const getBashCompletionsInternal = ( ): Effect.Effect> => traverseCommand( self, - Array.empty<[ReadonlyArray, ReadonlyArray]>(), + Arr.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) - : Array.empty() + : Arr.empty() const subcommandNames = pipe( info.subcommands, - Array.map(([name]) => name), - Array.sort(Order.string) + Arr.map(([name]) => name), + Arr.sort(Order.string) ) - const wordList = Array.appendAll(optionNames, subcommandNames) - const preformatted = Array.isEmptyReadonlyArray(info.parentCommands) - ? Array.of(info.command.name) + const wordList = Arr.appendAll(optionNames, subcommandNames) + const preformatted = Arr.isEmptyReadonlyArray(info.parentCommands) + ? Arr.of(info.command.name) : pipe( info.parentCommands, - Array.append(info.command.name), - Array.map((command) => command.replace("-", "__")) + Arr.append(info.command.name), + Arr.map((command) => command.replace("-", "__")) ) - const caseName = Array.join(preformatted, ",") - const funcName = Array.join(preformatted, "__") - const funcLines = Array.isEmptyReadonlyArray(info.parentCommands) - ? Array.empty() + const caseName = Arr.join(preformatted, ",") + const funcName = Arr.join(preformatted, "__") + const funcLines = Arr.isEmptyReadonlyArray(info.parentCommands) + ? Arr.empty() : [ `${caseName})`, ` cmd="${funcName}"`, @@ -1058,7 +1058,7 @@ const getBashCompletionsInternal = ( ] const cmdLines = [ `${funcName})`, - ` opts="${Array.join(wordList, " ")}"`, + ` opts="${Arr.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 = Array.append( + const lines = Arr.append( state, [funcLines, cmdLines] as [ReadonlyArray, ReadonlyArray] ) return Effect.succeed(lines) } ).pipe(Effect.map((lines) => { - const rootCommand = Array.unsafeGet(getNamesInternal(self), 0) + const rootCommand = Arr.unsafeGet(getNamesInternal(self), 0) const scriptName = `_${rootCommand}_bash_completions` - const funcCases = Array.flatMap(lines, ([funcLines]) => funcLines) - const cmdCases = Array.flatMap(lines, ([, cmdLines]) => cmdLines) + const funcCases = Arr.flatMap(lines, ([funcLines]) => funcLines) + const cmdCases = Arr.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, Array.empty(), (state, info) => { - const baseTemplate = Array.make("complete", "-c", executable) + traverseCommand(self, Arr.empty(), (state, info) => { + const baseTemplate = Arr.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) - : Array.empty() + : Arr.empty() const rootCompletions = (conditionals: ReadonlyArray) => pipe( - Array.map(optionsCompletions, (option) => + Arr.map(optionsCompletions, (option) => pipe( baseTemplate, - Array.appendAll(conditionals), - Array.append(option), - Array.join(" ") + Arr.appendAll(conditionals), + Arr.append(option), + Arr.join(" ") )), - Array.appendAll( - Array.map(argsCompletions, (option) => + Arr.appendAll( + Arr.map(argsCompletions, (option) => pipe( baseTemplate, - Array.appendAll(conditionals), - Array.append(option), - Array.join(" ") + Arr.appendAll(conditionals), + Arr.append(option), + Arr.join(" ") )) ) ) const subcommandCompletions = (conditionals: ReadonlyArray) => - Array.map(info.subcommands, ([name, subcommand]) => { + Arr.map(info.subcommands, ([name, subcommand]) => { const description = getShortDescription(subcommand) return pipe( baseTemplate, - Array.appendAll(conditionals), - Array.appendAll(Array.make("-f", "-a", `"${name}"`)), - Array.appendAll( + Arr.appendAll(conditionals), + Arr.appendAll(Arr.make("-f", "-a", `"${name}"`)), + Arr.appendAll( description.length === 0 - ? Array.empty() - : Array.make("-d", `'${description}'`) + ? Arr.empty() + : Arr.make("-d", `'${description}'`) ), - Array.join(" ") + Arr.join(" ") ) }) // If parent commands are empty, then the info is for the root command - if (Array.isEmptyReadonlyArray(info.parentCommands)) { - const conditionals = Array.make("-n", "\"__fish_use_subcommand\"") + if (Arr.isEmptyReadonlyArray(info.parentCommands)) { + const conditionals = Arr.make("-n", "\"__fish_use_subcommand\"") return Effect.succeed(pipe( state, - Array.appendAll(rootCompletions(conditionals)), - Array.appendAll(subcommandCompletions(conditionals)) + Arr.appendAll(rootCompletions(conditionals)), + Arr.appendAll(subcommandCompletions(conditionals)) )) } // Otherwise the info is for a subcommand const parentConditionals = pipe( info.parentCommands, // Drop the root command name from the subcommand conditionals - Array.drop(1), - Array.append(info.command.name), - Array.map((command) => `__fish_seen_subcommand_from ${command}`) + Arr.drop(1), + Arr.append(info.command.name), + Arr.map((command) => `__fish_seen_subcommand_from ${command}`) ) - const subcommandConditionals = Array.map( + const subcommandConditionals = Arr.map( info.subcommands, ([name]) => `not __fish_seen_subcommand_from ${name}` ) const baseConditionals = pipe( - Array.appendAll(parentConditionals, subcommandConditionals), - Array.join("; and ") + Arr.appendAll(parentConditionals, subcommandConditionals), + Arr.join("; and ") ) - const conditionals = Array.make("-n", `"${baseConditionals}"`) + const conditionals = Arr.make("-n", `"${baseConditionals}"`) return Effect.succeed(pipe( state, - Array.appendAll(rootCompletions(conditionals)), - Array.appendAll(subcommandCompletions(conditionals)) + Arr.appendAll(rootCompletions(conditionals)), + Arr.appendAll(subcommandCompletions(conditionals)) )) }) @@ -1196,26 +1196,26 @@ const getZshCompletionsInternal = ( self: Instruction, executable: string ): Effect.Effect> => - traverseCommand(self, Array.empty(), (state, info) => { - const preformatted = Array.isEmptyReadonlyArray(info.parentCommands) - ? Array.of(info.command.name) + traverseCommand(self, Arr.empty(), (state, info) => { + const preformatted = Arr.isEmptyReadonlyArray(info.parentCommands) + ? Arr.of(info.command.name) : pipe( info.parentCommands, - Array.append(info.command.name), - Array.map((command) => command.replace("-", "__")) + Arr.append(info.command.name), + Arr.map((command) => command.replace("-", "__")) ) - const underscoreName = Array.join(preformatted, "__") - const spaceName = Array.join(preformatted, " ") + const underscoreName = Arr.join(preformatted, "__") + const spaceName = Arr.join(preformatted, " ") const subcommands = pipe( info.subcommands, - Array.map(([name, subcommand]) => { + Arr.map(([name, subcommand]) => { const desc = getShortDescription(subcommand) return `'${name}:${desc}' \\` }) ) - const commands = Array.isEmptyReadonlyArray(subcommands) + const commands = Arr.isEmptyReadonlyArray(subcommands) ? `commands=()` - : `commands=(\n${Array.join(indentAll(subcommands, 8), "\n")}\n )` + : `commands=(\n${Arr.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(Array.appendAll(state, handlerLines)) + return Effect.succeed(Arr.appendAll(state, handlerLines)) }).pipe(Effect.map((handlers) => { - const rootCommand = Array.unsafeGet(getNamesInternal(self), 0) - const cases = getZshSubcommandCases(self, Array.empty(), Array.empty()) + const rootCommand = Arr.unsafeGet(getNamesInternal(self), 0) + const cases = getZshSubcommandCases(self, Arr.empty(), Arr.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), - Array.map((completion) => `'${completion}' \\`) + Arr.map((completion) => `'${completion}' \\`) ) const argCompletions = pipe( InternalArgs.getZshCompletions(args as InternalArgs.Instruction), - Array.map((completion) => `'${completion}' \\`) + Arr.map((completion) => `'${completion}' \\`) ) - if (Array.isEmptyReadonlyArray(parentCommands)) { + if (Arr.isEmptyReadonlyArray(parentCommands)) { return [ "_arguments \"${_arguments_options[@]}\" \\", ...indentAll(optionCompletions, 4), @@ -1288,7 +1288,7 @@ const getZshSubcommandCases = ( " && ret=0" ] } - if (Array.isEmptyReadonlyArray(subcommands)) { + if (Arr.isEmptyReadonlyArray(subcommands)) { return [ `(${self.name})`, "_arguments \"${_arguments_options[@]}\" \\", @@ -1303,7 +1303,7 @@ const getZshSubcommandCases = ( "_arguments \"${_arguments_options[@]}\" \\", ...indentAll(optionCompletions, 4), ...indentAll(argCompletions, 4), - ` ":: :_${Array.append(parentCommands, self.name).join("__")}_commands" \\`, + ` ":: :_${Arr.append(parentCommands, self.name).join("__")}_commands" \\`, ` "*::: :->${self.name}" \\`, " && ret=0" ] @@ -1317,25 +1317,25 @@ const getZshSubcommandCases = ( const parentLines = getZshSubcommandCases( self.parent, parentCommands, - Array.appendAll(subcommands, nextSubcommands) + Arr.appendAll(subcommands, nextSubcommands) ) const childCases = pipe( self.children, - Array.flatMap((child) => + Arr.flatMap((child) => getZshSubcommandCases( child, - Array.appendAll(parentCommands, parentNames), + Arr.appendAll(parentCommands, parentNames), subcommands ) ) ) const hyphenName = pipe( - Array.appendAll(parentCommands, parentNames), - Array.join("-") + Arr.appendAll(parentCommands, parentNames), + Arr.join("-") ) const childLines = pipe( parentNames, - Array.flatMap((parentName) => [ + Arr.flatMap((parentName) => [ "case $state in", ` (${parentName})`, ` words=($line[1] "\${words[@]}")`, @@ -1347,13 +1347,13 @@ const getZshSubcommandCases = ( " ;;", "esac" ]), - Array.appendAll( - Array.isEmptyReadonlyArray(parentCommands) - ? Array.empty() - : Array.of(";;") + Arr.appendAll( + Arr.isEmptyReadonlyArray(parentCommands) + ? Arr.empty() + : Arr.of(";;") ) ) - return Array.appendAll(parentLines, childLines) + return Arr.appendAll(parentLines, childLines) } } } diff --git a/packages/cli/src/internal/helpDoc.ts b/packages/cli/src/internal/helpDoc.ts index 1545e47e42..ed4529bc5a 100644 --- a/packages/cli/src/internal/helpDoc.ts +++ b/packages/cli/src/internal/helpDoc.ts @@ -1,7 +1,7 @@ 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 Arr from "effect/Array" import { dual, pipe } from "effect/Function" import type * as HelpDoc from "../HelpDoc.js" import type * as Span from "../HelpDoc/Span.js" @@ -58,8 +58,8 @@ export const orElse = dual< /** @internal */ export const blocks = (helpDocs: Iterable): HelpDoc.HelpDoc => { - const elements = Array.fromIterable(helpDocs) - if (Array.isNonEmptyReadonlyArray(elements)) { + const elements = Arr.fromIterable(helpDocs) + if (Arr.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: Array.NonEmptyReadonlyArray<[Span.Span, HelpDoc.HelpDoc]> + definitions: Arr.NonEmptyReadonlyArray<[Span.Span, HelpDoc.HelpDoc]> ): HelpDoc.HelpDoc => ({ _tag: "DescriptionList", definitions @@ -79,7 +79,7 @@ export const descriptionList = ( /** @internal */ export const enumeration = ( - elements: Array.NonEmptyReadonlyArray + elements: Arr.NonEmptyReadonlyArray ): HelpDoc.HelpDoc => ({ _tag: "Enumeration", elements @@ -123,7 +123,7 @@ export const mapDescriptionList = dual< ) => HelpDoc.HelpDoc >(2, (self, f) => isDescriptionList(self) - ? descriptionList(Array.map(self.definitions, ([span, helpDoc]) => f(span, helpDoc))) + ? descriptionList(Arr.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 65929e7594..249ea31165 100644 --- a/packages/cli/src/internal/helpDoc/span.ts +++ b/packages/cli/src/internal/helpDoc/span.ts @@ -1,7 +1,7 @@ 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 * as Arr from "effect/Array" import { dual } from "effect/Function" import type * as Span from "../../HelpDoc/Span.js" @@ -92,8 +92,8 @@ export const getText = (self: Span.Span): string => { /** @internal */ export const spans = (spans: Iterable): Span.Span => { - const elements = Array.fromIterable(spans) - if (Array.isNonEmptyReadonlyArray(elements)) { + const elements = Arr.fromIterable(spans) + if (Arr.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 1510f9c214..9cbf642acf 100644 --- a/packages/cli/src/internal/options.ts +++ b/packages/cli/src/internal/options.ts @@ -3,7 +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 * as Arr from "effect/Array" import type * as Config from "effect/Config" import * as Console from "effect/Console" import * as Effect from "effect/Effect" @@ -192,7 +192,7 @@ export const all: < if (arguments.length === 1) { if (isOptions(arguments[0])) { return map(arguments[0], (x) => [x]) as any - } else if (Array.isArray(arguments[0])) { + } else if (Arr.isArray(arguments[0])) { return allTupled(arguments[0] as Array) as any } else { const entries = Object.entries( @@ -232,9 +232,9 @@ export const boolean = ( aliases, InternalPrimitive.boolean(Option.some(ifPresent)) ) - if (Array.isNonEmptyReadonlyArray(negationNames)) { - const head = Array.headNonEmpty(negationNames) - const tail = Array.tailNonEmpty(negationNames) + if (Arr.isNonEmptyReadonlyArray(negationNames)) { + const head = Arr.headNonEmpty(negationNames) + const tail = Arr.tailNonEmpty(negationNames) const negationOption = makeSingle( head, tail, @@ -254,19 +254,19 @@ export const choice = >( choices: C ): Options.Options => { const primitive = InternalPrimitive.choice( - Array.map(choices, (choice) => [choice, choice]) + Arr.map(choices, (choice) => [choice, choice]) ) - return makeSingle(name, Array.empty(), primitive) + return makeSingle(name, Arr.empty(), primitive) } /** @internal */ export const choiceWithValue = >( name: string, choices: C -): Options.Options => makeSingle(name, Array.empty(), InternalPrimitive.choice(choices)) +): Options.Options => makeSingle(name, Arr.empty(), InternalPrimitive.choice(choices)) /** @internal */ -export const date = (name: string): Options.Options => makeSingle(name, Array.empty(), InternalPrimitive.date) +export const date = (name: string): Options.Options => makeSingle(name, Arr.empty(), InternalPrimitive.date) /** @internal */ export const directory = ( @@ -275,7 +275,7 @@ export const directory = ( ): Options.Options => makeSingle( name, - Array.empty(), + Arr.empty(), InternalPrimitive.path("directory", config?.exists ?? "either") ) @@ -286,7 +286,7 @@ export const file = ( ): Options.Options => makeSingle( name, - Array.empty(), + Arr.empty(), InternalPrimitive.path("file", config?.exists ?? "either") ) @@ -347,18 +347,18 @@ export const filterMap = dual< }))) /** @internal */ -export const float = (name: string): Options.Options => makeSingle(name, Array.empty(), InternalPrimitive.float) +export const float = (name: string): Options.Options => makeSingle(name, Arr.empty(), InternalPrimitive.float) /** @internal */ export const integer = (name: string): Options.Options => - makeSingle(name, Array.empty(), InternalPrimitive.integer) + makeSingle(name, Arr.empty(), InternalPrimitive.integer) /** @internal */ export const keyValueMap = ( option: string | Options.Options ): Options.Options> => { if (typeof option === "string") { - const single = makeSingle(option, Array.empty(), InternalPrimitive.text) + const single = makeSingle(option, Arr.empty(), InternalPrimitive.text) return makeKeyValueMap(single as Single) } if (!isSingle(option as Instruction)) { @@ -377,10 +377,10 @@ export const none: Options.Options = (() => { /** @internal */ export const secret = (name: string): Options.Options => - makeSingle(name, Array.empty(), InternalPrimitive.secret) + makeSingle(name, Arr.empty(), InternalPrimitive.secret) /** @internal */ -export const text = (name: string): Options.Options => makeSingle(name, Array.empty(), InternalPrimitive.text) +export const text = (name: string): Options.Options => makeSingle(name, Arr.empty(), InternalPrimitive.text) // ============================================================================= // Combinators @@ -392,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) @@ -416,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> @@ -424,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) @@ -570,7 +570,7 @@ export const withAlias = dual< (self: Options.Options, alias: string) => Options.Options >(2, (self, alias) => modifySingle(self as Instruction, (single) => { - const aliases = Array.append(single.aliases, alias) + const aliases = Arr.append(single.aliases, alias) return makeSingle( single.name, aliases, @@ -694,7 +694,7 @@ const getHelpInternal = (self: Instruction): HelpDoc.HelpDoc => { return InternalHelpDoc.empty } case "Single": { - return InternalHelpDoc.descriptionList(Array.of([ + return InternalHelpDoc.descriptionList(Arr.of([ InternalHelpDoc.getSpan(InternalUsage.getHelp(getUsageInternal(self))), InternalHelpDoc.sequence( InternalHelpDoc.p(InternalPrimitive.getHelp(self.primitiveType)), @@ -795,13 +795,13 @@ const getIdentifierInternal = (self: Instruction): Option.Option => { } case "Both": case "OrElse": { - const ids = Array.getSomes([ + const ids = Arr.getSomes([ getIdentifierInternal(self.left as Instruction), getIdentifierInternal(self.right as Instruction) ]) - return Array.match(ids, { + return Arr.match(ids, { onEmpty: () => Option.none(), - onNonEmpty: (ids) => Option.some(Array.join(ids, ", ")) + onNonEmpty: (ids) => Option.some(Arr.join(ids, ", ")) }) } case "KeyValueMap": @@ -1085,10 +1085,10 @@ export const getNames = (self: Instruction): Array => { const loop = (self: Instruction): ReadonlyArray => { switch (self._tag) { case "Empty": { - return Array.empty() + return Arr.empty() } case "Single": { - return Array.prepend(self.aliases, self.name) + return Arr.prepend(self.aliases, self.name) } case "KeyValueMap": case "Variadic": { @@ -1103,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 Array.appendAll(left, right) + return Arr.appendAll(left, right) } } } @@ -1113,21 +1113,21 @@ export const getNames = (self: Instruction): Array => { ) return pipe( loop(self), - Array.map((str) => makeFullName(str)), - Array.sort(order), - Array.map((tuple) => tuple[1]) + Arr.map((str) => makeFullName(str)), + Arr.sort(order), + Arr.map((tuple) => tuple[1]) ) } const toParseableInstruction = (self: Instruction): Array => { switch (self._tag) { case "Empty": { - return Array.empty() + return Arr.empty() } case "Single": case "KeyValueMap": case "Variadic": { - return Array.of(self) + return Arr.of(self) } case "Map": case "WithDefault": @@ -1136,7 +1136,7 @@ const toParseableInstruction = (self: Instruction): Array } case "Both": case "OrElse": { - return Array.appendAll( + return Arr.appendAll( toParseableInstruction(self.left as Instruction), toParseableInstruction(self.right as Instruction) ) @@ -1158,21 +1158,21 @@ const parseInternal = ( return Effect.void } case "Single": { - 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)) { + const singleNames = Arr.filterMap(getNames(self), (name) => HashMap.get(args, name)) + if (Arr.isNonEmptyReadonlyArray(singleNames)) { + const head = Arr.headNonEmpty(singleNames) + const tail = Arr.tailNonEmpty(singleNames) + if (Arr.isEmptyReadonlyArray(tail)) { + if (Arr.isEmptyReadonlyArray(head)) { return InternalPrimitive.validate(self.primitiveType, Option.none(), config).pipe( Effect.mapError((e) => InternalValidationError.invalidValue(InternalHelpDoc.p(e))) ) } if ( - Array.isNonEmptyReadonlyArray(head) && - Array.isEmptyReadonlyArray(Array.tailNonEmpty(head)) + Arr.isNonEmptyReadonlyArray(head) && + Arr.isEmptyReadonlyArray(Arr.tailNonEmpty(head)) ) { - const value = Array.headNonEmpty(head) + const value = Arr.headNonEmpty(head) return InternalPrimitive.validate(self.primitiveType, Option.some(value), config).pipe( Effect.mapError((e) => InternalValidationError.invalidValue(InternalHelpDoc.p(e))) ) @@ -1194,7 +1194,7 @@ const parseInternal = ( value: string ): Effect.Effect<[string, string], ValidationError.ValidationError> => { const split = value.trim().split("=") - if (Array.isNonEmptyReadonlyArray(split) && split.length === 2 && split[1] !== "") { + if (Arr.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}'`) @@ -1276,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 = Array.filterMap(getNames(self), (name) => HashMap.get(args, name)) + const matchedArgument = Arr.filterMap(getNames(self), (name) => HashMap.get(args, name)) const validateMinMax = (values: ReadonlyArray) => { if (values.length < min) { const name = self.argumentOption.fullName @@ -1297,15 +1297,15 @@ const parseInternal = ( } // If we did not receive any variadic arguments then perform the bounds // checks with an empty array - if (Array.every(matchedArgument, Array.isEmptyReadonlyArray)) { - return validateMinMax(Array.empty()) + if (Arr.every(matchedArgument, Arr.isEmptyReadonlyArray)) { + return validateMinMax(Arr.empty()) } return parseInternal(self.argumentOption, args, config).pipe(Effect.matchEffect({ onFailure: (error) => InternalValidationError.isMultipleValuesDetected(error) ? validateMinMax(error.values) : Effect.fail(error), - onSuccess: (value) => validateMinMax(Array.of(value as string)) + onSuccess: (value) => validateMinMax(Arr.of(value as string)) })) } case "WithDefault": { @@ -1331,14 +1331,14 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. > => { switch (self._tag) { case "Empty": { - return Effect.succeed(Array.empty()) + return Effect.succeed(Arr.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 = Array.make(getNames(self)[0]!, input as string) + const args = Arr.make(getNames(self)[0]!, input as string) return parseCommandLine(self, args, config).pipe(Effect.as(args)) }), Effect.zipLeft(Console.log()) @@ -1353,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(Array.prepend(args, identifier)) + Effect.as(Arr.prepend(args, identifier)) ) }), Effect.zipLeft(Console.log()) @@ -1366,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) => Array.appendAll(left, right) + (left, right) => Arr.appendAll(left, right) ) } case "OrElse": { @@ -1376,7 +1376,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. InternalHelpDoc.sequence(alternativeHelp) ) const makeChoice = (title: string, value: Instruction) => ({ title, value }) - const choices = Array.getSomes([ + const choices = Arr.getSomes([ Option.map( getIdentifierInternal(self.left as Instruction), (title) => makeChoice(title, self.left as Instruction) @@ -1406,11 +1406,11 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. }).pipe( Effect.flatMap((n) => n <= 0 - ? Effect.succeed(Array.empty()) - : Ref.make(Array.empty()).pipe( + ? Effect.succeed(Arr.empty()) + : Ref.make(Arr.empty()).pipe( Effect.flatMap((ref) => wizardInternal(self.argumentOption as Instruction, config).pipe( - Effect.flatMap((args) => Ref.update(ref, Array.appendAll(args))), + Effect.flatMap((args) => Ref.update(ref, Arr.appendAll(args))), Effect.repeatN(n - 1), Effect.zipRight(Ref.get(ref)) ) @@ -1438,7 +1438,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. Effect.zipLeft(Console.log()), Effect.flatMap((useFallback) => useFallback - ? Effect.succeed(Array.empty()) + ? Effect.succeed(Arr.empty()) : wizardInternal(self.options as Instruction, config) ) ) @@ -1462,7 +1462,7 @@ const wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect. Effect.zipLeft(Console.log()), Effect.flatMap((useFallback) => useFallback - ? Effect.succeed(Array.empty()) + ? Effect.succeed(Arr.empty()) : wizardInternal(self.options as Instruction, config) ) ) @@ -1489,7 +1489,7 @@ const matchOptions = ( HashMap.HashMap> ] > => { - if (Array.isNonEmptyReadonlyArray(options)) { + if (Arr.isNonEmptyReadonlyArray(options)) { return findOptions(input, options, config).pipe( Effect.flatMap(([otherArgs, otherOptions, map1]) => { if (HashMap.isEmpty(map1)) { @@ -1501,7 +1501,7 @@ const matchOptions = ( } return matchOptions(otherArgs, otherOptions, config).pipe( Effect.map(([error, otherArgs, map2]) => - [error, otherArgs, merge(map1, Array.fromIterable(map2))] as [ + [error, otherArgs, merge(map1, Arr.fromIterable(map2))] as [ Option.Option, ReadonlyArray, HashMap.HashMap> @@ -1518,8 +1518,8 @@ const matchOptions = ( ) ) } - return Array.isEmptyReadonlyArray(input) - ? Effect.succeed([Option.none(), Array.empty(), HashMap.empty()] as [ + return Arr.isEmptyReadonlyArray(input) + ? Effect.succeed([Option.none(), Arr.empty(), HashMap.empty()] as [ Option.Option, ReadonlyArray, HashMap.HashMap> @@ -1547,15 +1547,15 @@ const findOptions = ( ], ValidationError.ValidationError > => - Array.matchLeft(options, { - onEmpty: () => Effect.succeed([input, Array.empty(), HashMap.empty()]), + Arr.matchLeft(options, { + onEmpty: () => Effect.succeed([input, Arr.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, Array.prepend(nextOptions, head), map] as [ + [nextArgs, Arr.prepend(nextOptions, head), map] as [ ReadonlyArray, ReadonlyArray, HashMap.HashMap> @@ -1576,7 +1576,7 @@ const findOptions = ( Effect.flatMap(([otherArgs, otherOptions, map]) => Effect.fail(e).pipe( Effect.when(() => HashMap.isEmpty(map)), - Effect.as([otherArgs, Array.prepend(otherOptions, head), map] as [ + Effect.as([otherArgs, Arr.prepend(otherOptions, head), map] as [ ReadonlyArray, ReadonlyArray, HashMap.HashMap> @@ -1587,7 +1587,7 @@ const findOptions = ( MissingFlag: () => findOptions(input, tail, config).pipe( Effect.map(([otherArgs, otherOptions, map]) => - [otherArgs, Array.prepend(otherOptions, head), map] as [ + [otherArgs, Arr.prepend(otherOptions, head), map] as [ ReadonlyArray, ReadonlyArray, HashMap.HashMap> @@ -1625,8 +1625,8 @@ const FLAG_REGEX = /^(--[^=]+)(?:=(.+))?$/ const processArgs = ( args: ReadonlyArray ): Effect.Effect, ValidationError.ValidationError> => - Array.matchLeft(args, { - onEmpty: () => Effect.succeed(Array.empty()), + Arr.matchLeft(args, { + onEmpty: () => Effect.succeed(Arr.empty()), onNonEmpty: (head, tail) => { const value = head.trim() // Attempt to match clustered short command-line arguments (i.e. `-abc`) @@ -1644,7 +1644,7 @@ const processArgs = ( const result = FLAG_REGEX.exec(value) if (result !== null && result[2] !== undefined) { return Effect.succeed>( - Array.appendAll([result[1], result[2]], tail) + Arr.appendAll([result[1], result[2]], tail) ) } } @@ -1667,7 +1667,7 @@ const parseCommandLine = ( switch (self._tag) { case "Single": { return processArgs(args).pipe(Effect.flatMap((args) => - Array.matchLeft(args, { + Arr.matchLeft(args, { onEmpty: () => { const error = InternalHelpDoc.p(`Expected to find option: '${self.fullName}'`) return Effect.fail(InternalValidationError.missingFlag(error)) @@ -1675,29 +1675,29 @@ const parseCommandLine = ( onNonEmpty: (head, tail) => { const normalize = (value: string) => InternalCliConfig.normalizeCase(config, value) const normalizedHead = normalize(head) - const normalizedNames = Array.map(getNames(self), (name) => normalize(name)) - if (Array.contains(normalizedNames, normalizedHead)) { + const normalizedNames = Arr.map(getNames(self), (name) => normalize(name)) + if (Arr.contains(normalizedNames, normalizedHead)) { if (InternalPrimitive.isBool(self.primitiveType)) { - return Array.matchLeft(tail, { + return Arr.matchLeft(tail, { onEmpty: () => { - const parsed = Option.some({ name: head, values: Array.empty() }) + const parsed = Option.some({ name: head, values: Arr.empty() }) return Effect.succeed({ parsed, leftover: tail }) }, onNonEmpty: (value, leftover) => { if (InternalPrimitive.isTrueValue(value)) { - const parsed = Option.some({ name: head, values: Array.of("true") }) + const parsed = Option.some({ name: head, values: Arr.of("true") }) return Effect.succeed({ parsed, leftover }) } if (InternalPrimitive.isFalseValue(value)) { - const parsed = Option.some({ name: head, values: Array.of("false") }) + const parsed = Option.some({ name: head, values: Arr.of("false") }) return Effect.succeed({ parsed, leftover }) } - const parsed = Option.some({ name: head, values: Array.empty() }) + const parsed = Option.some({ name: head, values: Arr.empty() }) return Effect.succeed({ parsed, leftover: tail }) } }) } - return Array.matchLeft(tail, { + return Arr.matchLeft(tail, { onEmpty: () => { const error = InternalHelpDoc.p( `Expected a value following option: '${self.fullName}'` @@ -1705,7 +1705,7 @@ const parseCommandLine = ( return Effect.fail(InternalValidationError.missingValue(error)) }, onNonEmpty: (value, leftover) => { - const parsed = Option.some({ name: head, values: Array.of(value) }) + const parsed = Option.some({ name: head, values: Arr.of(value) }) return Effect.succeed({ parsed, leftover }) } }) @@ -1727,27 +1727,27 @@ const parseCommandLine = ( )) } case "KeyValueMap": { - const normalizedNames = Array.map( + const normalizedNames = Arr.map( getNames(self.argumentOption), (name) => InternalCliConfig.normalizeCase(config, name) ) - return Array.matchLeft(args, { + return Arr.matchLeft(args, { onEmpty: () => Effect.succeed({ parsed: Option.none(), leftover: args }), onNonEmpty: (head, tail) => { const loop = ( args: ReadonlyArray ): [ReadonlyArray, ReadonlyArray] => { - let keyValues = Array.empty() + let keyValues = Arr.empty() let leftover = args as ReadonlyArray - while (Array.isNonEmptyReadonlyArray(leftover)) { - const name = Array.headNonEmpty(leftover).trim() + while (Arr.isNonEmptyReadonlyArray(leftover)) { + const name = Arr.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 && Array.contains(normalizedNames, normalizedName)) { + if (leftover.length >= 2 && Arr.contains(normalizedNames, normalizedName)) { const keyValue = leftover[1].trim() const [key, value] = keyValue.split("=") if (key !== undefined && value !== undefined && value.length > 0) { - keyValues = Array.append(keyValues, keyValue) + keyValues = Arr.append(keyValues, keyValue) leftover = leftover.slice(2) continue } @@ -1756,7 +1756,7 @@ const parseCommandLine = ( if (name.includes("=")) { const [key, value] = name.split("=") if (key !== undefined && value !== undefined && value.length > 0) { - keyValues = Array.append(keyValues, name) + keyValues = Arr.append(keyValues, name) leftover = leftover.slice(1) continue } @@ -1766,7 +1766,7 @@ const parseCommandLine = ( return [keyValues, leftover] } const normalizedName = InternalCliConfig.normalizeCase(config, head) - if (Array.contains(normalizedNames, normalizedName)) { + if (Arr.contains(normalizedNames, normalizedName)) { const [values, leftover] = loop(tail) return Effect.succeed({ parsed: Option.some({ name: head, values }), leftover }) } @@ -1775,23 +1775,23 @@ const parseCommandLine = ( }) } case "Variadic": { - const normalizedNames = Array.map( + const normalizedNames = Arr.map( getNames(self.argumentOption), (name) => InternalCliConfig.normalizeCase(config, name) ) let optionName: string | undefined = undefined - let values = Array.empty() + let values = Arr.empty() let leftover = args as ReadonlyArray - while (Array.isNonEmptyReadonlyArray(leftover)) { - const name = Array.headNonEmpty(leftover) + while (Arr.isNonEmptyReadonlyArray(leftover)) { + const name = Arr.headNonEmpty(leftover) const normalizedName = InternalCliConfig.normalizeCase(config, name) - if (leftover.length >= 2 && Array.contains(normalizedNames, normalizedName)) { + if (leftover.length >= 2 && Arr.contains(normalizedNames, normalizedName)) { if (optionName === undefined) { optionName = name } const value = leftover[1] if (value !== undefined && value.length > 0) { - values = Array.append(values, value.trim()) + values = Arr.append(values, value.trim()) leftover = leftover.slice(2) continue } @@ -1822,16 +1822,16 @@ const matchUnclustered = ( ], ValidationError.ValidationError > => { - if (Array.isNonEmptyReadonlyArray(input)) { - const flag = Array.headNonEmpty(input) - const otherFlags = Array.tailNonEmpty(input) - return findOptions(Array.of(flag), options, config).pipe( + if (Arr.isNonEmptyReadonlyArray(input)) { + const flag = Arr.headNonEmpty(input) + const otherFlags = Arr.tailNonEmpty(input) + return findOptions(Arr.of(flag), options, config).pipe( Effect.flatMap(([_, opts1, map1]) => { if (HashMap.isEmpty(map1)) { return Effect.fail( InternalValidationError.unclusteredFlag( InternalHelpDoc.empty, - Array.empty(), + Arr.empty(), tail ) ) @@ -1839,7 +1839,7 @@ const matchUnclustered = ( return matchUnclustered(otherFlags, tail, opts1, config).pipe( Effect.map(( [_, opts2, map2] - ) => [tail, opts2, merge(map1, Array.fromIterable(map2))]) + ) => [tail, opts2, merge(map1, Arr.fromIterable(map2))]) ) }) ) @@ -1854,12 +1854,12 @@ const merge = ( map1: HashMap.HashMap>, map2: ReadonlyArray<[string, ReadonlyArray]> ): HashMap.HashMap> => { - if (Array.isNonEmptyReadonlyArray(map2)) { - const head = Array.headNonEmpty(map2) - const tail = Array.tailNonEmpty(map2) + if (Arr.isNonEmptyReadonlyArray(map2)) { + const head = Arr.headNonEmpty(map2) + const tail = Arr.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], Array.appendAll(elems, head[1])) + onSome: (elems) => HashMap.set(map1, head[0], Arr.appendAll(elems, head[1])) }) return merge(newMap, tail) } @@ -1908,15 +1908,15 @@ const getShortDescription = (self: Instruction): string => { export const getBashCompletions = (self: Instruction): ReadonlyArray => { switch (self._tag) { case "Empty": { - return Array.empty() + return Arr.empty() } case "Single": { const names = getNames(self) - const cases = Array.join(names, "|") + const cases = Arr.join(names, "|") const compgen = InternalPrimitive.getBashCompletions( self.primitiveType as InternalPrimitive.Instruction ) - return Array.make( + return Arr.make( `${cases})`, ` COMPREPLY=( ${compgen} )`, ` return 0`, @@ -1936,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 Array.appendAll(left, right) + return Arr.appendAll(left, right) } } } @@ -1945,26 +1945,26 @@ export const getBashCompletions = (self: Instruction): ReadonlyArray => export const getFishCompletions = (self: Instruction): Array => { switch (self._tag) { case "Empty": { - return Array.empty() + return Arr.empty() } case "Single": { const description = getShortDescription(self) const order = Order.mapInput(Order.boolean, (tuple: readonly [boolean, string]) => !tuple[0]) return pipe( - 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( + Arr.prepend(self.aliases, self.name), + Arr.map((name) => [name.length === 1, name] as const), + Arr.sort(order), + Arr.flatMap(([isShort, name]) => Arr.make(isShort ? "-s" : "-l", name)), + Arr.appendAll(InternalPrimitive.getFishCompletions( self.primitiveType as InternalPrimitive.Instruction )), - Array.appendAll( + Arr.appendAll( description.length === 0 - ? Array.empty() - : Array.of(`-d '${description}'`) + ? Arr.empty() + : Arr.of(`-d '${description}'`) ), - Array.join(" "), - Array.of + Arr.join(" "), + Arr.of ) } case "KeyValueMap": @@ -1980,7 +1980,7 @@ export const getFishCompletions = (self: Instruction): Array => { case "OrElse": { return pipe( getFishCompletions(self.left as Instruction), - Array.appendAll(getFishCompletions(self.right as Instruction)) + Arr.appendAll(getFishCompletions(self.right as Instruction)) ) } } @@ -1994,11 +1994,11 @@ interface ZshCompletionState { /** @internal */ export const getZshCompletions = ( self: Instruction, - state: ZshCompletionState = { conflicts: Array.empty(), multiple: false } + state: ZshCompletionState = { conflicts: Arr.empty(), multiple: false } ): Array => { switch (self._tag) { case "Empty": { - return Array.empty() + return Arr.empty() } case "Single": { const names = getNames(self) @@ -2007,10 +2007,10 @@ export const getZshCompletions = ( self.primitiveType as InternalPrimitive.Instruction ) const multiple = state.multiple ? "*" : "" - const conflicts = Array.isNonEmptyReadonlyArray(state.conflicts) - ? `(${Array.join(state.conflicts, " ")})` + const conflicts = Arr.isNonEmptyReadonlyArray(state.conflicts) + ? `(${Arr.join(state.conflicts, " ")})` : "" - return Array.map( + return Arr.map( names, (name) => `${conflicts}${multiple}${name}[${escape(description)}]${possibleValues}` ) @@ -2026,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 Array.appendAll(left, right) + return Arr.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: Array.appendAll(state.conflicts, rightNames) } + { ...state, conflicts: Arr.appendAll(state.conflicts, rightNames) } ) const right = getZshCompletions( self.right as Instruction, - { ...state, conflicts: Array.appendAll(state.conflicts, leftNames) } + { ...state, conflicts: Arr.appendAll(state.conflicts, leftNames) } ) - return Array.appendAll(left, right) + return Arr.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 72a0286ada..3185902967 100644 --- a/packages/cli/src/internal/primitive.ts +++ b/packages/cli/src/internal/primitive.ts @@ -1,6 +1,6 @@ import * as FileSystem from "@effect/platform/FileSystem" import * as Schema from "@effect/schema/Schema" -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Effect from "effect/Effect" import { dual, pipe } from "effect/Function" import * as Option from "effect/Option" @@ -258,8 +258,8 @@ const getChoicesInternal = (self: Instruction): Option.Option => { } case "Choice": { const choices = pipe( - Array.map(self.alternatives, ([choice]) => choice), - Array.join(" | ") + Arr.map(self.alternatives, ([choice]) => choice), + Arr.join(" | ") ) return Option.some(choices) } @@ -283,8 +283,8 @@ const getHelpInternal = (self: Instruction): Span.Span => { } case "Choice": { const choices = pipe( - Array.map(self.alternatives, ([choice]) => choice), - Array.join(", ") + Arr.map(self.alternatives, ([choice]) => choice), + Arr.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) => Array.findFirst(self.alternatives, ([choice]) => choice === value)), + Effect.flatMap((value) => Arr.findFirst(self.alternatives, ([choice]) => choice === value)), Effect.mapBoth({ onFailure: () => { const choices = pipe( - Array.map(self.alternatives, ([choice]) => choice), - Array.join(", ") + Arr.map(self.alternatives, ([choice]) => choice), + Arr.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: Array.map( + choices: Arr.map( self.alternatives, ([title]) => ({ title, value: title }) ) @@ -625,8 +625,8 @@ export const getBashCompletions = (self: Instruction): string => { } case "Choice": { const choices = pipe( - Array.map(self.alternatives, ([choice]) => choice), - Array.join(",") + Arr.map(self.alternatives, ([choice]) => choice), + Arr.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 Array.empty() + return Arr.empty() } case "DateTime": case "Float": case "Integer": case "Secret": case "Text": { - return Array.make("-r", "-f") + return Arr.make("-r", "-f") } case "Path": { switch (self.pathType) { case "file": { return self.pathExists === "yes" || self.pathExists === "either" - ? Array.make("-r", "-F") - : Array.make("-r") + ? Arr.make("-r", "-F") + : Arr.make("-r") } case "directory": { return self.pathExists === "yes" || self.pathExists === "either" - ? Array.make( + ? Arr.make( "-r", "-f", "-a", `"(__fish_complete_directories (commandline -ct))"` ) - : Array.make("-r") + : Arr.make("-r") } case "either": { return self.pathExists === "yes" || self.pathExists === "either" - ? Array.make("-r", "-F") - : Array.make("-r") + ? Arr.make("-r", "-F") + : Arr.make("-r") } } } case "Choice": { const choices = pipe( - Array.map(self.alternatives, ([choice]) => `${choice}''`), - Array.join(",") + Arr.map(self.alternatives, ([choice]) => `${choice}''`), + Arr.join(",") ) - return Array.make("-r", "-f", "-a", `"{${choices}}"`) + return Arr.make("-r", "-f", "-a", `"{${choices}}"`) } } } @@ -688,8 +688,8 @@ export const getZshCompletions = (self: Instruction): string => { } case "Choice": { const choices = pipe( - Array.map(self.alternatives, ([name]) => name), - Array.join(" ") + Arr.map(self.alternatives, ([name]) => name), + Arr.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 0f7a9af0af..839100e9d1 100644 --- a/packages/cli/src/internal/prompt/ansi-utils.ts +++ b/packages/cli/src/internal/prompt/ansi-utils.ts @@ -1,5 +1,5 @@ import * as Doc from "@effect/printer-ansi/AnsiDoc" -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" @@ -62,7 +62,7 @@ export const lines = (prompt: string, columns: number): number => { return columns === 0 ? lines.length : pipe( - Array.map(lines, (line) => Math.ceil(line.length / columns)), - Array.reduce(0, (left, right) => left + right) + Arr.map(lines, (line) => Math.ceil(line.length / columns)), + Arr.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 08fa5bee68..8d5be0a224 100644 --- a/packages/cli/src/internal/prompt/confirm.ts +++ b/packages/cli/src/internal/prompt/confirm.ts @@ -2,7 +2,7 @@ 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 Arr from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" @@ -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 Array.match(options.message.split(/\r?\n/), { + return Arr.match(options.message.split(/\r?\n/), { onEmpty: () => Doc.hsep([prefix, trailingSymbol, confirm]), onNonEmpty: (promptLines) => { - const lines = Array.map(promptLines, (line) => annotateLine(line)) + const lines = Arr.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 34baa3bd3b..025c41c05e 100644 --- a/packages/cli/src/internal/prompt/date.ts +++ b/packages/cli/src/internal/prompt/date.ts @@ -2,7 +2,7 @@ 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 Arr from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Match from "effect/Match" @@ -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 (Array.isNonEmptyReadonlyArray(errorLines)) { + if (Arr.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 = Array.map(errorLines, (str) => annotateLine(str)) + const lines = Arr.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) => - Array.reduce( + Arr.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 Array.match(options.message.split(/\r?\n/), { + return Arr.match(options.message.split(/\r?\n/), { onEmpty: () => Doc.hsep([prefix, trailingSymbol, parts]), onNonEmpty: (promptLines) => { - const lines = Array.map(promptLines, (line) => annotateLine(line)) + const lines = Arr.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 - }, Array.empty()) + }, Arr.empty()) parts.splice(0, parts.length, ...orderedParts) return parts } @@ -400,9 +400,9 @@ abstract class DatePart { */ nextPart(): Option.Option { return pipe( - Array.findFirstIndex(this.parts, (part) => part === this), + Arr.findFirstIndex(this.parts, (part) => part === this), Option.flatMap((currentPartIndex) => - Array.findFirst(this.parts.slice(currentPartIndex + 1), (part) => !part.isToken()) + Arr.findFirst(this.parts.slice(currentPartIndex + 1), (part) => !part.isToken()) ) ) } @@ -412,9 +412,9 @@ abstract class DatePart { */ previousPart(): Option.Option { return pipe( - Array.findFirstIndex(this.parts, (part) => part === this), + Arr.findFirstIndex(this.parts, (part) => part === this), Option.flatMap((currentPartIndex) => - Array.findLast(this.parts.slice(0, currentPartIndex), (part) => !part.isToken()) + Arr.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 24aa08bf2c..ff506cdc7e 100644 --- a/packages/cli/src/internal/prompt/number.ts +++ b/packages/cli/src/internal/prompt/number.ts @@ -3,7 +3,7 @@ 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 Arr from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" @@ -67,13 +67,13 @@ const renderError = (nextState: State, pointer: Doc.AnsiDoc): Doc.AnsiDoc => Option.match(nextState.error, { onNone: () => Doc.empty, onSome: (error) => - Array.match(error.split(/\r?\n/), { + Arr.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 = Array.map(errorLines, (str) => annotateLine(str)) + const lines = Arr.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 Array.match(options.message.split(/\r?\n/), { + return Arr.match(options.message.split(/\r?\n/), { onEmpty: () => Doc.hsep([prefix, trailingSymbol, renderInput(nextState, submitted)]), onNonEmpty: (promptLines) => { - const lines = Array.map(promptLines, (line) => annotateLine(line)) + const lines = Arr.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 9120c2c0ab..2ede516a66 100644 --- a/packages/cli/src/internal/prompt/select.ts +++ b/packages/cli/src/internal/prompt/select.ts @@ -1,7 +1,7 @@ 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 Arr from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" @@ -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 = Array.map(choicesToRender, (choice, currentIndex) => { + const docs = Arr.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 Array.match(options.message.split(/\r?\n/), { + return Arr.match(options.message.split(/\r?\n/), { onEmpty: () => Doc.hsep([prefix, trailingSymbol]), onNonEmpty: (promptLines) => { - const lines = Array.map(promptLines, (line) => annotateLine(line)) + const lines = Arr.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 f2fad7a793..a8958c8c59 100644 --- a/packages/cli/src/internal/prompt/text.ts +++ b/packages/cli/src/internal/prompt/text.ts @@ -2,7 +2,7 @@ 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 Arr from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" @@ -86,7 +86,7 @@ const renderError = (nextState: State, pointer: Doc.AnsiDoc): Doc.AnsiDoc => Option.match(nextState.error, { onNone: () => Doc.empty, onSome: (error) => - Array.match(error.split(/\r?\n/), { + Arr.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 = Array.map(errorLines, (str) => annotateLine(str)) + const lines = Arr.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 (Array.isNonEmptyReadonlyArray(promptLines)) { - const lines = Array.map(promptLines, (line) => annotateLine(line)) + if (Arr.isNonEmptyReadonlyArray(promptLines)) { + const lines = Arr.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 c514386cee..7110602043 100644 --- a/packages/cli/src/internal/prompt/toggle.ts +++ b/packages/cli/src/internal/prompt/toggle.ts @@ -2,7 +2,7 @@ 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 Arr from "effect/Array" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" import * as Option from "effect/Option" @@ -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 (Array.isNonEmptyReadonlyArray(promptLines)) { - const lines = Array.map(promptLines, (line) => annotateLine(line)) + if (Arr.isNonEmptyReadonlyArray(promptLines)) { + const lines = Arr.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 86050940c8..593a6ca291 100644 --- a/packages/cli/src/internal/usage.ts +++ b/packages/cli/src/internal/usage.ts @@ -1,4 +1,4 @@ -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import { dual, pipe } from "effect/Function" import * as Option from "effect/Option" import type * as CliConfig from "../CliConfig.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 (Array.isNonEmptyReadonlyArray(spans)) { - const head = Array.headNonEmpty(spans) - const tail = Array.tailNonEmpty(spans) - if (Array.isNonEmptyReadonlyArray(tail)) { + if (Arr.isNonEmptyReadonlyArray(spans)) { + const head = Arr.headNonEmpty(spans) + const tail = Arr.tailNonEmpty(spans) + if (Arr.isNonEmptyReadonlyArray(tail)) { return pipe( - Array.map(spans, (span) => InternalHelpDoc.p(span)), - Array.reduceRight( + Arr.map(spans, (span) => InternalHelpDoc.p(span)), + Arr.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(Array.head(render(self, config)))) { + if (Option.isNone(Arr.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 Array.of(InternalSpan.text("")) + return Arr.of(InternalSpan.text("")) } case "Mixed": { - return Array.of(InternalSpan.text("")) + return Arr.of(InternalSpan.text("")) } case "Named": { const typeInfo = config.showTypes @@ -169,24 +169,24 @@ const render = (self: Usage.Usage, config: CliConfig.CliConfig): Array 1 ? pipe( - Array.filter(self.names, (name) => name.startsWith("--")), - Array.head, - Option.map(Array.of), + Arr.filter(self.names, (name) => name.startsWith("--")), + Arr.head, + Option.map(Arr.of), Option.getOrElse(() => self.names) ) : self.names - const nameInfo = InternalSpan.text(Array.join(namesToShow, ", ")) + const nameInfo = InternalSpan.text(Arr.join(namesToShow, ", ")) return config.showAllNames && self.names.length > 1 - ? Array.of(InternalSpan.spans([ + ? Arr.of(InternalSpan.spans([ InternalSpan.text("("), nameInfo, typeInfo, InternalSpan.text(")") ])) - : Array.of(InternalSpan.concat(nameInfo, typeInfo)) + : Arr.of(InternalSpan.concat(nameInfo, typeInfo)) } case "Optional": { - return Array.map(render(self.usage, config), (span) => + return Arr.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 - Array.map( + Arr.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 Array.map(rightSpan, (right) => InternalSpan.spans([left, separator, right])) + (left) => Arr.map(rightSpan, (right) => InternalSpan.spans([left, separator, right])) ) } } diff --git a/packages/effect/src/Brand.ts b/packages/effect/src/Brand.ts index 2ff9bce4d7..daf781fac6 100644 --- a/packages/effect/src/Brand.ts +++ b/packages/effect/src/Brand.ts @@ -16,7 +16,7 @@ * * @since 2.0.0 */ -import * as Array from "./Array.js" +import * as Arr from "./Array.js" import * as Either from "./Either.js" import { identity } from "./Function.js" import * as Option from "./Option.js" @@ -183,7 +183,7 @@ export const error = (message: string, meta?: unknown): Brand.BrandErrors => [{ */ export const errors: (...errors: Array) => Brand.BrandErrors = ( ...errors: Array -): Brand.BrandErrors => Array.flatten(errors) +): Brand.BrandErrors => Arr.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/Cron.ts b/packages/effect/src/Cron.ts index 42a0e2a936..2087883d34 100644 --- a/packages/effect/src/Cron.ts +++ b/packages/effect/src/Cron.ts @@ -1,7 +1,7 @@ /** * @since 2.0.0 */ -import * as Array from "./Array.js" +import * as Arr from "./Array.js" import * as Either from "./Either.js" import * as Equal from "./Equal.js" import * as equivalence from "./Equivalence.js" @@ -46,11 +46,11 @@ const CronProto: Omit }): Cron => { const o: Mutable = Object.create(CronProto) - 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)) + o.minutes = new Set(Arr.sort(minutes, N.Order)) + o.hours = new Set(Arr.sort(hours, N.Order)) + o.days = new Set(Arr.sort(days, N.Order)) + o.months = new Set(Arr.sort(months, N.Order)) + o.weekdays = new Set(Arr.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(Array.fromIterable(self), Array.fromIterable(that)) + restrictionsArrayEquals(Arr.fromIterable(self), Arr.fromIterable(that)) /** * Checks if two `Cron`s are equal. diff --git a/packages/effect/src/List.ts b/packages/effect/src/List.ts index a1e95dd856..407eac7320 100644 --- a/packages/effect/src/List.ts +++ b/packages/effect/src/List.ts @@ -21,7 +21,7 @@ * Licensed under Apache License 2.0 * (http://www.apache.org/licenses/LICENSE-2.0). */ -import * as Array from "./Array.js" +import * as Arr from "./Array.js" import * as Chunk from "./Chunk.js" import * as Either from "./Either.js" import * as Equal from "./Equal.js" @@ -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.fromIterable(self) +export const toArray = (self: List): Array => Arr.fromIterable(self) /** * @category equivalence * @since 2.0.0 */ export const getEquivalence = (isEquivalent: Equivalence.Equivalence): Equivalence.Equivalence> => - Equivalence.mapInput(Array.getEquivalence(isEquivalent), toArray) + Equivalence.mapInput(Arr.getEquivalence(isEquivalent), toArray) const _equivalence = getEquivalence(Equal.equals) diff --git a/packages/effect/src/internal/cause.ts b/packages/effect/src/internal/cause.ts index 883bdc6b80..77068237bf 100644 --- a/packages/effect/src/internal/cause.ts +++ b/packages/effect/src/internal/cause.ts @@ -1,4 +1,4 @@ -import * as Array from "../Array.js" +import * as Arr from "../Array.js" import type * as Cause from "../Cause.js" import * as Chunk from "../Chunk.js" import * as Either from "../Either.js" @@ -584,7 +584,7 @@ const flattenCauseLoop = ( while (1) { const [parallel, sequential] = pipe( causes, - Array.reduce( + Arr.reduce( [HashSet.empty(), Chunk.empty>()] as const, ([parallel, sequential], cause) => { const [par, seq] = evaluateCause(cause) diff --git a/packages/effect/src/internal/configProvider.ts b/packages/effect/src/internal/configProvider.ts index bccd0b6848..e30a3cb010 100644 --- a/packages/effect/src/internal/configProvider.ts +++ b/packages/effect/src/internal/configProvider.ts @@ -1,4 +1,4 @@ -import * as Array from "../Array.js" +import * as Arr from "../Array.js" import type * as Config from "../Config.js" import type * as ConfigError from "../ConfigError.js" import type * as ConfigProvider from "../ConfigProvider.js" @@ -85,12 +85,12 @@ export const makeFlat = ( export const fromFlat = (flat: ConfigProvider.ConfigProvider.Flat): ConfigProvider.ConfigProvider => make({ load: (config) => - core.flatMap(fromFlatLoop(flat, Array.empty(), config, false), (chunk) => - Option.match(Array.head(chunk), { + core.flatMap(fromFlatLoop(flat, Arr.empty(), config, false), (chunk) => + Option.match(Arr.head(chunk), { onNone: () => core.fail( configError.MissingData( - Array.empty(), + Arr.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, Array.join(pathDelim)) + const makePathString = (path: ReadonlyArray): string => pipe(path, Arr.join(pathDelim)) const unmakePathString = (pathString: string): ReadonlyArray => pathString.split(pathDelim) const getEnv = () => @@ -134,7 +134,7 @@ export const fromEnv = ( 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, Array.unsafeGet(i)) + const pathComponent = pipe(path, Arr.unsafeGet(i)) const currentElement = keyPath[i] if (currentElement === undefined || pathComponent !== currentElement) { return false @@ -154,7 +154,7 @@ export const fromMap = ( config?: Partial ): ConfigProvider.ConfigProvider => { const { pathDelim, seqDelim } = Object.assign({ seqDelim: ",", pathDelim: "." }, config) - const makePathString = (path: ReadonlyArray): string => pipe(path, Array.join(pathDelim)) + const makePathString = (path: ReadonlyArray): string => pipe(path, Arr.join(pathDelim)) const unmakePathString = (pathString: string): ReadonlyArray => pathString.split(pathDelim) const mapWithIndexSplit = splitIndexInKeys( map, @@ -180,10 +180,10 @@ export const fromMap = ( path: ReadonlyArray ): Effect.Effect, ConfigError.ConfigError> => core.sync(() => { - const keyPaths = Array.fromIterable(mapWithIndexSplit.keys()).map(unmakePathString) + const keyPaths = Arr.fromIterable(mapWithIndexSplit.keys()).map(unmakePathString) const filteredKeyPaths = keyPaths.filter((keyPath) => { for (let i = 0; i < path.length; i++) { - const pathComponent = pipe(path, Array.unsafeGet(i)) + const pathComponent = pipe(path, Arr.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 = Array.unfold( + const leftPad = Arr.unfold( left.length, (index) => index >= right.length ? Option.none() : Option.some([leftDef(index), index + 1]) ) - const rightPad = Array.unfold( + const rightPad = Arr.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(Array.of(op.value)) as Effect.Effect, ConfigError.ConfigError> + return core.succeed(Arr.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, Array.of(op.name)), + concat(prefix, Arr.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(Array.last(prefix), Option.getOrElse(() => "")) + const name = pipe(Arr.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), Array.of) + core.map(fromFlatLoop(flat, patchedPrefix, op.config, true), Arr.of) ) as unknown as Effect.Effect, ConfigError.ConfigError> } return pipe( core.forEachSequential( indices, - (index) => fromFlatLoop(flat, Array.append(prefix, `[${index}]`), op.config, true) + (index) => fromFlatLoop(flat, Arr.append(prefix, `[${index}]`), op.config, true) ), core.map((chunkChunk) => { - const flattened = Array.flatten(chunkChunk) + const flattened = Arr.flatten(chunkChunk) if (flattened.length === 0) { - return Array.of(Array.empty()) + return Arr.of(Arr.empty()) } - return Array.of(flattened) + return Arr.of(flattened) }) ) as unknown as Effect.Effect, ConfigError.ConfigError> }) @@ -363,18 +363,18 @@ const fromFlatLoop = ( core.forEachSequential((key) => fromFlatLoop( flat, - concat(prefix, Array.of(key)), + concat(prefix, Arr.of(key)), op.valueConfig, split ) ), core.map((matrix) => { if (matrix.length === 0) { - return Array.of(HashMap.empty()) + return Arr.of(HashMap.empty()) } return pipe( transpose(matrix), - Array.map((values) => HashMap.fromIterable(Array.zip(Array.fromIterable(keys), values))) + Arr.map((values) => HashMap.fromIterable(Arr.zip(Arr.fromIterable(keys), values))) ) }) ) @@ -404,17 +404,17 @@ const fromFlatLoop = ( return core.fail(right.left) } if (Either.isRight(left) && Either.isRight(right)) { - const path = pipe(prefix, Array.join(".")) + const path = pipe(prefix, Arr.join(".")) const fail = fromFlatLoopFail(prefix, path) const [lefts, rights] = extend( fail, fail, - pipe(left.right, Array.map(Either.right)), - pipe(right.right, Array.map(Either.right)) + pipe(left.right, Arr.map(Either.right)), + pipe(right.right, Arr.map(Either.right)) ) return pipe( lefts, - Array.zip(rights), + Arr.zip(rights), core.forEachSequential(([left, right]) => pipe( core.zip(left, right), @@ -587,8 +587,8 @@ export const within = dual< f: (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider ) => ConfigProvider.ConfigProvider >(3, (self, path, f) => { - const unnest = Array.reduce(path, self, (provider, name) => unnested(provider, name)) - const nest = Array.reduceRight(path, f(unnest), (provider, name) => nested(provider, name)) + const unnest = Arr.reduce(path, self, (provider, name) => unnested(provider, name)) + const nest = Arr.reduceRight(path, f(unnest), (provider, name) => nested(provider, name)) return orElse(nest, () => self) }) @@ -609,7 +609,7 @@ const parsePrimitive = ( primitive.parse(text), core.mapBoth({ onFailure: configError.prefixed(path), - onSuccess: Array.of + onSuccess: Arr.of }) ) } @@ -628,8 +628,8 @@ const indicesFrom = (quotedIndices: HashSet.HashSet): Effect.Effect Array.empty(), - onSuccess: Array.sort(number.Order) + onFailure: () => Arr.empty(), + onSuccess: Arr.sort(number.Order) }), core.either, core.map(Either.merge) @@ -661,10 +661,10 @@ const splitIndexInKeys = ( for (const [pathString, value] of map) { const keyWithIndex = pipe( unmakePathString(pathString), - Array.flatMap((key) => + Arr.flatMap((key) => Option.match(splitIndexFrom(key), { - onNone: () => Array.of(key), - onSome: ([key, index]) => Array.make(key, `[${index}]`) + onNone: () => Arr.of(key), + onSome: ([key, index]) => Arr.make(key, `[${index}]`) }) ) ) @@ -717,7 +717,7 @@ interface JsonArray extends Array { const hiddenDelimiter = "\ufeff" - const indexedEntries = Array.map( + const indexedEntries = Arr.map( getIndexedEntries(json as JsonMap), ([key, value]): [string, string] => [configPathToString(key).join(hiddenDelimiter), value] ) @@ -759,38 +759,38 @@ const getIndexedEntries = ( value: string | number | boolean | JsonMap | JsonArray | null ): ReadonlyArray<[path: ReadonlyArray, value: string]> => { if (typeof value === "string") { - return Array.make([path, value] as [ReadonlyArray, string]) + return Arr.make([path, value] as [ReadonlyArray, string]) } if (typeof value === "number" || typeof value === "boolean") { - return Array.make([path, String(value)] as [ReadonlyArray, string]) + return Arr.make([path, String(value)] as [ReadonlyArray, string]) } - if (Array.isArray(value)) { + if (Arr.isArray(value)) { return loopArray(path, value) } if (typeof value === "object" && value !== null) { return loopObject(path, value) } - return Array.empty<[ReadonlyArray, string]>() + return Arr.empty<[ReadonlyArray, string]>() } const loopArray = ( path: ReadonlyArray, values: JsonArray ): ReadonlyArray<[path: ReadonlyArray, value: string]> => - Array.match(values, { - onEmpty: () => Array.make([path, ""] as [ReadonlyArray, string]), - onNonEmpty: Array.flatMap((value, index) => loopAny(Array.append(path, keyIndex(index)), value)) + Arr.match(values, { + onEmpty: () => Arr.make([path, ""] as [ReadonlyArray, string]), + onNonEmpty: Arr.flatMap((value, index) => loopAny(Arr.append(path, keyIndex(index)), value)) }) const loopObject = ( path: ReadonlyArray, value: JsonMap ): ReadonlyArray<[path: ReadonlyArray, value: string]> => Object.entries(value).flatMap(([key, value]) => { - const newPath = Array.append(path, keyName(key)) + const newPath = Arr.append(path, keyName(key)) const result = loopAny(newPath, value) - if (Array.isEmptyReadonlyArray(result)) { - return Array.make([newPath, ""] as [ReadonlyArray, string]) + if (Arr.isEmptyReadonlyArray(result)) { + return Arr.make([newPath, ""] as [ReadonlyArray, string]) } return result }) - return loopObject(Array.empty(), config) + return loopObject(Arr.empty(), config) } diff --git a/packages/effect/src/internal/core-effect.ts b/packages/effect/src/internal/core-effect.ts index 261a30d07e..f7357d427a 100644 --- a/packages/effect/src/internal/core-effect.ts +++ b/packages/effect/src/internal/core-effect.ts @@ -1,4 +1,4 @@ -import * as Array from "../Array.js" +import * as Arr from "../Array.js" import type * as Cause from "../Cause.js" import * as Chunk from "../Chunk.js" import * as Clock from "../Clock.js" @@ -512,7 +512,7 @@ export const filterMap = dual< >(2, (elements, pf) => core.map( core.forEachSequential(elements, identity), - Array.filterMap(pf) + Arr.filterMap(pf) )) /* @internal */ @@ -695,7 +695,7 @@ export const firstSuccessOf = >( } return pipe( Chunk.tailNonEmpty(list), - Array.reduce(Chunk.headNonEmpty(list), (left, right) => core.orElse(left, () => right) as Eff) + Arr.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.fromIterable) + : core.map(loopInternal(initial, options.while, options.step, options.body), Arr.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.fromIterable(internalCause.failures(cause)) + const errors = Arr.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 ) => - Array.fromIterable(elements).reduce( + Arr.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) => - Array.fromIterable(elements).reduceRight( + Arr.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) => Array.union(old, labels)) + (self, labels) => core.fiberRefLocallyWith(self, core.currentMetricLabels, (old) => Arr.union(old, labels)) ) /* @internal */ @@ -2082,7 +2082,7 @@ export const unsafeMakeSpan = ( ...(options?.links ?? []) ] : Chunk.toReadonlyArray(linksFromEnv.value) : - options?.links ?? Array.empty() + options?.links ?? Arr.empty() const span = tracer.span( name, diff --git a/packages/effect/src/internal/core.ts b/packages/effect/src/internal/core.ts index 86af70a272..6e2a397d6b 100644 --- a/packages/effect/src/internal/core.ts +++ b/packages/effect/src/internal/core.ts @@ -1,4 +1,4 @@ -import * as Array from "../Array.js" +import * as Arr from "../Array.js" import type * as Cause from "../Cause.js" import * as Chunk from "../Chunk.js" import * as Context from "../Context.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 = Array.fromIterable(self) - const ret = Array.allocate(arr.length) + const arr = Arr.fromIterable(self) + const ret = Arr.allocate(arr.length) let i = 0 return as( whileLoop({ @@ -910,7 +910,7 @@ export const forEachSequentialDiscard: { 2, (self: Iterable, f: (a: A, i: number) => Effect.Effect): Effect.Effect => suspend(() => { - const arr = Array.fromIterable(self) + const arr = Arr.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] => - Array.fromIterable(elements).reduceRight( + Arr.fromIterable(elements).reduceRight( ([lefts, rights], current) => { const either = f(current) switch (either._tag) { @@ -1168,7 +1168,7 @@ export const partitionMap = ( } } }, - [Array.empty(), Array.empty()] + [Arr.empty(), Arr.empty()] ) /* @internal */ @@ -2000,7 +2000,7 @@ export const withUnhandledErrorLogLevel = dual< /** @internal */ export const currentMetricLabels: FiberRef.FiberRef> = globalValue( Symbol.for("effect/FiberRef/currentMetricLabels"), - () => fiberRefUnsafeMakeReadonlyArray(Array.empty()) + () => fiberRefUnsafeMakeReadonlyArray(Arr.empty()) ) /* @internal */ @@ -2110,8 +2110,8 @@ export const causeSquashWith = dual< Chunk.head, Option.match({ onNone: () => { - const interrupts = Array.fromIterable(internalCause.interruptors(self)).flatMap((fiberId) => - Array.fromIterable(FiberId.ids(fiberId)).map((id) => `#${id}`) + const interrupts = Arr.fromIterable(internalCause.interruptors(self)).flatMap((fiberId) => + Arr.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), - Array.reduce( + Arr.reduce( pipe(Chunk.headNonEmpty(list), exitMap>(Chunk.of)), (accumulator, current) => pipe( diff --git a/packages/effect/src/internal/differ/readonlyArrayPatch.ts b/packages/effect/src/internal/differ/readonlyArrayPatch.ts index 0b2aa31002..2cf69801b8 100644 --- a/packages/effect/src/internal/differ/readonlyArrayPatch.ts +++ b/packages/effect/src/internal/differ/readonlyArrayPatch.ts @@ -1,4 +1,4 @@ -import * as Array from "../../Array.js" +import * as Arr from "../../Array.js" import type * as Differ from "../../Differ.js" import * as Equal from "../../Equal.js" import * as Dual from "../../Function.js" @@ -135,7 +135,7 @@ export const diff = ( patch = combine(patch, makeSlice(0, i)) } if (i < options.newValue.length) { - patch = combine(patch, makeAppend(Array.drop(i)(options.newValue))) + patch = combine(patch, makeAppend(Arr.drop(i)(options.newValue))) } return patch } @@ -173,10 +173,10 @@ export const patch = Dual.dual< return oldValue } let readonlyArray = oldValue.slice() - let patches: Array> = Array.of(self) - while (Array.isNonEmptyArray(patches)) { - const head: Instruction = Array.headNonEmpty(patches) as Instruction - const tail = Array.tailNonEmpty(patches) + let patches: Array> = Arr.of(self) + while (Arr.isNonEmptyArray(patches)) { + const head: Instruction = Arr.headNonEmpty(patches) as Instruction + const tail = Arr.tailNonEmpty(patches) switch (head._tag) { case "Empty": { patches = tail diff --git a/packages/effect/src/internal/metric.ts b/packages/effect/src/internal/metric.ts index f4a510e5fa..43f0b2d9f9 100644 --- a/packages/effect/src/internal/metric.ts +++ b/packages/effect/src/internal/metric.ts @@ -1,4 +1,4 @@ -import * as Array from "../Array.js" +import * as Arr from "../Array.js" import * as Clock from "../Clock.js" import * as Duration from "../Duration.js" import type * as Effect from "../Effect.js" @@ -275,7 +275,7 @@ export const taggedWithLabelsInput = dual< (input, extraTags) => self.unsafeUpdate( input, - Array.union(f(input), extraTags) + Arr.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, Array.union(extraTags, extraTags1)), - (extraTags1) => self.unsafeValue(Array.union(extraTags, extraTags1)) + (input, extraTags1) => self.unsafeUpdate(input, Arr.union(extraTags, extraTags1)), + (extraTags1) => self.unsafeValue(Arr.union(extraTags, extraTags1)) ) }) diff --git a/packages/effect/src/internal/metric/boundaries.ts b/packages/effect/src/internal/metric/boundaries.ts index d7e93c95d0..6c5a67f3bb 100644 --- a/packages/effect/src/internal/metric/boundaries.ts +++ b/packages/effect/src/internal/metric/boundaries.ts @@ -1,4 +1,4 @@ -import * as Array from "../../Array.js" +import * as Arr from "../../Array.js" import * as Chunk from "../../Chunk.js" import * as Equal from "../../Equal.js" import { pipe } from "../../Function.js" @@ -44,8 +44,8 @@ export const isMetricBoundaries = (u: unknown): u is MetricBoundaries.MetricBoun export const fromIterable = (iterable: Iterable): MetricBoundaries.MetricBoundaries => { const values = pipe( iterable, - Array.appendAll(Chunk.of(Number.POSITIVE_INFINITY)), - Array.dedupe + Arr.appendAll(Chunk.of(Number.POSITIVE_INFINITY)), + Arr.dedupe ) return new MetricBoundariesImpl(values) } @@ -57,7 +57,7 @@ export const linear = (options: { readonly count: number }): MetricBoundaries.MetricBoundaries => pipe( - Array.makeBy(options.count - 1, (i) => options.start + i * options.width), + Arr.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( - Array.makeBy(options.count - 1, (i) => options.start * Math.pow(options.factor, i)), + Arr.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 d38277fb06..d8f2688778 100644 --- a/packages/effect/src/internal/metric/hook.ts +++ b/packages/effect/src/internal/metric/hook.ts @@ -1,4 +1,4 @@ -import * as Array from "../../Array.js" +import * as Arr from "../../Array.js" import * as Duration from "../../Duration.js" import type { LazyArg } from "../../Function.js" import { dual, pipe } from "../../Function.js" @@ -123,8 +123,8 @@ export const histogram = (key: MetricKey.MetricKey.Histogram): MetricHook.Metric pipe( bounds, - Array.sort(number.Order), - Array.map((n, i) => { + Arr.sort(number.Order), + Arr.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.allocate(size) as any + const builder: Array = Arr.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, Array.sort(number.Order)) - const values = Array.allocate(maxSize) + const sortedQuantiles = pipe(quantiles, Arr.sort(number.Order)) + const values = Arr.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, - Array.sort(builder, number.Order) + Arr.sort(builder, number.Order) ) } @@ -291,8 +291,8 @@ const calculateQuantiles = ( ): ReadonlyArray]> => { // The number of samples examined const sampleCount = sortedSamples.length - if (!Array.isNonEmptyReadonlyArray(sortedQuantiles)) { - return Array.empty() + if (!Arr.isNonEmptyReadonlyArray(sortedQuantiles)) { + return Arr.empty() } const head = sortedQuantiles[0] const tail = sortedQuantiles.slice(1) @@ -304,7 +304,7 @@ const calculateQuantiles = ( head, sortedSamples ) - const resolved = Array.of(resolvedHead) + const resolved = Arr.of(resolvedHead) tail.forEach((quantile) => { resolved.push( resolveQuantile( @@ -317,7 +317,7 @@ const calculateQuantiles = ( ) ) }) - return Array.map(resolved, (rq) => [rq.quantile, rq.value] as const) + return Arr.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 (!Array.isNonEmptyReadonlyArray(rest_1)) { + if (!Arr.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(Array.lastNonEmpty(rest_1)), + value: Option.some(Arr.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 = Array.span(rest_1, (n) => n <= rest_1[0]) + const sameHead = Arr.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 = Array.head(rest_1) + current_2 = Arr.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 = Array.head(rest_1) + current_2 = Arr.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 = Array.head(rest_1) + current_2 = Arr.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 4bda8b45e9..50f4439dbf 100644 --- a/packages/effect/src/internal/metric/key.ts +++ b/packages/effect/src/internal/metric/key.ts @@ -1,4 +1,4 @@ -import * as Array from "../../Array.js" +import * as Arr from "../../Array.js" import type * as Duration from "../../Duration.js" import * as Equal from "../../Equal.js" import { dual, pipe } from "../../Function.js" @@ -26,7 +26,7 @@ const metricKeyVariance = { _Type: (_: never) => _ } -const arrayEquivilence = Array.getEquivalence(Equal.equals) +const arrayEquivilence = Arr.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, Array.union(self.tags, extraTags))) + : new MetricKeyImpl(self.name, self.keyType, self.description, Arr.union(self.tags, extraTags))) diff --git a/packages/effect/src/internal/metric/state.ts b/packages/effect/src/internal/metric/state.ts index 1d01b5996c..aff36216c5 100644 --- a/packages/effect/src/internal/metric/state.ts +++ b/packages/effect/src/internal/metric/state.ts @@ -1,4 +1,4 @@ -import * as Array from "../../Array.js" +import * as Arr from "../../Array.js" import * as Equal from "../../Equal.js" import { pipe } from "../../Function.js" import * as Hash from "../../Hash.js" @@ -80,7 +80,7 @@ class CounterState implements MetricState.MetricSta } } -const arrayEquals = Array.getEquivalence(Equal.equals) +const arrayEquals = Arr.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(Array.fromIterable(this.occurrences.entries()))), + Hash.combine(Hash.array(Arr.fromIterable(this.occurrences.entries()))), Hash.cached(this) ) } [Equal.symbol](that: unknown): boolean { return isFrequencyState(that) && arrayEquals( - Array.fromIterable(this.occurrences.entries()), - Array.fromIterable(that.occurrences.entries()) + Arr.fromIterable(this.occurrences.entries()), + Arr.fromIterable(that.occurrences.entries()) ) } pipe() { diff --git a/packages/effect/src/internal/queue.ts b/packages/effect/src/internal/queue.ts index d99925bc17..1a2c12a609 100644 --- a/packages/effect/src/internal/queue.ts +++ b/packages/effect/src/internal/queue.ts @@ -1,4 +1,4 @@ -import * as Array from "../Array.js" +import * as Arr from "../Array.js" import * as Chunk from "../Chunk.js" import type * as Deferred from "../Deferred.js" import type * as Effect from "../Effect.js" @@ -208,11 +208,11 @@ class QueueImpl implements Queue.Queue { if (MutableRef.get(this.shutdownFlag)) { return core.interrupt } - const values = Array.fromIterable(iterable) + const values = Arr.fromIterable(iterable) const pTakers = this.queue.length() === 0 - ? Array.fromIterable(unsafePollN(this.takers, values.length)) - : Array.empty - const [forTakers, remaining] = pipe(values, Array.splitAt(pTakers.length)) + ? Arr.fromIterable(unsafePollN(this.takers, values.length)) + : Arr.empty + const [forTakers, remaining] = pipe(values, Arr.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.fromIterable(iterable) + const stuff = Arr.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 6014978c15..d40873f36d 100644 --- a/packages/effect/src/internal/redBlackTree/iterator.ts +++ b/packages/effect/src/internal/redBlackTree/iterator.ts @@ -1,4 +1,4 @@ -import * as Array from "../../Array.js" +import * as Arr from "../../Array.js" import * as Option from "../../Option.js" import type * as RBT from "../../RedBlackTree.js" import type { RedBlackTreeImpl } from "../redBlackTree.js" @@ -83,7 +83,7 @@ export class RedBlackTreeIterator implements Iterator<[K, V]> { * Returns the key */ get entry(): Option.Option<[K, V]> { - return Option.map(Array.last(this.stack), (node) => [node.key, node.value]) + return Option.map(Arr.last(this.stack), (node) => [node.key, node.value]) } /** diff --git a/packages/effect/src/internal/secret.ts b/packages/effect/src/internal/secret.ts index ab0868afbd..6abcf43909 100644 --- a/packages/effect/src/internal/secret.ts +++ b/packages/effect/src/internal/secret.ts @@ -1,4 +1,4 @@ -import * as Array from "../Array.js" +import * as Arr from "../Array.js" import * as Equal from "../Equal.js" import { pipe } from "../Function.js" import * as Hash from "../Hash.js" @@ -56,7 +56,7 @@ export const make = (bytes: Array): Secret.Secret => { /** @internal */ export const fromIterable = (iterable: Iterable): Secret.Secret => - make(Array.fromIterable(iterable).map((char) => char.charCodeAt(0))) + make(Arr.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 0b6b583134..75995fbe6b 100644 --- a/packages/effect/src/internal/sink.ts +++ b/packages/effect/src/internal/sink.ts @@ -1,4 +1,4 @@ -import * as Array from "../Array.js" +import * as Arr from "../Array.js" import * as Cause from "../Cause.js" import type * as Channel from "../Channel.js" import * as Chunk from "../Chunk.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), Array.span(predicate)) + const [collected, leftovers] = pipe(Chunk.toReadonlyArray(input), Arr.span(predicate)) if (leftovers.length === 0) { return collectAllWhileReader( predicate, diff --git a/packages/effect/src/internal/stm/tPriorityQueue.ts b/packages/effect/src/internal/stm/tPriorityQueue.ts index 98c1ecc17f..dbc7801390 100644 --- a/packages/effect/src/internal/stm/tPriorityQueue.ts +++ b/packages/effect/src/internal/stm/tPriorityQueue.ts @@ -1,4 +1,4 @@ -import * as Array from "../../Array.js" +import * as Arr from "../../Array.js" import * as Chunk from "../../Chunk.js" import { dual, pipe } from "../../Function.js" import * as Option from "../../Option.js" @@ -42,7 +42,7 @@ export const fromIterable = (order: Order.Order) => (iterable: Iterable): STM.STM> => pipe( tRef.make( - Array.fromIterable(iterable).reduce( + Arr.fromIterable(iterable).reduce( (map, value) => pipe( map, @@ -52,8 +52,8 @@ export const fromIterable = map, SortedMap.get(value), Option.match({ - onNone: () => Array.of(value), - onSome: Array.prepend(value) + onNone: () => Arr.of(value), + onSome: Arr.prepend(value) }) ) ) @@ -86,8 +86,8 @@ export const offer = dual< map, value, Option.match(SortedMap.get(map, value), { - onNone: () => Array.of(value), - onSome: Array.prepend(value) + onNone: () => Arr.of(value), + onSome: Arr.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.fromIterable(values).reduce( + Arr.fromIterable(values).reduce( (map, value) => SortedMap.set( map, value, Option.match(SortedMap.get(map, value), { - onNone: () => Array.of(value), - onSome: Array.prepend(value) + onNone: () => Arr.of(value), + onSome: Arr.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 = Array.filter(value, predicate) + const filtered: ReadonlyArray = Arr.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, Array.splitAt(n - index)) + const [left, right] = pipe(value, Arr.splitAt(n - index)) for (const value of left) { builder.push(value) } diff --git a/packages/experimental/src/Machine.ts b/packages/experimental/src/Machine.ts index 39c190f6d2..ed70297921 100644 --- a/packages/experimental/src/Machine.ts +++ b/packages/experimental/src/Machine.ts @@ -4,7 +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 Arr from "effect/Array" import * as Cause from "effect/Cause" import * as Context from "effect/Context" import * as Deferred from "effect/Deferred" @@ -703,7 +703,7 @@ export const boot = < )), decodeRequest: Schema.decodeUnknown( Schema.Union( - ...Array.filter( + ...Arr.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 09a8eebc4b..0ca9eed4a3 100644 --- a/packages/experimental/src/Persistence/Lmdb.ts +++ b/packages/experimental/src/Persistence/Lmdb.ts @@ -1,7 +1,7 @@ /** * @since 1.0.0 */ -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Effect from "effect/Effect" import { identity } from "effect/Function" import * as Layer from "effect/Layer" @@ -31,7 +31,7 @@ export const make = (options: Lmdb.RootDatabaseOptionsWithPath) => (store) => Effect.promise(() => store.close()) )) const valueToOption = (key: string, _: any) => { - if (!Array.isArray(_)) return Option.none() + if (!Arr.isArray(_)) return Option.none() const [value, expires] = _ as [unknown, number | null] if (expires !== null && expires <= clock.unsafeCurrentTimeMillis()) { store.remove(key) @@ -51,7 +51,7 @@ export const make = (options: Lmdb.RootDatabaseOptionsWithPath) => try: () => store.getMany(keys), catch: (error) => Persistence.PersistenceBackingError.make("getMany", error) }), - Array.map((value, i) => valueToOption(keys[i], value)) + Arr.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 bb60741a18..00cd82f320 100644 --- a/packages/experimental/src/RequestResolver.ts +++ b/packages/experimental/src/RequestResolver.ts @@ -2,7 +2,7 @@ * @since 1.0.0 */ import type * as Serializable from "@effect/schema/Serializable" -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Deferred from "effect/Deferred" import type * as Duration from "effect/Duration" import * as Effect from "effect/Effect" @@ -59,8 +59,8 @@ export const dataLoader = dual< Queue.shutdown ) ) - const batch = yield* _(Ref.make(Array.empty>())) - const takeOne = Effect.flatMap(Queue.take(queue), (item) => Ref.updateAndGet(batch, Array.append(item))) + const batch = yield* _(Ref.make(Arr.empty>())) + const takeOne = Effect.flatMap(Queue.take(queue), (item) => Ref.updateAndGet(batch, Arr.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, Array.empty())) + Effect.zipRight(Ref.getAndSet(batch, Arr.empty())) ) yield* _( @@ -163,7 +163,7 @@ export const persisted: { const partition = (requests: ReadonlyArray) => storage.getMany(requests as any).pipe( Effect.map( - Array.partitionMap((_, i) => + Arr.partitionMap((_, i) => Option.match(_, { onNone: () => Either.left(requests[i]), onSome: (_) => Either.right([requests[i], _] as const) diff --git a/packages/opentelemetry/src/internal/metrics.ts b/packages/opentelemetry/src/internal/metrics.ts index d7b5d891b0..2f883cf389 100644 --- a/packages/opentelemetry/src/internal/metrics.ts +++ b/packages/opentelemetry/src/internal/metrics.ts @@ -12,7 +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 Arr from "effect/Array" import * as Effect from "effect/Effect" import type { LazyArg } from "effect/Function" import * as Layer from "effect/Layer" @@ -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 = Array.reduce(metricKey.tags, {}, (acc: Record, label) => { + const attributes = Arr.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.allocate(size - 1) as Array, - counts: Array.allocate(size) as Array + boundaries: Arr.allocate(size - 1) as Array, + counts: Arr.allocate(size) as Array } let i = 0 let prev = 0 diff --git a/packages/platform/src/Http/Headers.ts b/packages/platform/src/Http/Headers.ts index 6a05d267c2..f243c962c6 100644 --- a/packages/platform/src/Http/Headers.ts +++ b/packages/platform/src/Http/Headers.ts @@ -2,7 +2,7 @@ * @since 1.0.0 */ import * as Schema from "@effect/schema/Schema" -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import { dual, identity } from "effect/Function" import type * as Option from "effect/Option" import * as Predicate from "effect/Predicate" @@ -79,8 +79,8 @@ export const fromInput: (input?: Input) => Headers = (input) => { if (input === undefined) { return empty } else if (Symbol.iterator in input) { - return Record.fromEntries(Array.map( - Array.fromIterable(input), + return Record.fromEntries(Arr.map( + Arr.fromIterable(input), ([k, v]) => [k.toLowerCase(), v] as const )) as Headers } @@ -88,7 +88,7 @@ export const fromInput: (input?: Input) => Headers = (input) => { Object.entries(input).map(([k, v]) => [ k.toLowerCase(), - Array.isArray(v) ? v.join(", ") : v + Arr.isArray(v) ? v.join(", ") : v ] as const ) ) as Headers diff --git a/packages/platform/src/Http/UrlParams.ts b/packages/platform/src/Http/UrlParams.ts index 8edb5afe52..2c04f46de9 100644 --- a/packages/platform/src/Http/UrlParams.ts +++ b/packages/platform/src/Http/UrlParams.ts @@ -4,7 +4,7 @@ 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 Arr from "effect/Array" import * as Effect from "effect/Effect" import { dual } from "effect/Function" import * as Option from "effect/Option" @@ -27,9 +27,9 @@ export type Input = Readonly> | Iterable { if (Symbol.iterator in input) { - return Array.fromIterable(input) + return Arr.fromIterable(input) } - return Array.fromIterable(Object.entries(input)) + return Arr.fromIterable(Object.entries(input)) } /** @@ -59,7 +59,7 @@ export const getAll: { (key: string) => (self: UrlParams) => ReadonlyArray, (self: UrlParams, key: string) => ReadonlyArray >(2, (self, key) => - Array.reduce(self, [] as Array, (acc, [k, value]) => { + Arr.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( - Array.findFirst( + Arr.findFirst( self, ([k]) => k === key ), @@ -97,7 +97,7 @@ export const getLast: { (self: UrlParams, key: string) => Option.Option >(2, (self, key) => Option.map( - Array.findLast( + Arr.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) => - Array.append( - Array.filter(self, ([k]) => k !== key), + Arr.append( + Arr.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 Array.appendAll( - Array.filter(self, ([k]) => keys.includes(k)), + return Arr.appendAll( + Arr.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) => - Array.append( + Arr.append( self, [key, value] )) @@ -166,7 +166,7 @@ export const appendAll: { (input: Input) => (self: UrlParams) => UrlParams, (self: UrlParams, input: Input) => UrlParams >(2, (self, input) => - Array.appendAll( + Arr.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) => Array.filter(self, ([k]) => k !== key)) +>(2, (self, key) => Arr.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()) - Array.forEach(params, ([key, value]) => { + Arr.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 3b03b34aab..6a71afbb76 100644 --- a/packages/platform/src/PlatformConfigProvider.ts +++ b/packages/platform/src/PlatformConfigProvider.ts @@ -1,7 +1,7 @@ /** * @since 1.0.0 */ -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Cause from "effect/Cause" import type * as Config from "effect/Config" import * as ConfigError from "effect/ConfigError" @@ -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()), Array.of) + Either.map(primitive.parse(value.trim()), Arr.of) const readConfig = (filePath: string, primitive: Config.Config.Primitive) => Effect.flatMap( diff --git a/packages/platform/src/internal/http/multiplex.ts b/packages/platform/src/internal/http/multiplex.ts index da06a565e7..c0d74d3c0e 100644 --- a/packages/platform/src/internal/http/multiplex.ts +++ b/packages/platform/src/internal/http/multiplex.ts @@ -1,4 +1,4 @@ -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Effect from "effect/Effect" import * as Effectable from "effect/Effectable" import { dual } from "effect/Function" @@ -72,7 +72,7 @@ export const make = ( apps: Iterable< readonly [predicate: (request: ServerRequest.ServerRequest) => Effect.Effect, app: App.Default] > -): Multiplex.Multiplex => new MultiplexImpl(Array.fromIterable(apps)) +): Multiplex.Multiplex => new MultiplexImpl(Arr.fromIterable(apps)) /** @internal */ export const add = dual< diff --git a/packages/platform/src/internal/worker.ts b/packages/platform/src/internal/worker.ts index 75a77d2388..d23f450f51 100644 --- a/packages/platform/src/internal/worker.ts +++ b/packages/platform/src/internal/worker.ts @@ -1,6 +1,6 @@ import * as Schema from "@effect/schema/Schema" import * as Serializable from "@effect/schema/Serializable" -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Cause from "effect/Cause" import * as Channel from "effect/Channel" import * as Chunk from "effect/Chunk" @@ -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(Array.unsafeGet(0))), + ([, queue]) => Effect.flatMap(Queue.take(queue), Exit.map(Arr.unsafeGet(0))), executeRelease ) diff --git a/packages/printer-ansi/src/internal/ansi.ts b/packages/printer-ansi/src/internal/ansi.ts index 11008de072..21c73f49d4 100644 --- a/packages/printer-ansi/src/internal/ansi.ts +++ b/packages/printer-ansi/src/internal/ansi.ts @@ -1,6 +1,6 @@ import * as Monoid from "@effect/typeclass/Monoid" import * as Semigroup from "@effect/typeclass/Semigroup" -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import { dual } from "effect/Function" import * as Option from "effect/Option" import type * as Ansi from "../Ansi.js" @@ -222,16 +222,16 @@ export const bgWhiteBright: Ansi.Ansi = bgColorBright(InternalColor.white) // ----------------------------------------------------------------------------- /** @internal */ -export const beep: Ansi.Ansi = make({ commands: Array.of(BEL) }) +export const beep: Ansi.Ansi = make({ commands: Arr.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: Array.of(command) }) + return make({ commands: Arr.of(command) }) } const command = `${ESC}${row + 1}${SEP}${Math.max(column + 1, 0)}H` - return make({ commands: Array.of(command) }) + return make({ commands: Arr.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: Array.of(command) }) + return make({ commands: Arr.of(command) }) } /** @internal */ export const cursorUp = (lines: number = 1): Ansi.Ansi => { const command = `${ESC}${lines}A` - return make({ commands: Array.of(command) }) + return make({ commands: Arr.of(command) }) } /** @internal */ export const cursorDown = (lines: number = 1): Ansi.Ansi => { const command = `${ESC}${lines}B` - return make({ commands: Array.of(command) }) + return make({ commands: Arr.of(command) }) } /** @internal */ export const cursorForward = (columns: number = 1): Ansi.Ansi => { const command = `${ESC}${columns}C` - return make({ commands: Array.of(command) }) + return make({ commands: Arr.of(command) }) } /** @internal */ export const cursorBackward = (columns: number = 1): Ansi.Ansi => { const command = `${ESC}${columns}D` - return make({ commands: Array.of(command) }) + return make({ commands: Arr.of(command) }) } /** @internal */ -export const cursorLeft: Ansi.Ansi = make({ commands: Array.of(`${ESC}G`) }) +export const cursorLeft: Ansi.Ansi = make({ commands: Arr.of(`${ESC}G`) }) /** @internal */ -export const cursorSavePosition: Ansi.Ansi = make({ commands: Array.of(`${ESC}s`) }) +export const cursorSavePosition: Ansi.Ansi = make({ commands: Arr.of(`${ESC}s`) }) /** @internal */ -export const cursorRestorePosition: Ansi.Ansi = make({ commands: Array.of(`${ESC}u`) }) +export const cursorRestorePosition: Ansi.Ansi = make({ commands: Arr.of(`${ESC}u`) }) /** @internal */ -export const cursorNextLine = (rows: number = 1): Ansi.Ansi => make({ commands: Array.of(`${ESC}${rows}E`) }) +export const cursorNextLine = (rows: number = 1): Ansi.Ansi => make({ commands: Arr.of(`${ESC}${rows}E`) }) /** @internal */ -export const cursorPrevLine = (rows: number = 1): Ansi.Ansi => make({ commands: Array.of(`${ESC}${rows}F`) }) +export const cursorPrevLine = (rows: number = 1): Ansi.Ansi => make({ commands: Arr.of(`${ESC}${rows}F`) }) /** @internal */ -export const cursorHide: Ansi.Ansi = make({ commands: Array.of(`${ESC}?25l`) }) +export const cursorHide: Ansi.Ansi = make({ commands: Arr.of(`${ESC}?25l`) }) /** @internal */ -export const cursorShow: Ansi.Ansi = make({ commands: Array.of(`${ESC}?25h`) }) +export const cursorShow: Ansi.Ansi = make({ commands: Arr.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: Array.of(command) }) + return make({ commands: Arr.of(command) }) } /** @internal */ -export const eraseEndLine: Ansi.Ansi = make({ commands: Array.of(`${ESC}K`) }) +export const eraseEndLine: Ansi.Ansi = make({ commands: Arr.of(`${ESC}K`) }) /** @internal */ -export const eraseStartLine: Ansi.Ansi = make({ commands: Array.of(`${ESC}1K`) }) +export const eraseStartLine: Ansi.Ansi = make({ commands: Arr.of(`${ESC}1K`) }) /** @internal */ -export const eraseLine: Ansi.Ansi = make({ commands: Array.of(`${ESC}2K`) }) +export const eraseLine: Ansi.Ansi = make({ commands: Arr.of(`${ESC}2K`) }) /** @internal */ -export const eraseDown: Ansi.Ansi = make({ commands: Array.of(`${ESC}J`) }) +export const eraseDown: Ansi.Ansi = make({ commands: Arr.of(`${ESC}J`) }) /** @internal */ -export const eraseUp: Ansi.Ansi = make({ commands: Array.of(`${ESC}1J`) }) +export const eraseUp: Ansi.Ansi = make({ commands: Arr.of(`${ESC}1J`) }) /** @internal */ -export const eraseScreen: Ansi.Ansi = make({ commands: Array.of(`${ESC}2J`) }) +export const eraseScreen: Ansi.Ansi = make({ commands: Arr.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( - Array.getSomes([ + Arr.getSomes([ Option.some(SGR.reset), self.foreground, self.background, @@ -362,6 +362,6 @@ const stringifyInternal = (self: AnsiImpl): string => { self.underlined ]) ) - const commandSequence = Array.join(self.commands, "") + const commandSequence = Arr.join(self.commands, "") return `${displaySequence}${commandSequence}` } diff --git a/packages/printer/src/internal/doc.ts b/packages/printer/src/internal/doc.ts index 210b3c7a85..a924365804 100644 --- a/packages/printer/src/internal/doc.ts +++ b/packages/printer/src/internal/doc.ts @@ -2,7 +2,7 @@ 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 Arr from "effect/Array" import * as Effect from "effect/Effect" import * as Equal from "effect/Equal" import { dual, pipe } from "effect/Function" @@ -342,9 +342,9 @@ export const concatWith = dual< f: (left: Doc.Doc, right: Doc.Doc) => Doc.Doc ) => Doc.Doc >(2, (docs, f) => - Array.matchRight(Array.fromIterable(docs), { + Arr.matchRight(Arr.fromIterable(docs), { onEmpty: () => empty, - onNonEmpty: (init, last) => Array.reduceRight(init, last, (curr, acc) => f(acc, curr)) + onNonEmpty: (init, last) => Arr.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 = Array.fromIterable(docs) - if (Array.isEmptyReadonlyArray(documents)) { + const documents = Arr.fromIterable(docs) + if (Arr.isEmptyReadonlyArray(documents)) { return cat(left, right) } if (documents.length === 1) { return cat(left, cat(documents[0]!, right)) } const xs = pipe( - Array.makeBy(documents.length - 1, () => sep), - Array.prepend(left), - Array.zipWith(documents, (left: Doc.Doc, right) => cat(left, right)) + Arr.makeBy(documents.length - 1, () => sep), + Arr.prepend(left), + Arr.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) => - Array.reduceRight( - Array.fromIterable(f(self.annotation)), + Arr.reduceRight( + Arr.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 = Array.fromIterable(docs) - return Array.map(documents, (x, i) => documents.length - 1 === i ? x : cat(x, punctuator)) + const documents = Arr.fromIterable(docs) + return Arr.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 5f7f9bb295..a45c7ff6f1 100644 --- a/packages/printer/src/internal/docTree.ts +++ b/packages/printer/src/internal/docTree.ts @@ -2,7 +2,7 @@ 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 Arr from "effect/Array" import * as Effect from "effect/Effect" import * as Equal from "effect/Equal" import { dual, pipe } from "effect/Function" @@ -202,8 +202,8 @@ const alterAnnotationsSafe = ( return Effect.succeed(line(self.indentation)) } case "AnnotationTree": { - return Array.reduce( - Array.fromIterable(f(self.annotation)), + return Arr.reduce( + Arr.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 (Array.isEmptyReadonlyArray(self.trees)) { + if (Arr.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 Array.reduce(tail, head, M.combine) + return Arr.reduce(tail, head, M.combine) } ) } @@ -321,12 +321,12 @@ const renderSimplyDecoratedSafe = ( ) } case "ConcatTree": { - if (Array.isEmptyReadonlyArray(self.trees)) { + if (Arr.isEmptyReadonlyArray(self.trees)) { return Effect.succeed(M.empty) } const head = self.trees[0] const tail = self.trees.slice(1) - return Array.reduce( + return Arr.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(Array.make(self, that)), - combineMany: (self, trees) => concat(Array.fromIterable([self, ...trees])) + combine: (self, that) => concat(Arr.make(self, that)), + combineMany: (self, trees) => concat(Arr.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(Array.make(self, that)), - combineMany: (self, trees) => concat(Array.fromIterable([self, ...trees])), - combineAll: (trees) => concat(Array.fromIterable(trees)) + combine: (self, that) => concat(Arr.make(self, that)), + combineMany: (self, trees) => concat(Arr.fromIterable([self, ...trees])), + combineAll: (trees) => concat(Arr.fromIterable(trees)) } } diff --git a/packages/rpc/src/Resolver.ts b/packages/rpc/src/Resolver.ts index 3eedd44db5..3185eac5e2 100644 --- a/packages/rpc/src/Resolver.ts +++ b/packages/rpc/src/Resolver.ts @@ -5,7 +5,7 @@ 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 Arr from "effect/Array" import * as Cause from "effect/Cause" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" @@ -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] = Array.partition( + const [effectRequests, streamRequests] = Arr.partition( requests, (_): _ is Rpc.Request => StreamRequestTypeId in _.request ) @@ -47,7 +47,7 @@ export const make = ( Stream.runForEach( Stream.filter( handler(payload), - (_): _ is Router.Router.Response => Array.isArray(_) && _.length === 2 + (_): _ is Router.Router.Response => Arr.isArray(_) && _.length === 2 ), ([index, response]): Effect.Effect => { const request = effectRequests[index] diff --git a/packages/schema/src/AST.ts b/packages/schema/src/AST.ts index 6493ca8a86..6565a2f949 100644 --- a/packages/schema/src/AST.ts +++ b/packages/schema/src/AST.ts @@ -2,7 +2,7 @@ * @since 1.0.0 */ -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import type { Effect } from "effect/Effect" import { dual, identity } from "effect/Function" import { globalValue } from "effect/GlobalValue" @@ -55,7 +55,7 @@ export type AST = * @category annotations * @since 1.0.0 */ -export type BrandAnnotation = Array.NonEmptyReadonlyArray +export type BrandAnnotation = Arr.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 = Array.NonEmptyReadonlyArray +export type ExamplesAnnotation = Arr.NonEmptyReadonlyArray /** * @category annotations @@ -1003,7 +1003,7 @@ export class TemplateLiteral implements Annotated { spans: ReadonlyArray, annotations: Annotations = {} ): TemplateLiteral | Literal => - Array.isNonEmptyReadonlyArray(spans) ? + Arr.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: Array.NonEmptyReadonlyArray, + readonly spans: Arr.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 Array.matchLeft(ast.rest, { + return Arr.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 = Array.sort( +const sortCandidates = Arr.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 => - Array.flatMap(candidates, (ast) => isUnion(ast) ? flatten(ast.types) : [ast]) + Arr.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 = Array.findFirst(ast.propertySignatures, (ps) => ps.name === name) + const ops = Arr.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) => Array.intersection(out, getPropertyKeys(ast)), + (out: Array, ast) => Arr.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), - Array.isNonEmptyReadonlyArray(ts) ? + Arr.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)), - Array.match(ast.rest, { + Arr.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: Array.NonEmptyReadonlyArray, + as: Arr.NonEmptyReadonlyArray, f: (a: A) => A -): Array.NonEmptyReadonlyArray +): Arr.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.allocate(as.length) as Array + const out = Arr.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 = Array.sort( +const sortPropertySignatures = Arr.sort( Order.mapInput(Number.Order, (ps: PropertySignature) => getCardinality(ps.type)) ) -const sortIndexSignatures = Array.sort( +const sortIndexSignatures = Arr.sort( Order.mapInput(Number.Order, (is: IndexSignature) => { switch (getParameterBase(is.parameter)._tag) { case "StringKeyword": @@ -2471,11 +2471,11 @@ export const getParameterBase = ( } } -const equalsTemplateLiteralSpan = Array.getEquivalence((self, that) => +const equalsTemplateLiteralSpan = Arr.getEquivalence((self, that) => self.type._tag === that.type._tag && self.literal === that.literal ) -const equalsEnums = Array.getEquivalence((self, that) => +const equalsEnums = Arr.getEquivalence((self, that) => that[0] === self[0] && that[1] === self[1] ) @@ -2512,7 +2512,7 @@ const equals = (self: AST, that: AST) => { } } -const intersection = Array.intersectionWith(equals) +const intersection = Arr.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 704415c722..0fa165fa00 100644 --- a/packages/schema/src/Arbitrary.ts +++ b/packages/schema/src/Arbitrary.ts @@ -2,7 +2,7 @@ * @since 1.0.0 */ -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Option from "effect/Option" import * as Predicate from "effect/Predicate" import * as AST from "./AST.js" @@ -211,7 +211,7 @@ const go = (ast: AST.AST, options: Options): LazyArbitrary => { // --------------------------------------------- // handle rest element // --------------------------------------------- - if (Array.isNonEmptyReadonlyArray(rest)) { + if (Arr.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 f56e4ba588..a7da7ffb74 100644 --- a/packages/schema/src/ArrayFormatter.ts +++ b/packages/schema/src/ArrayFormatter.ts @@ -2,7 +2,7 @@ * @since 1.0.0 */ -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Effect from "effect/Effect" import type * as ParseResult from "./ParseResult.js" import * as TreeFormatter from "./TreeFormatter.js" @@ -76,19 +76,19 @@ const go = ( return go(e, path) } }), - Array.flatten + Arr.flatten )) case "TupleType": return getArray(e, path, () => Effect.map( Effect.forEach(e.errors, (index) => go(index.error, [...path, index.index])), - Array.flatten + Arr.flatten )) case "TypeLiteral": return getArray(e, path, () => Effect.map( Effect.forEach(e.errors, (key) => go(key.error, [...path, key.key])), - Array.flatten + Arr.flatten )) case "Transformation": case "Refinement": diff --git a/packages/schema/src/Equivalence.ts b/packages/schema/src/Equivalence.ts index a60acb6b68..fa26cb1bae 100644 --- a/packages/schema/src/Equivalence.ts +++ b/packages/schema/src/Equivalence.ts @@ -2,7 +2,7 @@ * @since 1.0.0 */ -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Equal from "effect/Equal" import * as Equivalence from "effect/Equivalence" import * as Option from "effect/Option" @@ -104,7 +104,7 @@ const go = (ast: AST.AST): Equivalence.Equivalence => { // --------------------------------------------- // handle rest element // --------------------------------------------- - if (Array.isNonEmptyReadonlyArray(rest)) { + if (Arr.isNonEmptyReadonlyArray(rest)) { const [head, ...tail] = rest for (; i < len - tail.length; i++) { if (!head(a[i], b[i])) { diff --git a/packages/schema/src/ParseResult.ts b/packages/schema/src/ParseResult.ts index 8f0c4e0d2c..f4357902a1 100644 --- a/packages/schema/src/ParseResult.ts +++ b/packages/schema/src/ParseResult.ts @@ -2,7 +2,7 @@ * @since 1.0.0 */ -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import { TaggedError } from "effect/Data" import * as Effect from "effect/Effect" import * as Either from "effect/Either" @@ -81,7 +81,7 @@ export class TupleType { constructor( readonly ast: AST.TupleType, readonly actual: unknown, - readonly errors: Array.NonEmptyReadonlyArray, + readonly errors: Arr.NonEmptyReadonlyArray, readonly output: ReadonlyArray = [] ) {} } @@ -114,7 +114,7 @@ export class TypeLiteral { constructor( readonly ast: AST.TypeLiteral, readonly actual: unknown, - readonly errors: Array.NonEmptyReadonlyArray, + readonly errors: Arr.NonEmptyReadonlyArray, readonly output: { readonly [x: string]: unknown } = {} ) {} } @@ -254,7 +254,7 @@ export class Union { constructor( readonly ast: AST.Union, readonly actual: unknown, - readonly errors: Array.NonEmptyReadonlyArray + readonly errors: Arr.NonEmptyReadonlyArray ) {} } @@ -925,7 +925,7 @@ const go = (ast: AST.AST, isDecoding: boolean): Parser => { const concurrency = getConcurrency(ast) const batching = getBatching(ast) return (input: unknown, options) => { - if (!Array.isArray(input)) { + if (!Arr.isArray(input)) { return Either.left(new Type(ast, input)) } const allErrors = options?.errors === "all" @@ -1023,7 +1023,7 @@ const go = (ast: AST.AST, isDecoding: boolean): Parser => { // --------------------------------------------- // handle rest element // --------------------------------------------- - if (Array.isNonEmptyReadonlyArray(rest)) { + if (Arr.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) => - Array.isNonEmptyArray(es) ? + Arr.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.copy(es), - output: Array.copy(output) + es: Arr.copy(es), + output: Arr.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) => - Array.isNonEmptyArray(es) ? + Arr.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.copy(es), + es: Arr.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"]) => - Array.isNonEmptyArray(es) ? + Arr.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.copy(es) } + const state: State = { es: Arr.copy(es) } return Effect.flatMap( Effect.forEach(cqueue, (f) => f(state), { concurrency, batching, discard: true }), () => { @@ -1630,8 +1630,8 @@ const handleForbidden = ( } function sortByIndex( - es: Array.NonEmptyArray<[number, T]> -): Array.NonEmptyArray + es: Arr.NonEmptyArray<[number, T]> +): Arr.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 a1a12a3fd4..90e92ced61 100644 --- a/packages/schema/src/Pretty.ts +++ b/packages/schema/src/Pretty.ts @@ -1,7 +1,7 @@ /** * @since 1.0.0 */ -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Option from "effect/Option" import * as AST from "./AST.js" import * as errors_ from "./internal/errors.js" @@ -116,7 +116,7 @@ export const match: AST.Match> = { // --------------------------------------------- // handle rest element // --------------------------------------------- - if (Array.isNonEmptyReadonlyArray(rest)) { + if (Arr.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 Array.isNonEmptyReadonlyArray(output) ? "{ " + output.join(", ") + " }" : "{}" + return Arr.isNonEmptyReadonlyArray(output) ? "{ " + output.join(", ") + " }" : "{}" } }, "Union": (ast, go) => { diff --git a/packages/sql/src/Migrator.ts b/packages/sql/src/Migrator.ts index dc30401eed..e7db594a27 100644 --- a/packages/sql/src/Migrator.ts +++ b/packages/sql/src/Migrator.ts @@ -2,7 +2,7 @@ * @since 1.0.0 */ import { FileSystem } from "@effect/platform/FileSystem" -import * as Array from "effect/Array" +import * as Arr from "effect/Array" import * as Data from "effect/Data" import * as Effect from "effect/Effect" import { pipe } from "effect/Function" @@ -278,15 +278,15 @@ export const fromGlob = ( ): Loader => pipe( Object.keys(migrations), - Array.filterMap((_) => Option.fromNullable(_.match(/^(?:.*\/)?(\d+)_([^.]+)\.(js|ts)$/))), - Array.map( + Arr.filterMap((_) => Option.fromNullable(_.match(/^(?:.*\/)?(\d+)_([^.]+)\.(js|ts)$/))), + Arr.map( ([key, id, name]): ResolvedMigration => [ Number(id), name, Effect.promise(() => migrations[key]()) ] ), - Array.sort(migrationOrder), + Arr.sort(migrationOrder), Effect.succeed ) @@ -297,15 +297,15 @@ export const fromGlob = ( export const fromBabelGlob = (migrations: Record): Loader => pipe( Object.keys(migrations), - Array.filterMap((_) => Option.fromNullable(_.match(/^_(\d+)_([^.]+?)(Js|Ts)?$/))), - Array.map( + Arr.filterMap((_) => Option.fromNullable(_.match(/^_(\d+)_([^.]+?)(Js|Ts)?$/))), + Arr.map( ([key, id, name]): ResolvedMigration => [ Number(id), name, Effect.succeed(migrations[key]) ] ), - Array.sort(migrationOrder), + Arr.sort(migrationOrder), Effect.succeed )