Git Product home page Git Product logo

utilities's Introduction

Sapphire Logo

Sapphire Utilities

Common NodeJS packages for Sapphire Repositories and others.

GitHub codecov

Packages

npm npm npm npm npm npm npm npm npm npm npm npm npm npm npm npm npm npm npm npm npm npm

Buy us some doughnuts

Sapphire Community is and always will be open source, even if we don't get donations. That being said, we know there are amazing people who may still want to donate just to show their appreciation. Thank you very much in advance!

We accept donations through Open Collective, Ko-fi, Paypal, Patreon and GitHub Sponsorships. You can use the buttons below to donate through your method of choice.

Donate With Address
Open Collective Click Here
Ko-fi Click Here
Patreon Click Here
PayPal Click Here

Contributors

Please make sure to read the Contributing Guide before making a pull request.

Thank you to all the people who already contributed to Sapphire!

utilities's People

Contributors

allcontributors[bot] avatar c43721 avatar commandtechno avatar dependabot[bot] avatar depfu[bot] avatar didinele avatar enxg avatar evolutionx-10 avatar favna avatar fc5570 avatar github-actions[bot] avatar imranbarbhuiya avatar killbasa avatar kyranet avatar legendhimself avatar lioness100 avatar megatank58 avatar mzato0001 avatar noftaly avatar nytelife26 avatar pyrotechniac avatar realshadownova avatar renovate-bot avatar renovate[bot] avatar sawa-ko avatar soumil-07 avatar undiedgamer avatar vetlix avatar vladfrangu avatar yuansheng1549 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

utilities's Issues

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (github>whitesource/merge-confidence:beta)

request: separate `@sapphire/time-utilities` in several packages

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

Currently, if we want to use just one time utility, we need to install the entire thing, which increases node_modules's size.

Desired solution

@sapphire/time-utilities comes with 4 time utilities that can be broken into several ones:

  • @sapphire/cron
  • @sapphire/duration
  • @sapphire/timer-manager
  • @sapphire/timestamp

The main @sapphire/time-utilities package would install and re-export the 4 packages.

Alternatives considered

N/a

Additional context

No response

request: timezone support in `Cron`

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

Currently, Cron supports only UTC, however, it could be adapted to support various timezones, even local time.

Desired solution

Implement a way to define the timezone offset, this can be a function so we can calculate it in case a timezone's offset changes due to DST.

In the future, we can add support for Temporal.TimeZone.

Alternatives considered

N/a.

Additional context

No response

request: port `Result` code from framework to new package `@sapphire/result`

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

More and more do I see use cases for https://github.com/sapphiredev/framework/blob/main/src/lib/parsers/Result.ts in other places that do not depend on @sapphire/framework so it would be nice if this code was in a new package called@sapphire/result instead.

Desired solution

First of all, the code from the https://github.com/sapphiredev/framework/blob/main/src/lib/parsers/Result.ts file to be ported to @sapphire/result. Then, once an update has been released, a follow up PR to be made in framework to remove the code there and instead re-export it from utilities.

Secondly, as we would like @sapphire/result to work on the web, be small and standalone, and not depend on any external packages, we should include the types Ok and Err types from Lexure directory into our own code with a proper license header copy in 1:1 into utilities.

Alternatives considered

Including the code in @sapphire/utilities

We could copy the code into @sapphire/utilities, but that unnecessarily increases the bundle size of any package that requires only Result such as @sapphire/shapeshift.

Additional context

No response

request: add components for MessagePrompter

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

I would be great if there was a way to use components (buttons/select menus) for MessagePrompter, for example for the confirm (yes/no) prompt, or any custom component prompt (the same way there is a custom reaction prompt)

Desired solution

It could just replace the replace the current confirm entirely, or add the component-confirm and components strategies, for respectively having a yes/no button and having custom components.
If you decide to go with the latter, perhaps confirm should be renamed to reaction-confirm for symmetry.

Alternatives considered

Not using interactions, or making a manual prompter

Additional context

No response

request(ratelimits): data export/inport support

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

I want to export ratelimit data and save them in a database when my application goes offline and have the ability to import it back once the application comes back online.

Desired solution

For rateLimitManager to have an export and import function.

Alternatives considered

