@fluxerjs/util 1.4.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,75 +1,74 @@
1
+ import { Snowflake } from '@fluxerjs/types';
2
+
1
3
  /**
2
- * Data structure that allows efficient storage of multiple flags (bits) in a single number.
3
- *
4
- * Note: JavaScript bitwise operations (|, &, ^, <<, >>) operate on 32-bit signed integers.
5
- * Flags with values exceeding 2^30 may exhibit unexpected behavior. For permission-style
6
- * bitfields with more than 30 bits, consider using BigInt-based implementations.
4
+ * Multi-flag storage backed by bigint (supports bits ≥ 32).
7
5
  */
8
- type BitFieldResolvable<S extends string> = S | bigint | number | BitField<S> | (S | number | bigint | BitField<S>)[];
6
+ type BitFieldResolvable<S extends string> = S | bigint | number | string | BitField<S> | readonly (S | number | bigint | string | BitField<S>)[];
9
7
  declare class BitField<S extends string> {
10
8
  static Flags: Record<string, bigint>;
11
- defaultBit: number;
9
+ static DefaultBit: bigint;
12
10
  bitfield: bigint;
13
11
  constructor(bits?: BitFieldResolvable<S>);
14
12
  get [Symbol.toStringTag](): string;
13
+ /** Resolve a resolvable into a single bigint bitfield. */
15
14
  static resolve<S extends string>(bits: BitFieldResolvable<S>): bigint;
15
+ private get ctor();
16
+ private orAll;
17
+ /** Whether this bitfield contains all of the given bits. */
16
18
  has(bit: BitFieldResolvable<S>): boolean;
19
+ /** Whether this bitfield contains any of the given bits. */
20
+ any(bit: BitFieldResolvable<S>): boolean;
21
+ /** Bits present in `bit` but missing from this bitfield. */
22
+ missing(bit: BitFieldResolvable<S>): S[];
17
23
  add(...bits: BitFieldResolvable<S>[]): this;
18
24
  remove(...bits: BitFieldResolvable<S>[]): this;
19
25
  serialize(): Record<S, boolean>;
20
26
  toArray(): S[];
27
+ /** Decimal string of the bigint bitfield (API / JSON). */
21
28
  toJSON(): string;
22
- valueOf(): string;
23
- equals(bitfield: BitField<S>): boolean;
24
- freeze(): Readonly<BitField<S>>;
29
+ toString(): string;
30
+ valueOf(): bigint;
31
+ equals(other: BitFieldResolvable<S>): boolean;
32
+ freeze(): Readonly<this>;
33
+ [Symbol.iterator](): IterableIterator<S>;
25
34
  }
26
35
 
27
- /** Fluxer epoch (2015-01-01 00:00:00 UTC) in milliseconds */
36
+ /** Fluxer epoch (2015-01-01 00:00:00 UTC) in milliseconds. */
28
37
  declare const FLUXER_EPOCH = 1420070400000n;
38
+ interface DeconstructedSnowflake {
39
+ /** Unix timestamp in milliseconds. */
40
+ timestamp: number;
41
+ date: Date;
42
+ workerId: number;
43
+ processId: number;
44
+ increment: number;
45
+ }
29
46
  /**
30
- * Utilities for Fluxer snowflake IDs.
31
- * Fluxer uses Twitter Snowflakes with a custom epoch.
47
+ * Fluxer snowflake IDs (Twitter layout, custom epoch).
48
+ * Public API is string-only — never number — to avoid precision loss above 2^53.
32
49
  */