I haven't concidered any other alternatives because the sapphire framework has cooldowns already built-in that use this library.

Additional context

No response

request: Paginated embeds with embed-jsx

Is your feature request related to a problem? Please describe.
Creating embeds with embed-jsx is nice, however with the util in discord.js-utilities, it is possible to create paginated embeds, which I would like to do with jsx syntax

Describe the solution you'd like
Using Fragment syntax, it should be possible to create paginated embeds with the tsconfig option jsxFragmentFactory

Describe alternatives you've considered
N/A

Additional context
N/A

bug: [@sapphire/ts-config] Option 'importsNotUsedAsValues' is deprecated and will stop functioning in TypeScript 5.5.

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

When extending @sapphire/ts-config in the tsconfig, the following error shows up

grafik
grafik

the importsNotUsedAsValues option seems deprecated, and should be updated in this package

Steps To Reproduce

Extend @sapphire/ts-config in your tsconfig

Expected behavior

No error should be shown

Screenshots

No response

Additional context

microsoft/TypeScript#51909
Found this (related?) Issue on the topic

request: add `objectEntries` (a strictly typed `Object.entries`) to `@sapphire/utilities`

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

The types built into TypeScript for Object.entries intentionally aren't fully strictly typed, however there are instances where a strictly typed Object.entries can be useful. This is where a custom objectEntries can come in.

Desired solution

Add a function like this and export it:

export function objectEntries<T extends NonNullObject>(obj: T): [keyof T, T[keyof T]][] {
  return Object.entries(obj) as [keyof T, T[keyof T]][];
}

Then implement unit tests for this

Alternatives considered

N.A.

Additional context

Porting this code from my work tbh

request: (PaginatedMessage) 'Go To Page' button to get page input from a user via a text modal

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

Have an option to have a button Go To Page button show a text input modal for input on what page the bot should go to.

  • This would allow more than 25 pages.
  • Gives developers other options when it comes to displaying pages to users.
  • It gives a more clean way of allowing the user to go to a certain page without the developer limiting PaginatedMessage to only 25 pages.

Or removing the string select menu and bypassing addPage / addPages warning / check for the 25 page limit, which is what you can do currently but removes the ability to go to a certain page.

Desired solution

For PaginatedMessage add an option to use / not use the 'Go To Page' button as a default action to be handled by the package itself.

  • PaginatedMessage adds Go To Page / โ” button to the pages
  • PaginatedMessage Once that button is pressed it will show a modal to get a page number input from the user.
  • PaginatedMessage Once that modal is submitted it will be processed and the page will change (if valid etc.)

Alternatives considered

N/A

Additional context

No response

request: port `walk` from `subpath-updater` to a proper function in `utilities` package

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

In #454 we added a script subpath-updater.mjs which has a function walk to deeply walk a directory path and find files matching a file extension. It would be useful if this would be ported to a proper function in the utilities package.

Desired solution

The following is a write-up of the function as it should approximately be. The name of the function is still open to discussion.

Other than that unit tests should be written.

Furthermore, the turbo.json should be updated to require @sapphire/utilities to be built before check-subpath is ran.

import type { PathLike } from 'node:fs';
import { opendir } from 'node:fs/promises';
import { join } from 'node:path';

/**
 *
 * @param path The path in which to find files. This can be a string, buffer or {@link URL}.
 * @param fileNameEndsWith The string pattern with which the file name must end.
 * Ideally this is a file extension, however you can also provide more parts of the end of the file.
 *
 * Note that we do **not** support a full globby pattern using asterisk for wildcards. It has to be an exact match with {@link String.endsWith}
 *
 * @return An {@link AsyncIterableIterator<string>} of all the files. To loop over these use `for await (const file of walk(path, fileNameEndsWith)) {}`
 *
 *
 * @example
 * ```typescript
 * // With CommonJS: To find all files ending with `.ts` in the src directory:
 * const path = require('node:path');
 *
 * for await (const file of walk(path.join(__dirname, 'src'), '.ts')) {
 *   console.log(file);
 * }
 * ```
 *
 * @example
 * ```typescript
 * // With ESM: To find all files ending with `.ts` in the src directory:
 * for await (const file of walk(new URL('src', import.meta.url), '.ts')) {
 *   console.log(file);
 * }
 * ```
 */
async function* findFilesRecursively(path: PathLike, fileNameEndsWith: string): AsyncIterableIterator<string> {
	try {
		const dir = await opendir(path);

		for await (const item of dir) {
			if (item.isFile() && (!fileNameEndsWith || item.name.endsWith(fileNameEndsWith))) {
				yield join(dir.path, item.name);
			} else if (item.isDirectory()) {
				yield* findFilesRecursively(join(dir.path, item.name), fileNameEndsWith);
			}
		}
	} catch (error) {
		if ((error as any).code !== 'ENOENT') {
			console.error(error);
		}
	}
}

Alternatives considered

N.A.

Additional context

The name of the function is still open for discussing. Likewise we can also considering extending this to several functions using 1 base function and passing a predicate so those several functions can do startsWith, endsWith, includes and regex. For example taking the code above for findFilesRecursively we could have findFilesRecursivelyStringStartsWith, findFilesRecursivelyStringEndsWith, etc.

request(time-utilities): Add formatting options for duration

Currently, the duration formatter only supports changing the name of the units.
e.g.
DurationFormatter(TIMES).format(11101000) => 3 hours 5 minutes 1 second

For versatility purposes and to increase the use cases of the package, it would be better to support format strings with substitution, similar to how date formatting is done with the built-in Date object.
e.g.
DurationFormatter("%h:%m:%s").format(11101000) => 03:05:01

bug: PaginatedMessage#addAction custom select menu options not available

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

Whenever you try to add a custom select menu to the default PaginatedMessage instance through addAction, the options are not shown, instead it shows the same options as the default select menu.

Steps To Reproduce

Add the code below as function body of a messageCreate event

const embed = new MessageEmbed().setDescription("hello")

const paginationEmbed = new PaginatedMessage()
  .addPageEmbed(embed)
  .addPageEmbed(embed)

paginationEmbed.addAction({
  customId: "select_menu",
  type: Constants.MessageComponentTypes.SELECT_MENU,
  maxValues: 1,
  placeholder: "test",
  options: [
    {
      label: "test",
      description: "test",
      value: "test",
    },
  ],
  run: async (action) => {
    console.log("hi")
  },
})

paginationEmbed.addAction({
  type: Constants.MessageComponentTypes.BUTTON,
  customId: "Ban",
  style: "DANGER",
  emoji: "๐Ÿ”จ",
  run: async () => console.log("hello"),
})

return paginationEmbed.run(message)

Expected behavior

The custom options should be available.

Screenshots

https://cdn.discordapp.com/attachments/737142503043498015/944302201436782623/unknown.png

Additional context

"@sapphire/discord.js-utilities": "^4.8.0",
"discord.js": "^13.6.0",

request: ability to import single functions in `@sapphire/utilities`

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

Right now, if we want to import an utility, we have to import from @sapphire/utilities, which loads all of the utilities, which in turn increases the load time and memory usage.

Desired solution

Be able to import with subpaths, e.g. import { chunk } from '@sapphire/utilities/chunk';

Alternatives considered

N/a.

Additional context

No response

request: add `objectValues` (a strictly typed `Object.values`) to `@sapphire/utilities`

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

The types built into TypeScript for Object.values intentionally aren't fully strictly typed, however there are instances where a strictly typed Object.values can be useful. This is where a custom objectValues can come in.

Desired solution

Add a function like this and export it:

export function objectValues<T extends NonNullObject>(obj: T): T[keyof T][] {
  return Object.values(obj) as T[keyof T][];
}

Then implement unit tests for this

Alternatives considered

N.A.

Additional context

No response

bug: example code in `MessagePrompt` it outdated

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

The examples in the MessagePrompter class are outdated, showing the old style of creating them.

Steps To Reproduce

  1. Go to https://www.sapphirejs.dev/docs/Documentation/api-utilities/classes/sapphire_discord_js_utilities.MessagePrompter
  2. See incorrect examples at the top

Expected behavior

Examples in the documentation represent the actual usage of the class

Screenshots

image