33
50
  declare class SnowflakeUtil {
34
51
  static readonly EPOCH = 1420070400000n;
52
+ /** Whether `value` is a non-negative decimal snowflake string (≤ 20 digits). */
53
+ static isValid(snowflake: string): boolean;
54
+ /** Parse a snowflake string to bigint. */
55
+ static parse(snowflake: Snowflake): bigint;
56
+ /** Unix timestamp (ms) from a snowflake. */
57
+ static timestampFromSnowflake(snowflake: Snowflake): number;
58
+ /** Date from a snowflake. */
59
+ static dateFromSnowflake(snowflake: Snowflake): Date;
35
60
  /**
36
- * Converts a snowflake to a Unix timestamp in milliseconds.
37
- */
38
- static timestampFromSnowflake(snowflake: string): number;
39
- /**
40
- * Converts a snowflake to a Date.
41
- */
42
- static dateFromSnowflake(snowflake: string): Date;
43
- /**
44
- * Converts a Unix timestamp (ms) to a snowflake string.
45
- * Useful for pagination (before/after).
46
- */
47
- static snowflakeFromTimestamp(timestamp: number): string;
48
- /**
49
- * Deconstructs a snowflake into its components.
50
- * @throws TypeError If snowflake is not a valid numeric string
51
- */
52
- static deconstruct(snowflake: string): {
53
- timestamp: number;
54
- date: Date;
55
- workerId: number;
56
- processId: number;
57
- increment: number;
58
- };
59
- /**
60
- * Checks if a string is a valid snowflake format (numeric string, 0 or positive).
61
+ * Snowflake string from a Unix timestamp (ms).
62
+ * Useful for pagination (`before` / `after`).
61
63
  */
62
- static isValid(snowflake: string): boolean;
64
+ static snowflakeFromTimestamp(timestamp: number): Snowflake;
65
+ /** Deconstruct a snowflake into timestamp / worker / process / increment. */
66
+ static deconstruct(snowflake: Snowflake): DeconstructedSnowflake;
63
67
  }
64
68
 
65
69
  /**
66
- * Permission flags aligned with Fluxer API (fluxer_api/src/constants/Channel.ts).
67
- * Bit positions use BigInt shifts (1n << n).
68
- * Administrator (bit 3) implies all permissions. Guild owner bypasses role computation.
69
- *
70
- * @example
71
- * if (member.permissions.has(PermissionFlags.BanMembers)) { ... }
72
- * if (perms.has(PermissionFlags.Administrator)) { ... }
70
+ * Permission flags aligned with the Fluxer API (`1n << n`).
71
+ * Administrator (bit 3) implies all permissions in {@link PermissionsBitField.has}.
73
72
  */