Additional context

  1. Examples in question:
    * @example
    * ```typescript
    * const { MessagePrompter } = require('@sapphire/discord.js-utilities');
    *
    * const handler = new MessagePrompter('Are you sure you want to continue?');
    * const result = await handler.run(channel, author);
    * ```
    *
    * @example
    * ```typescript
    * const { MessagePrompter, MessagePrompterStrategies } = require('@sapphire/discord.js-utilities');
    *
    * const handler = new MessagePrompter('Choose a number between 5 and 10?', MessagePrompterStrategies.Number, {
    * start: 5,
    * end: 10
    * });
    * const result = await handler.run(channel, author);
    * ```
    *
    * @example
    * ```typescript
    * const { MessagePrompter, MessagePrompterStrategies } = require('@sapphire/discord.js-utilities');
    *
    * const handler = new MessagePrompter('Are you happy or sad?', MessagePrompterStrategies.Reaction, {
    * reactions: ['๐Ÿ™‚', '๐Ÿ™']
    * });
    * const result = await handler.run(channel, author);
    * ```
    *
    * @example
    * ```typescript
    * const { MessagePrompter, MessagePrompterStrategies } = require('@sapphire/discord.js-utilities');
    *
    * const handler = new MessagePrompter('Do you love me?', MessagePrompterStrategies.Message);
    * const result = await handler.run(channel, author);
    * ```
  2. Also check all the other examples used across MessagePrompt and its related classes

Depfu Error: No dependency files found

Hello,

We've tried to activate or update your repository on Depfu and couldn't find any supported dependency files. If we were to guess, we would say that this is not actually a project Depfu supports and has probably been activated by error.

Monorepos

Please note that Depfu currently only searches for your dependency files in the root folder. We do support monorepos and non-root files, but don't auto-detect them. If that's the case with this repo, please send us a quick email with the folder you want Depfu to work on and we'll set it up right away!

How to deactivate the project

  • Go to the Settings page of either your own account or the organization you've used
  • Go to "Installed Integrations"
  • Click the "Configure" button on the Depfu integration
  • Remove this repo (sapphire-project/utilities) from the list of accessible repos.

Please note that using the "All Repositories" setting doesn't make a lot of sense with Depfu.

If you think that this is a mistake

Please let us know by sending an email to [email protected].


This is an automated issue by Depfu. You're getting it because someone configured Depfu to automatically update dependencies on this project.

bug: bun build `@sapphire/utilities`

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

Warning bun build due wildcard sideEffects in @sapphire/utilities

Steps To Reproduce

Execute bun build --target node src/index.ts --outdir dist/ in any project using bun build --target node src/index.ts --outdir dist/

Expected behavior

Use explicit sideEffects so the build is optimized and the warning doesn't appear

Screenshots

image

Additional context

No response

bug: `Date` parsing in `deepClone`

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

There is a critical bug in deepClone in @sapphire/utilities (which then also affects mergeDefault) where it is incapable of parsing dates. Instead of duplicating the Date, it assigns the current date.

Steps To Reproduce

const { deepClone } = require('@sapphire/utilities');

const originalObject = { dateTime: new Date('2020-01-01T12:45:00.000Z') };

const clonedObject = deepClone(originalObject);

console.log(obj);
// { dateTime: 2020-01-01T12:45:00.000Z }

console.log(clonedObject);
// { dateTime: 2022-01-26T23:31:03.734Z }

Not the same date!

Expected behavior

The date has to be the same

Screenshots

image

Additional context

I discovered this when we ran into the bug with code at work

request(discord.js-utilities): make it possible to parse MessagePrompter results

Is your feature request related to a problem? Please describe.

Using a MessagePrompter with a MessageStrategy is used in most of the cases to ask for arguments, but in a separate message. But it currently only returns a Message, so if we asked for a channel, we have to parse it ourselves. This makes it redundant as the same logic is already present in the library, to parse command arguments for example.

Describe the solution you'd like

There should be a way to parse MessagePrompter results, either through the Args class (which will require quite a lot of refactor since it currently requires a command, but a MessagePrompter can be run anywhere, including in an event), or with another custom ""type parser"" that can also be implemented in Args to avoid duplicating the same logic twice.

Describe alternatives you've considered

Parse it myself, not optimal. And making our own instance of Args is not possible because as I said, it requires a command ; but MessagePrompter can be used in an event.

request: add `objectKeys` (a strictly typed `Object.keys`) to `@sapphire/utilities`

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

The types built into TypeScript for Object.keys intentionally aren't fully strictly typed, however there are instances where a strictly typed Object.keys can be useful. This is where a custom objectKeys can come in.

Desired solution

Add a function like this and export it:

export function objectKeys<T extends NonNullObject>(obj: T): (keyof T)[] {
  return Object.keys(obj) as (keyof T)[];
}

Then implement unit tests for this

Alternatives considered

N.A.

Additional context

No response

request: Add examples for result

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

Add examples for https://github.com/sapphiredev/utilities/tree/main/packages/result

this is a similar library which gives lots of examples: https://github.com/traverse1984/oxide.ts . doesn't have to be as much as this one has, but just some basic examples covering the main api.

Desired solution

N/A

Alternatives considered

N/A

Additional context

No response

request: allow `RoleSelectMenu`, `ChannelSelectMenu` and `MentionableSelectMenu` in PaginatedMessage select menu's

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

Currently, the PaginatedMessage class only supports the StringSelectMenu as it was written before Role-, Channel-, and MentionableSelectMenuComponent were created. We should however still support these new classes.

Desired solution

Implement Role-, Channel-, and MentionableSelectMenuComponent into PaginatedMessage as options for the select menu component

Alternatives considered

N.A.

Additional context

Docs:

bug(PaginatedMessage): custom select menu is recognized as the default one

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

I created a paginated message with all default actions except for the select menu. I then added a select menu myself through handler.addAction. Although the placeholder text was accurate, the options were not what I had assigned, but instead "Page 1" and "Page 2".

Steps To Reproduce

// version ^4.6.0 (also I understand that any fix for this wouldn't matter for me since I'm not at latest lol)
const handler = new PaginatedMessage({ actions: PaginatedMessage.defaultActions.slice(1) });

handler.addAction({
	customId: '...',
	type: 'SELECT_MENU',
	placeholder: '...',
	options: [/* ... */]
	run(context) {
		// ...
	}
});

Expected behavior

The custom select menu's options should not be overridden.

Screenshots

No response

Additional context

options: await Promise.all(
this.pages.map(async (_, index) => {
return {
...(await this.selectMenuOptions(
index + 1,
this.resolvePaginatedMessageInternationalizationContext(messageOrInteraction, targetUser)
)),
value: index.toString()
};
})
),

^ This is where the PaginatedMessage assigns options without regard to whether it's the default menu.

request: remove deprecated code in `discord.js-utilities`

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

@sapphire/discord.js-utilities has some deprecate code we can remove and release in a breaking version. This would should go along with Sapphire Framework v3.

Desired solution

Remove deprecated code

Alternatives considered

N.A.

Additional context

Deprecated code:

request: `@sapphire/bitfield` lacks support for 2-way enums

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

Depends on #502.

Implementing a mapEnum utility function to map TypeScript's 2-way enums into 1-way ones, as BitField's constructor requires all values to be of the same type, and supporting them in the constructor can lead to much more complicated types, as opposed to a function, which would remove one step.

Desired solution

The idea is to make a function that maps (both value and types) of 2-way enums (aka TypeScript enums) into 1-way ones, for example:

enum State {
	On,
	Off
}

Results on the following:

const State = {
	On: 0,
	Off: 1,
	0: 'On',
	1: 'Off'
};

The idea is to have a function, e.g. mapEnum, that maps the above object (and type) into:

const State = {
	On: 0,
	Off: 1
};

type State = {
	On: 0;
	Off: 1;
};

So it can be passed into the BitField's constructor in the following manner:

const PermissionsBitField = new BitField(mapEnum(PermissionsFlagsBits));

Alternatives considered

Mapping in the constructor by ignoring values which type is string and are a property of flags, but then again types would need to handle this, and I fear they might be incredibly complex.

Additional context

Conversation at #502 (comment)

bug(fetch): Reponse.text() hangs if you've cloned the response

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

Basically just node-fetch/node-fetch#1131. The solutions that are offered are using highWaterMark, which might not be possible with cross-fetch, or "to resolve cloned response in parallel", which might not be applicable with cross-fetch? I don't know much about cross-fetch or the technicalities of fetching in general, so help would be appreciated.

Steps To Reproduce

See node-fetch/node-fetch#1131

Expected behavior