74
73
  declare const PermissionFlags: {
75
74
  readonly CreateInstantInvite: bigint;
@@ -101,7 +100,7 @@ declare const PermissionFlags: {
101
100
  readonly ManageNicknames: bigint;
102
101
  readonly ManageRoles: bigint;
103
102
  readonly ManageWebhooks: bigint;
104
- readonly ManageEmojisAndStickers: bigint;
103
+ /** Manage emojis & stickers (expressions). */
105
104
  readonly ManageExpressions: bigint;
106
105
  readonly UseExternalStickers: bigint;
107
106
  readonly ModerateMembers: bigint;
@@ -109,10 +108,12 @@ declare const PermissionFlags: {
109
108
  readonly PinMessages: bigint;
110
109
  readonly BypassSlowmode: bigint;
111
110
  readonly UpdateRtcRegion: bigint;
111
+ readonly ViewChannelMembers: bigint;
112
112
  };
113
- /** BigInt OR of all permission flags. Used for guild owner override (owner has all perms). */
113
+ /** OR of all permission flags (guild owner / Administrator override). */
114
114
  declare const ALL_PERMISSIONS_BIGINT: bigint;
115
115
  type PermissionString = keyof typeof PermissionFlags;
116
+ type PermissionResolvable = BitFieldResolvable<PermissionString>;
116
117
  declare class PermissionsBitField extends BitField<PermissionString> {
117
118
  static Flags: {
118
119
  readonly CreateInstantInvite: bigint;
@@ -144,7 +145,7 @@ declare class PermissionsBitField extends BitField<PermissionString> {
144
145
  readonly ManageNicknames: bigint;
145
146
  readonly ManageRoles: bigint;
146
147
  readonly ManageWebhooks: bigint;
147
- readonly ManageEmojisAndStickers: bigint;
148
+ /** Manage emojis & stickers (expressions). */
148
149
  readonly ManageExpressions: bigint;
149
150
  readonly UseExternalStickers: bigint;
150
151
  readonly ModerateMembers: bigint;
@@ -152,23 +153,20 @@ declare class PermissionsBitField extends BitField<PermissionString> {
152
153
  readonly PinMessages: bigint;
153
154
  readonly BypassSlowmode: bigint;
154
155
  readonly UpdateRtcRegion: bigint;
156
+ readonly ViewChannelMembers: bigint;
155
157
  };
158
+ private get isAdmin();
159
+ /** Administrator implies every permission. */
160
+ has(bit: PermissionResolvable): boolean;
161
+ any(bit: PermissionResolvable): boolean;
162
+ missing(bit: PermissionResolvable): PermissionString[];
156
163
  }
157
- type PermissionResolvable = BitFieldResolvable<PermissionString>;
158
- /**
159
- * Resolve permission(s) to an API bitfield string. Uses BigInt to avoid overflow for flags > 2^31.
160
- * @param perms - Permission string (e.g. "2048"), number, PermissionString, array of permissions, or PermissionsBitField
161
- * @returns String bitfield for API (e.g. "8933636165185")
162
- * @example
163
- * resolvePermissionsToBitfield('2048'); // "2048"
164
- * resolvePermissionsToBitfield(PermissionFlags.SendMessages); // "2048"
165
- * resolvePermissionsToBitfield(['SendMessages', 'ViewChannel']); // combined bitfield
166
- */
164
+ /** Resolve permission(s) to an API bitfield string (decimal bigint). */
167
165
  declare function resolvePermissionsToBitfield(perms: PermissionResolvable): string;
168
166
 
169
167
  /**
170
- * Message flag bit values matching the API MessageFlags schema (openapi.json).
171
- * Format: int32.
168
+ * Message flag bits for {@link MessageFlagsBitField}.
169
+ * Values mirror `@fluxerjs/types` {@link MessageFlags} (int32 wire bitfield) as bigint.
172
170
  */
173
171
  declare const MessageFlagsBits: {
174
172
  readonly SuppressEmbeds: bigint;
@@ -177,6 +175,7 @@ declare const MessageFlagsBits: {
177
175
  readonly CompactAttachments: bigint;
178
176
  };
179
177
  type MessageFlagsString = keyof typeof MessageFlagsBits;
178
+ type MessageFlagsResolvable = BitFieldResolvable<MessageFlagsString>;
180
179
  declare class MessageFlagsBitField extends BitField<MessageFlagsString> {
181
180
  static Flags: {
182
181
  readonly SuppressEmbeds: bigint;
@@ -185,12 +184,10 @@ declare class MessageFlagsBitField extends BitField<MessageFlagsString> {
185
184
  readonly CompactAttachments: bigint;
186
185
  };
187
186
  }
188
- type MessageFlagsResolvable = BitFieldResolvable<MessageFlagsString>;
189
187
 
190
188
  /**
191
- * User flag bit values matching the API UserFlags schema (openapi.json).
192
- * Values are int64; bit shifts used where within 32-bit range, literals otherwise.
193
- * Note: BitField's has/add/remove use JS bitwise ops (32-bit); full values are for API serialization.
189
+ * User flag bits matching the API UserFlags schema (int64).
190
+ * Stored as bigint so bits ≥ 32 work with {@link BitField} operations.
194
191
  */
195
192
  declare const UserFlagsBits: {
196
193
  readonly Staff: bigint;
@@ -226,6 +223,7 @@ declare const UserFlagsBits: {
226
223
  readonly StaffHidden: bigint;
227
224
  };
228
225
  type UserFlagsString = keyof typeof UserFlagsBits;
226
+ type UserFlagsResolvable = BitFieldResolvable<UserFlagsString>;
229
227
  declare class UserFlagsBitField extends BitField<UserFlagsString> {
230
228
  static Flags: {
231
229
  readonly Staff: bigint;
@@ -261,74 +259,63 @@ declare class UserFlagsBitField extends BitField<UserFlagsString> {
261
259
  readonly StaffHidden: bigint;
262
260
  };
263
261
  }
264
- type UserFlagsResolvable = BitFieldResolvable<UserFlagsString>;
265
262
 
266
263
  /**
267
- * Format a number as a hex color string.
264
+ * Format a number as a `#rrggbb` hex color string.
268
265
  */
269
266
  declare function formatColor(color: number): string;
270
267
  /**
271
268
  * Escape markdown formatting characters in a string.
272
269
  */
273
270
  declare function escapeMarkdown(text: string): string;
271
+ type TimestampStyle = 't' | 'T' | 'd' | 'D' | 'f' | 'F' | 'R';
274
272
  /**
275
- * Format a Unix timestamp for Fluxer/Discord style timestamps.
276
- * @param timestamp - Unix timestamp in seconds
277
- * @param style - t, T, d, D, f, F, R, etc.
273
+ * Format a Unix timestamp (milliseconds) as a Fluxer/Discord timestamp mention.
274
+ * @param timestampMs - Unix timestamp in milliseconds
275
+ * @param style - Optional display style (`t`, `T`, `d`, `D`, `f`, `F`, `R`)
278
276
  */
279
- declare function formatTimestamp(timestamp: number, style?: 't' | 'T' | 'd' | 'D' | 'f' | 'F' | 'R'): string;
277
+ declare function formatTimestamp(timestampMs: number, style?: TimestampStyle): string;
280
278
  /**
281
279
  * Truncate a string to a maximum length with an optional suffix.
280
+ * If `maxLength` is smaller than the suffix, returns the suffix truncated to `maxLength`.
282
281
  */
283
282
  declare function truncate(str: string, maxLength: number, suffix?: string): string;
284
283
 
285
284
  /**
286
- * Resolve a color from various input types to a number (0-16777215).
287
- */
288
- declare function resolveColor(color: number | string | [number, number, number]): number;
289
- /**
290
- * Parse an emoji string into id and name.
291
- * Supports: <a?:name:id> (mention), :name: (colons), name:id (API format), unicode.
285
+ * Resolve a color from various input types to a number (0–16777215).
292
286
  */
293
- declare function parseEmoji(emoji: string): {
287
+ declare function resolveColor(color: number | string | readonly [number, number, number]): number;
288
+ interface ParsedEmoji {
294
289
  id: string | null;
295
290
  name: string;
296
291
  animated?: boolean;
297
- } | null;
292
+ }
293
+ /**
294
+ * Parse an emoji string into id and name.
295
+ * Supports: `<a?:name:id>`, `:name:`, `name:id`, unicode.
296
+ */
297
+ declare function parseEmoji(emoji: string): ParsedEmoji | null;
298
298
  /**
299
- * Parse a user mention string or raw snowflake and extract the user ID.
300
- * Supports: <@123456789012345678>, <@!123456789012345678>, or raw 17–19 digit snowflake.
301
- * @param arg - String that may contain a user mention or raw user ID
302
- * @returns The user ID if valid, otherwise null
303
- * @example
304
- * parseUserMention('<@!123456789012345678>'); // '123456789012345678'
305
- * parseUserMention('<@123456789012345678>'); // '123456789012345678'
306
- * parseUserMention('123456789012345678'); // '123456789012345678'
299
+ * Parse a user mention or raw snowflake and extract the user ID.
300
+ * Supports: `<@id>`, `<@!id>`, or a valid snowflake string.
307
301
  */
308
302
  declare function parseUserMention(arg: string): string | null;
309
303
  /**
310
- * Parse prefix command content into command name and args.
311
- * Returns null if content does not start with the prefix.
312
- * @param content - Raw message content
313
- * @param prefix - Command prefix (e.g. '!')
314
- * @returns { command, args } or null
315
- * @example
316
- * parsePrefixCommand('!ping', '!'); // { command: 'ping', args: [] }
317
- * parsePrefixCommand('!hello world', '!'); // { command: 'hello', args: ['world'] }
304
+ * Parse a role mention (`<@&id>`) and extract the role ID.
318
305
  */
319
- declare function parsePrefixCommand(content: string, prefix: string): {
306
+ declare function parseRoleMention(arg: string): string | null;
307
+ interface ParsedPrefixCommand {
320
308
  command: string;
321
309
  args: string[];
322
- } | null;
310
+ }
323
311
  /**
324
- * Parse a role mention string (e.g. <@&123456>) and extract the role ID.
325
- * @param arg - String that may contain a role mention
326
- * @returns The role ID if valid mention, otherwise null
312
+ * Parse prefix command content into command name and args.
313
+ * Returns null if content does not start with the prefix.
327
314
  */
328
- declare function parseRoleMention(arg: string): string | null;
315
+ declare function parsePrefixCommand(content: string, prefix: string): ParsedPrefixCommand | null;
329
316
  /**
330
- * Convert emoji to the format used in API (for reactions etc).
331
- * Custom: "name:id", Unicode: "unicode"
317
+ * Convert emoji to API reaction format.
318
+ * Custom: `name:id` (animated: `a:name:id`); Unicode: URI-encoded character.
332
319
  */
333
320
  declare function formatEmoji(emoji: {
334
321
  id: string | null;
@@ -348,29 +335,15 @@ interface TenorMediaResult {
348
335
  flags?: number;
349
336
  }
350
337
  /**
351
- * Resolve a Tenor view URL to a direct GIF URL for use in embeds.
352
- * Embeds require GIF format (not MP4). Fetches the Tenor page for JSON-LD
353
- * or oEmbed, then derives the GIF URL from the media.tenor.com path.
354
- *
355
- * @param tenorViewUrl - Tenor view URL (e.g. https://tenor.com/view/stressed-gif-7048057395502071840)
356
- * @returns { url, flags? } for setImage/setThumbnail, or null if resolution fails
357
- * @example
358
- * const media = await resolveTenorToImageUrl('https://tenor.com/view/stressed-gif-7048057395502071840');
359
- * if (media) embed.setImage(media);
338
+ * Resolve a Tenor view URL to a direct GIF URL for embeds.
339
+ * Prefers JSON-LD from the page; falls back to oEmbed thumbnail → `.gif`.
360
340
  */
361
341
  declare function resolveTenorToImageUrl(tenorViewUrl: string): Promise<TenorMediaResult | null>;
362
342
 
363
- declare function emitDeprecationWarning(symbol: string, message: string): void;
364
-
365
- interface FluxerErrorOptions {
366
- code?: string;
367
- cause?: Error;
368
- }
369
- declare class FluxerError extends Error {
370
- readonly code?: string;
371
- constructor(message: string, options?: FluxerErrorOptions);
372
- }
373
-
343
+ /**
344
+ * Stable machine-readable error codes for {@link FluxerError}.
345
+ * Keys are PascalCase; values are SCREAMING_SNAKE.
346
+ */
374
347
  declare const ErrorCodes: {
375
348
  readonly ClientNotReady: "CLIENT_NOT_READY";
376
349
  readonly NotLoggedIn: "NOT_LOGGED_IN";
@@ -399,9 +372,48 @@ declare const ErrorCodes: {
399
372
  readonly VoiceWebSocketRequired: "VOICE_WEBSOCKET_REQUIRED";
400
373
  readonly VoiceHttpError: "VOICE_HTTP_ERROR";
401
374
  readonly VoiceNoResponseBody: "VOICE_NO_RESPONSE_BODY";
402
- readonly InteractionOptionNotFound: "INTERACTION_OPTION_NOT_FOUND";
403
- readonly InteractionOptionTypeMismatch: "INTERACTION_OPTION_TYPE_MISMATCH";
404
- readonly InteractionInvalidPayload: "INTERACTION_INVALID_PAYLOAD";
375
+ readonly InvalidInstanceDiscovery: "INVALID_INSTANCE_DISCOVERY";
376
+ readonly ConflictingInstanceConfig: "CONFLICTING_INSTANCE_CONFIG";
377
+ /** @beta ClientCluster: duplicate runtime id */
378
+ readonly DuplicateRuntimeId: "DUPLICATE_RUNTIME_ID";
379
+ /** @beta ClientCluster: unknown runtime id */
380
+ readonly RuntimeNotFound: "RUNTIME_NOT_FOUND";
381
+ /** @beta ClientCluster: concurrent conflicting op on same id */
382
+ readonly RuntimeConflict: "RUNTIME_CONFLICT";
383
+ /** @beta ClientCluster: cluster already destroyed */
384
+ readonly ClusterDestroyed: "CLUSTER_DESTROYED";
385
+ /** @beta ClientCluster: prebuilt client already logged in */
386
+ readonly RuntimeAlreadyLoggedIn: "RUNTIME_ALREADY_LOGGED_IN";
387
+ /** @beta ClientCluster: missing/empty runtime id or token */
388
+ readonly InvalidRuntimeConfig: "INVALID_RUNTIME_CONFIG";
389
+ readonly EmptyMessage: "EMPTY_MESSAGE";
390
+ readonly InvalidMessageOptions: "INVALID_MESSAGE_OPTIONS";
391
+ readonly InvalidBulkDelete: "INVALID_BULK_DELETE";
392
+ /** Fetch / bulk-fetch limit or batch size out of range. */
393
+ readonly InvalidFetchLimit: "INVALID_FETCH_LIMIT";
394
+ /** Attachment plan/file mismatch or invalid attachment input. */
395
+ readonly InvalidAttachmentInput: "INVALID_ATTACHMENT_INPUT";
396
+ /** Presigned CDN PUT failed. */
397
+ readonly AttachmentUploadFailed: "ATTACHMENT_UPLOAD_FAILED";
398
+ /** Operation requires a personal-notes channel (or wrong channel type). */
399
+ readonly InvalidChannelType: "INVALID_CHANNEL_TYPE";
405
400
  };
401
+ type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
402
+
403
+ interface FluxerErrorOptions {
404
+ /** Machine-readable code from {@link ErrorCodes}. */
405
+ code?: ErrorCode | string;
406
+ cause?: unknown;
407
+ }
408
+ /**
409
+ * Base error for Fluxer SDK failures.
410
+ * Prefer an {@link ErrorCodes} value so callers can branch on `error.code`.
411
+ */
412
+ declare class FluxerError extends Error {
413
+ readonly code: string | undefined;
414
+ constructor(message: string, options?: FluxerErrorOptions);
415
+ static isFluxerError(error: unknown): error is FluxerError;
416
+ toString(): string;
417
+ }
406
418
 
407
- export { ALL_PERMISSIONS_BIGINT, BitField, type BitFieldResolvable, ErrorCodes, FLUXER_EPOCH, FluxerError, type FluxerErrorOptions, MessageFlagsBitField, MessageFlagsBits, type MessageFlagsResolvable, type MessageFlagsString, PermissionFlags, type PermissionResolvable, type PermissionString, PermissionsBitField, SnowflakeUtil, type TenorMediaResult, UserFlagsBitField, UserFlagsBits, type UserFlagsResolvable, type UserFlagsString, emitDeprecationWarning, escapeMarkdown, formatColor, formatEmoji, formatTimestamp, getUnicodeFromShortcode, parseEmoji, parsePrefixCommand, parseRoleMention, parseUserMention, resolveColor, resolvePermissionsToBitfield, resolveTenorToImageUrl, truncate };
419
+ export { ALL_PERMISSIONS_BIGINT, BitField, type BitFieldResolvable, type DeconstructedSnowflake, type ErrorCode, ErrorCodes, FLUXER_EPOCH, FluxerError, type FluxerErrorOptions, MessageFlagsBitField, MessageFlagsBits, type MessageFlagsResolvable, type MessageFlagsString, type ParsedEmoji, type ParsedPrefixCommand, PermissionFlags, type PermissionResolvable, type PermissionString, PermissionsBitField, SnowflakeUtil, type TenorMediaResult, type TimestampStyle, UserFlagsBitField, UserFlagsBits, type UserFlagsResolvable, type UserFlagsString, escapeMarkdown, formatColor, formatEmoji, formatTimestamp, getUnicodeFromShortcode, parseEmoji, parsePrefixCommand, parseRoleMention, parseUserMention, resolveColor, resolvePermissionsToBitfield, resolveTenorToImageUrl, truncate };