See node-fetch/node-fetch#1131

Screenshots

No response

Additional context

No response

bug: paginated + ephemeral + double command = bot crashes

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

Bot crash (sapphire error so the whole bot crashes) when using a paginated message in ephemeral mode and sending a command twice.

Steps To Reproduce

  1. Create a chatInput command with a paginated message with at least 2 pages (the pages buttons/select are needed)
  2. Make paginated-message's interaction ephemeral (interaction.deferReply({ ephemeral: true }))
  3. use the command twice without "Stopping" the first one. Just use the command twice in a row without doing anything else
  4. Bot crashes

Expected behavior

Either disable usage of paginated + ephemeral, or fix the crash issue

Screenshots

No response

Additional context

The error in the logs is the famous DiscordAPIError: Unknown Message. I guess because the lib is trying to load the previous message to remove the buttons&select (that's what it does when no ephemeral), but since it's an ephemeral interaction, it can't find it.

request: New decorators for subcommands

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

As we know the Command.Options have a lot of options which the subcommand lacks so with the help of decorators we can replicate this, it would be great to see this implemented all the Command.Options in the form of decorators for the subcommands.

Desired solution

As i mentioned with the help of decorators, we already have some like RequiredClientPermissions and RequiredUserPermissions, these decorators function same as the Command.Options#RequiredClientPermissions and Command.Options#RequiredUserPermissions.

Alternatives considered

Alternative solution can be is to add the CommandOptions to the SubCommandMappingOptions.

Additional context

N/A.

bug: Snowflake generating the same ID twice before incrementing

Describe the bug

image
image

Here's how I generated the IDs

   public static readonly snowflake = new Snowflake(new Date('2005-08-07T00:00:00.000Z'));
   /**
     * Generate a buttonID for discord
     * Looks like loop-q:a:n-2132321332112
     * @param command The name of the command to run
     * @param args The arguments to pass the command
     */
    public static generateButtonID(command: string, args?: string[]): string {
        const test = `${command}-${args ? args.join(':') : 'null'}-${this.snowflake.generate()}`;
        console.log(test);
        return test;
    };

To Reproduce

  1. Running the Snowflake#generate() method I guess?

bug: deepClone cannot handle buffers

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

deepClone throws when handling a Buffer.

Steps To Reproduce

deepClone(Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]));

Throws:
TypeError: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined

Stack trace:
https://github.com/sapphiredev/utilities/blob/main/packages/utilities/src/lib/deepClone.ts#L50

Does this not handle any constructors that throw errors if arguments aren't given?

Expected behavior

It returns Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72])

Screenshots

No response

Additional context

No response

request: add iife browser bundle to `@sapphire/stopwatch`

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

Following #270 we can now make @sapphire/stopwatch have an IIFE bundle because we can inject the Node import for CJS and ESM dynamically with esbuild. Previously we relied on import { performance } from 'node:perf_hooks';, but this import isn't needed for browsers where the Performance API is on the global scope.

Desired solution

@sapphire/stopwatch to have an IIFE bundle by modifying the tsup config to dynamically add the node:perf_hooks import.

Alternatives considered

  • Not providing a browser bundle
    • We have no reason not to provide it when it's possible

Additional context

This requires #270 to be merged

request: add `tryParseURL` to utilities + rename `tryParse` to `tryParseJSON` and add deprecation notice to the former of those two.

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

We have a tryParse in /utilities which wraps JSON.parse in a try/catch. Another case where you may want to parse and catch is new URL(...) so lets introduce tryParseURL

Desired solution

  • Implement new file
  • Do something smart for handling the type of URL. We cannot rely on people having DOM in their lib. Probably a triple slash directive.
  • Add new unit tests
  • Rename tryParse to tryParseJSON
  • Add an alias for tryParseJSON with @deprecated a TSDoc comment
  • Add the alias to the aliases map for subpath exports
  • Run check-subpath in packages/utilities to update the package.json
/**
 * Tries parse a string to a {@link URL} object
 * @param value The possible URL to parse
 * @returns an URL object if it was a valid URL or `null` if it was not.
 */
export function tryParseURL(value: string): URL | null {
  try {
    return new URL(value);
  } catch {
    return null;
  }
}

Alternatives considered

Not implementing it? Jk

Additional context

No response

bug: TwitterSnowflake using incorrect epoch

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

The epoch used for the TwitterSnowflake class is incorrect. Snowflakes were created in 2010, many years after tweet id 20 in 2006, which is just a number counting up.

Steps To Reproduce

import { TwitterSnowflake } from "@sapphire/snowflake";
const timestamp = TwitterSnowflake.timestampFrom("1593572310593806338");
console.log(new Date(timestamp));
// expecting: 2022-11-18T11:50:20.644Z
// result: 2018-04-05T06:57:39.987Z

Expected behavior

Using the epoch 1288834974657, found in https://oduwsdl.github.io/tweetedat/ and twitter's archived open source version of their snowflake worker.

import { Snowflake } from "@sapphire/snowflake";
const TwitterSnowflake = new Snowflake(1288834974657n);
console.log(new Date(TwitterSnowflake.timestampFrom("1593572310593806338")));
// expecting: 2022-11-18T11:50:20.644Z
// result: 2022-11-18T11:50:20.644Z

And rejecting snowflakes under a certain number, likely something similar to this, as non-snowflake tweet ids can't be deconstructed

Screenshots

Example

Additional context

This issue prevents the TwitterSnowflake class from being used in some real-world use cases needing timestamps. Since epochs are easily configured, the above code is a fine workaround.

[SFW-82] request: script to automatically generate index.ts re-exports for /utilities

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

It's easy to forget to re-export the utilities on index.ts level. To solve this it would be prudent to add a script and make the file completely auto-generated at pre-build time.

Desired solution

  • A script that automatically injects the code and runs automatically before the code gets build
  • A step in CI that validates if the file is correct

Alternatives considered

suffer.exe

Additional context

No response

SFW-82

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/auto-deprecate.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/auto-updater.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/codeql-analysis.yml
  • actions/checkout v4
  • github/codeql-action v3
  • github/codeql-action v3
  • github/codeql-action v3
.github/workflows/continuous-delivery.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/continuous-integration.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/setup-node v4
  • codecov/codecov-action v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/deprecate-on-merge.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/documentation.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/upload-artifact v4
  • actions/checkout v4
  • actions/setup-node v4
  • actions/download-artifact v4
  • actions/checkout v4
  • nick-fields/retry v3
.github/workflows/labelsync.yml
  • actions/checkout v4
  • actions/checkout v4
  • crazy-max/ghaction-github-labeler v5
.github/workflows/publish.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/release-crosspost.yml
  • kludge-cs/gitcord-release-changelogger v3.0.0@5592170408dc081d7cb6a74ce025911bd1fcb7c3
npm
package.json
  • @actions/core ^1.10.1
  • @commitlint/cli ^19.3.0
  • @commitlint/config-conventional ^19.2.2
  • @discordjs/collection ^1.5.3
  • @favware/cliff-jumper ^4.0.2
  • @favware/npm-deprecate ^1.0.7
  • @favware/rollup-type-bundler ^3.3.0
  • @sapphire/framework ^5.2.1
  • @types/lodash ^4.17.4
  • @types/node ^20.13.0
  • @types/ws ^8.5.10
  • @typescript-eslint/eslint-plugin ^7.11.0
  • @typescript-eslint/parser ^7.11.0
  • @vitest/coverage-v8 ^1.6.0
  • concurrently ^8.2.2
  • cz-conventional-changelog ^3.3.0
  • discord-api-types ^0.37.86
  • discord.js ^14.15.2
  • eslint ^8.57.0
  • eslint-config-prettier ^9.1.0
  • eslint-plugin-prettier ^5.1.3
  • lint-staged ^15.2.5
  • lodash ^4.17.21
  • msw ^2.3.1
  • npm-run-all2 ^6.2.0
  • prettier ^3.3.0
  • rimraf ^5.0.7
  • tslib ^2.6.2
  • tsup ^8.0.2
  • tsx ^4.11.0
  • turbo ^1.13.3
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vite ^5.2.12
  • vitest ^1.6.0
  • ansi-regex ^5.0.1
  • minimist ^1.2.8
  • yarn 4.2.2
packages/async-queue/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/bitfield/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/cron/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/decorators/package.json
  • tslib ^2.6.2
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/discord-utilities/package.json
  • discord-api-types ^0.37.86
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/discord.js-utilities/package.json
  • tslib ^2.6.2
  • @favware/cliff-jumper ^4.0.2
  • @favware/rollup-type-bundler ^3.3.0
  • concurrently ^8.2.2
  • tsup ^8.0.2
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
packages/duration/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/eslint-config/package.json
  • @typescript-eslint/eslint-plugin ^7.11.0
  • @typescript-eslint/parser ^7.11.0
  • eslint ^8.57.0
  • eslint-config-prettier ^9.1.0
  • eslint-plugin-prettier ^5.1.3
  • prettier ^3.3.0
  • typescript ^5.4.5
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • typedoc-json-parser ^10.0.0
  • vitest ^1.6.0
packages/eslint-plugin-result/package.json
  • @typescript-eslint/utils ^7.11.0
  • tsutils ^3.21.0
  • typescript ^5.4.5
  • @favware/cliff-jumper ^4.0.2
  • @typescript-eslint/rule-tester ^7.11.0
  • @typescript-eslint/typescript-estree ^7.11.0
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • typedoc-json-parser ^10.0.0
  • vitest ^1.6.0
packages/event-iterator/package.json
  • tslib ^2.6.2
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/fetch/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/iterator-utilities/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • npm-run-all2 ^6.2.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/lexure/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/node-utilities/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/phisherman/package.json
  • @favware/cliff-jumper ^4.0.2
  • esbuild-plugin-version-injector ^1.2.1
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
packages/prettier-config/package.json
  • prettier ^3.3.0
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/ratelimits/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/result/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/snowflake/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/stopwatch/package.json
  • tslib ^2.6.2
  • @favware/cliff-jumper ^4.0.2
  • @types/jsdom ^21.1.7
  • @vitest/coverage-v8 ^1.6.0
  • jsdom ^24.1.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/time-utilities/package.json
  • @favware/cliff-jumper ^4.0.2
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
packages/timer-manager/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/timestamp/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0
packages/ts-config/package.json
  • tslib ^2.6.2
  • typescript ^5.4.5
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • typedoc-json-parser ^10.0.0
  • vitest ^1.6.0
packages/utilities/package.json
  • @favware/cliff-jumper ^4.0.2
  • @vitest/coverage-v8 ^1.6.0
  • esbuild-plugin-file-path-extensions ^2.1.1
  • npm-run-all2 ^6.2.0
  • tsup ^8.0.2
  • tsx ^4.11.0
  • typedoc ^0.25.13
  • typedoc-json-parser ^10.0.0
  • typescript ^5.4.5
  • vitest ^1.6.0

  • Check this box to trigger a request for Renovate to run again on this repository

request: update for DiscordJS v14

Is there an existing issue or pull request for this?

  • I have searched the existing issues and pull requests

Feature description

DiscordJS v14 has been and we should update @sapphire/discord.js-utilities to match

Desired solution

The utilities should be updated

Alternatives considered

N.A.

Additional context

N.A.

bug: isMessageButtonInteraction function in PaginatedMessages utils

Is there an existing issue for this?

  • I have searched the existing issues

Description of the bug

DiscordAPIError: Invalid Form Body components: Must be 5 or fewer in length.

I add 4 button actions to the PaginatedMessage but it parses them as ContextMenu instead of Button.

Steps To Reproduce

  1. Use PaginatedMessage.setActions method.
  2. Set 4 other button actions with the type: "BUTTON".
  3. Set includeDefaultAction is true.
  4. Run the PaginatedMessage.

Expected behavior

PaginatedMessage will run normally with 5 default actions in the first action row. And your actions in the second row and a SelectMenu at the 3rd row.

Screenshots

No response

Additional context

export function isMessageButtonInteraction(
	interaction: InteractionButtonOptions | MessageSelectMenuOptions
): interaction is InteractionButtonOptions {
	return interaction.type === Constants.MessageComponentTypes.BUTTON;
}

The InteractionButtonOptions and MessageSelectMenuOptions is ExcludeEnum type so they accept all of those types: "BUTTON" | "SELECT_MENU" | 2 | 3
On the other hand, Constants.MessageComponentTypes.BUTTON return 2. So that means if the interaction.type === "BUTTON", the function will return false.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.