feat: redis api client, serialization

This commit is contained in:
xHyroM 2023-04-09 13:23:41 +02:00
parent ff76746cec
commit fb1290dacf
No known key found for this signature in database
GPG key ID: BE0423F386C436AA
34 changed files with 1035 additions and 1017 deletions

View file

@ -39,11 +39,11 @@ Promise.all([
}), }),
]) ])
.catch((err) => { .catch((err) => {
console.error("Builders failed to build"); console.error("Redis api failed to build");
console.error(err.message); console.error(err.message);
}) })
.then(() => { .then(() => {
console.log( console.log(
watch ? "Waiting for your changes..." : "Builders has been built", watch ? "Waiting for your changes..." : "Redis api has been built",
); );
}); });

View file

@ -23,6 +23,7 @@
"dependencies": { "dependencies": {
"builders": "workspace:*", "builders": "workspace:*",
"serialize": "workspace:*", "serialize": "workspace:*",
"redis-api-client": "workspace:*",
"discord-api-types": "^0.37.37" "discord-api-types": "^0.37.37"
} }
} }

View file

@ -1,39 +1,61 @@
import { Command } from "../structs/Command"; import { Command } from "../structs/Command";
import { import {
APIRole,
ChannelType, ChannelType,
InteractionResponseType,
MessageFlags, MessageFlags,
RouteBases,
Routes,
} from "discord-api-types/v10"; } from "discord-api-types/v10";
import { ActionRowBuilder, ChannelSelectMenuBuilder } from "builders"; import { ActionRowBuilder, ChannelSelectMenuBuilder } from "builders";
import { serializers } from "serialize"; import { REDIS } from "../things";
import { encodeToHex } from "serialize";
// Part 1 ## select channel // Part 1 ## select channel
new Command({ new Command({
name: "setup", name: "setup",
acknowledge: false, flags: MessageFlags.Ephemeral,
run: async (ctx) => { run: async (ctx) => {
return ctx.respond({ if (!ctx.guildId)
type: InteractionResponseType.ChannelMessageWithSource, return await ctx.editReply({
data: { content: "Guild not found.",
content: "Select the channel to which the panel will be sent.", });
components: [
new ActionRowBuilder<ChannelSelectMenuBuilder>() // Delete the data if it exists
.addComponents( await REDIS.del(`roles-bot-setup:${ctx.guildId}`);
new ChannelSelectMenuBuilder()
.setCustomId( const roles = (await (
serializers.genericObject.encodeCustomId({ await fetch(`${RouteBases.api}${Routes.guildRoles(ctx.guildId)}`, {
type: "setup:part-channel", headers: {
}), Authorization: `Bot ${ctx.env.token}`,
) },
.addChannelTypes( })
ChannelType.GuildAnnouncement, ).json()) as APIRole[];
ChannelType.GuildText,
), await REDIS.setex(
) `roles-bot-setup-roles:${ctx.guildId}`,
.toJSON(), encodeToHex(
], roles.map((r) => ({
flags: MessageFlags.Ephemeral, id: r.id,
}, name: r.name,
})),
),
3600,
);
await ctx.editReply({
content: "Select the channel to which the panel will be sent.",
components: [
new ActionRowBuilder<ChannelSelectMenuBuilder>()
.addComponents(
new ChannelSelectMenuBuilder()
.setCustomId("setup:part-channel")
.addChannelTypes(
ChannelType.GuildAnnouncement,
ChannelType.GuildText,
),
)
.toJSON(),
],
}); });
}, },
}); });

View file

@ -12,17 +12,32 @@ import {
MessageFlags, MessageFlags,
TextInputStyle, TextInputStyle,
} from "discord-api-types/v10"; } from "discord-api-types/v10";
import { serializers } from "serialize";
import returnRoleLpe from "../utils/returnRoleLpe"; import returnRoleLpe from "../utils/returnRoleLpe";
import { REDIS } from "../things";
import { encodeToHex, decodeFromString } from "serialize";
// Part 2 Channels ## select button/dropdowns // Part 2 Channels ## select button/dropdowns
new Component({ new Component({
id: "setup:part-channel", id: "setup:part-channel",
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
run: async (ctx) => { run: async (ctx) => {
if (!ctx.interaction.guild_id)
return await ctx.editReply({
content: "Guild not found.",
});
const interaction = const interaction =
ctx.interaction as APIMessageComponentSelectMenuInteraction; ctx.interaction as APIMessageComponentSelectMenuInteraction;
const channelId = interaction.data.values[0];
const data = {
channelId: interaction.data.values[0],
};
await REDIS.setex(
`roles-bot-setup:${interaction.guild_id}`,
encodeToHex(data),
600,
);
await ctx.editReply({ await ctx.editReply({
content: content:
@ -32,27 +47,11 @@ new Component({
.addComponents( .addComponents(
new ButtonBuilder() new ButtonBuilder()
.setLabel("Buttons") .setLabel("Buttons")
.setCustomId( .setCustomId("setup:part-selecting:buttons")
serializers.genericObject.encodeCustomId({
type: "setup:part-selecting",
data: {
channelId,
selecting: 1,
},
}),
)
.setStyle(ButtonStyle.Primary), .setStyle(ButtonStyle.Primary),
new ButtonBuilder() new ButtonBuilder()
.setLabel("Dropdowns") .setLabel("Dropdowns")
.setCustomId( .setCustomId("setup:part-selecting:dropdowns")
serializers.genericObject.encodeCustomId({
type: "setup:part-selecting",
data: {
channelId,
selecting: 2,
},
}),
)
.setStyle(ButtonStyle.Primary), .setStyle(ButtonStyle.Primary),
) )
.toJSON(), .toJSON(),
@ -66,7 +65,25 @@ new Component({
id: "setup:part-selecting", id: "setup:part-selecting",
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
run: async (ctx) => { run: async (ctx) => {
const data = ctx.decodedId.data; if (!ctx.interaction.guild_id)
return await ctx.editReply({ content: "Guild not found." });
const rawData = await REDIS.get(
`roles-bot-setup:${ctx.interaction.guild_id}`,
);
if (!rawData)
return await ctx.editReply({
content: "Data not found. Try running setup again.",
});
const data = decodeFromString(rawData);
data.selecting = ctx.interaction.data.custom_id.split(":")[2];
await REDIS.setex(
`roles-bot-setup:${ctx.interaction.guild_id}`,
encodeToHex(data),
600,
);
await ctx.editReply({ await ctx.editReply({
content: "Select the roles that will be available in the menu.", content: "Select the roles that will be available in the menu.",
@ -74,12 +91,7 @@ new Component({
new ActionRowBuilder<RoleSelectMenuBuilder>() new ActionRowBuilder<RoleSelectMenuBuilder>()
.addComponents( .addComponents(
new RoleSelectMenuBuilder() new RoleSelectMenuBuilder()
.setCustomId( .setCustomId("setup:part-roles")
serializers.genericObject.encodeCustomId({
type: "setup:part-roles",
data,
}),
)
.setPlaceholder("Select roles") .setPlaceholder("Select roles")
.setMinValues(1) .setMinValues(1)
.setMaxValues(25), .setMaxValues(25),
@ -94,23 +106,41 @@ new Component({
new Component({ new Component({
id: "setup:part-roles", id: "setup:part-roles",
acknowledge: false, acknowledge: false,
run: (ctx) => { run: async (ctx) => {
const previousData = ctx.decodedId.data; if (!ctx.interaction.guild_id)
return await ctx.editReply({ content: "Guild not found." });
const interaction = const interaction =
ctx.interaction as APIMessageComponentSelectMenuInteraction; ctx.interaction as APIMessageComponentSelectMenuInteraction;
const rawRoleIds =
(previousData.rawRoleIds as string[]) ?? interaction.data.values;
const data = { ...previousData, rawRoleIds }; const rawData = await REDIS.get(
`roles-bot-setup:${ctx.interaction.guild_id}`,
);
if (!rawData)
return ctx.respond({
type: InteractionResponseType.ChannelMessageWithSource,
data: {
content: "Data not found. Try running setup again.",
flags: MessageFlags.Ephemeral,
},
});
const data = decodeFromString(rawData);
const rawRoleIds = (data.rawRoleIds as string[]) ?? interaction.data.values;
data.rawRoleIds = rawRoleIds;
await REDIS.setex(
`roles-bot-setup:${ctx.interaction.guild_id}`,
encodeToHex(data),
600,
);
return rawRoleIds.length > 0 return rawRoleIds.length > 0
? returnRoleLpe(data, ctx, rawRoleIds[0]) ? returnRoleLpe(ctx, rawRoleIds[0])
: ctx.returnModal({ : ctx.returnModal({
title: "Message Preview", title: "Message Preview",
custom_id: serializers.genericObject.encodeCustomId({ custom_id: "setup:part-messageContent",
type: "setup:part-messageContent",
data,
}),
components: [ components: [
new ActionRowBuilder<TextInputBuilder>() new ActionRowBuilder<TextInputBuilder>()
.addComponents( .addComponents(
@ -166,30 +196,38 @@ new Component({
id: "setup:part-sendAs", id: "setup:part-sendAs",
acknowledge: false, acknowledge: false,
run: async (ctx) => { run: async (ctx) => {
const channelId = ctx.decodedId.data.channelId; if (!ctx.interaction.guild_id)
const selecting = return await ctx.editReply({ content: "Guild not found." });
ctx.decodedId.data.selecting === 1 ? "buttons" : "dropdowns";
const roleIds = ctx.decodedId.data.roleIds as {
label: string;
placeholder: string;
emoji: string;
}[];
const message = ctx.decodedId.data.message;
const sendAs = ctx.decodedId.data.sendAs === 1 ? "webhook" : "bot";
console.log(channelId, roleIds, message, sendAs); const rawData = await REDIS.get(
`roles-bot-setup:${ctx.interaction.guild_id}`,
);
if (!rawData)
return ctx.respond({
type: InteractionResponseType.ChannelMessageWithSource,
data: {
content: "Data not found. Try running setup again.",
flags: MessageFlags.Ephemeral,
},
});
const data = decodeFromString(rawData);
console.log(data);
// delete data
await REDIS.del(`roles-bot-setup:${ctx.guildId}`);
// TODO: finish sending // TODO: finish sending
const actionRow = new ActionRowBuilder(); const actionRow = new ActionRowBuilder();
switch (selecting) { /*switch (selecting) {
case "buttons": { case "buttons": {
// TOOD: finish // TOOD: finish
} }
case "dropdowns": { case "dropdowns": {
// TODO: finish // TODO: finish
} }
} }*/
return ctx.respond({ return ctx.respond({
type: InteractionResponseType.ChannelMessageWithSource, type: InteractionResponseType.ChannelMessageWithSource,

View file

@ -10,7 +10,7 @@ import {
InteractionResponseType, InteractionResponseType,
InteractionType, InteractionType,
} from "discord-api-types/v10"; } from "discord-api-types/v10";
import { COMMANDS, COMPONENTS, MODALS } from "./registers"; import { COMMANDS, COMPONENTS, MODALS, REDIS, setRedis } from "./things";
import { verify } from "./utils/verify"; import { verify } from "./utils/verify";
import respond from "./utils/respond"; import respond from "./utils/respond";
import { CommandContext } from "./structs/contexts/CommandContext"; import { CommandContext } from "./structs/contexts/CommandContext";
@ -20,6 +20,8 @@ import { Env } from "./types";
export default { export default {
fetch: async (request: Request, env: Env) => { fetch: async (request: Request, env: Env) => {
if (!REDIS) setRedis(env.redisApiClientKey, env.redisApiClientHost);
if ( if (
!request.headers.get("X-Signature-Ed25519") || !request.headers.get("X-Signature-Ed25519") ||
!request.headers.get("X-Signature-Timestamp") !request.headers.get("X-Signature-Timestamp")
@ -66,7 +68,9 @@ export default {
} }
case InteractionType.ModalSubmit: { case InteractionType.ModalSubmit: {
const context = new ModalContext(interaction, env); const context = new ModalContext(interaction, env);
const modal = MODALS.find((md) => md.id === context.decodedId.type); const modal = MODALS.find((md) =>
context.interaction.data.custom_id.startsWith(md.id),
);
if (!modal) return new Response("Unknown modal", { status: 404 }); if (!modal) return new Response("Unknown modal", { status: 404 });
@ -88,8 +92,8 @@ export default {
} }
case InteractionType.MessageComponent: { case InteractionType.MessageComponent: {
const context = new ComponentContext(interaction, env); const context = new ComponentContext(interaction, env);
const component = COMPONENTS.find( const component = COMPONENTS.find((cmp) =>
(cmp) => cmp.id === context.decodedId.type, context.interaction.data.custom_id.startsWith(cmp.id),
); );
if (!component) if (!component)

View file

@ -5,16 +5,24 @@ import {
} from "discord-api-types/v10"; } from "discord-api-types/v10";
import { Modal } from "../structs/Modal"; import { Modal } from "../structs/Modal";
import { ActionRowBuilder, ButtonBuilder } from "builders"; import { ActionRowBuilder, ButtonBuilder } from "builders";
import { serializers } from "serialize"; import { encodeToHex, decodeFromString } from "serialize";
import { REDIS } from "../things";
// Part 5 Roles ## add label, placeholder, emoji OR message content // Part 5 Roles ## add label, placeholder, emoji OR message content
new Modal({ new Modal({
id: "setup:part-roles-lpe", id: "setup:part-roles-lpe",
acknowledge: false,
run: async (ctx) => { run: async (ctx) => {
const previousData = ctx.decodedId.data; const rawData = await REDIS.get(
const rawRoleIds = previousData.rawRoleIds as string[]; `roles-bot-setup:${ctx.interaction.guild_id}`,
const roleIds = (previousData.roleIds ?? []) as { );
if (!rawData)
return await ctx.editReply({
content: "Data not found. Try running setup again.",
});
const data = decodeFromString(rawData);
const rawRoleIds = data.rawRoleIds as string[];
const roleIds = (data.roleIds ?? []) as {
label: string; label: string;
placeholder: string; placeholder: string;
emoji: string; emoji: string;
@ -27,34 +35,29 @@ new Modal({
roleIds.push({ label, placeholder, emoji }); roleIds.push({ label, placeholder, emoji });
rawRoleIds.shift(); rawRoleIds.shift();
previousData.rawRoleIds = rawRoleIds; data.rawRoleIds = rawRoleIds;
const data = { ...previousData, roleIds };
return ctx.respond({ await REDIS.setex(
type: InteractionResponseType.ChannelMessageWithSource, `roles-bot-setup:${ctx.interaction.guild_id}`,
data: { encodeToHex(data),
content: 600,
rawRoleIds.length > 0 );
? "Click the button to set the label, placeholder and emoji for next role."
: "Click the button to set message content or embed.", return await ctx.editReply({
components: [ content:
new ActionRowBuilder<ButtonBuilder>() rawRoleIds.length > 0
.addComponents( ? "Click the button to set the label, placeholder and emoji for next role."
new ButtonBuilder() : "Click the button to set message content or embed.",
.setLabel( components: [
rawRoleIds.length > 0 ? "Next Role" : "Message Content", new ActionRowBuilder<ButtonBuilder>()
) .addComponents(
.setCustomId( new ButtonBuilder()
serializers.genericObject.encodeCustomId({ .setLabel(rawRoleIds.length > 0 ? "Next Role" : "Message Content")
type: "setup:part-roles", .setCustomId("setup:part-roles")
data, .setStyle(ButtonStyle.Primary),
}), )
) .toJSON(),
.setStyle(ButtonStyle.Primary), ],
)
.toJSON(),
],
},
}); });
}, },
}); });
@ -64,15 +67,22 @@ new Modal({
id: "setup:part-messageContent", id: "setup:part-messageContent",
flags: MessageFlags.Ephemeral, flags: MessageFlags.Ephemeral,
run: async (ctx) => { run: async (ctx) => {
const previousData = ctx.decodedId.data; const rawData = await REDIS.get(
`roles-bot-setup:${ctx.interaction.guild_id}`,
);
if (!rawData)
return await ctx.editReply({
content: "Data not found. Try running setup again.",
});
const data = decodeFromString(rawData);
const content = ctx.interaction.data.components[0].components[0].value; const content = ctx.interaction.data.components[0].components[0].value;
const embedTitle = ctx.interaction.data.components[1].components[0].value; const embedTitle = ctx.interaction.data.components[1].components[0].value;
const embedDescription = const embedDescription =
ctx.interaction.data.components[2].components[0].value; ctx.interaction.data.components[2].components[0].value;
const embedColor = ctx.interaction.data.components[3].components[0].value; const embedColor = ctx.interaction.data.components[3].components[0].value;
console.log("asd");
if (!content && !embedTitle && !embedDescription) { if (!content && !embedTitle && !embedDescription) {
await ctx.editReply({ await ctx.editReply({
content: "You must provide a message content or embed.", content: "You must provide a message content or embed.",
@ -82,14 +92,15 @@ new Modal({
return; return;
} }
const data = { data.message = { content, embedTitle, embedDescription, embedColor };
...previousData,
message: { content, embedTitle, embedDescription, embedColor },
};
console.log("edit"); await REDIS.setex(
`roles-bot-setup:${ctx.interaction.guild_id}`,
encodeToHex(data),
600,
);
const o = await ctx.editReply({ await ctx.editReply({
content: content:
"Choose whether you want to send the message as a webhook or as a bot.", "Choose whether you want to send the message as a webhook or as a bot.",
components: [ components: [
@ -97,33 +108,15 @@ new Modal({
.addComponents( .addComponents(
new ButtonBuilder() new ButtonBuilder()
.setLabel("Webhook") .setLabel("Webhook")
.setCustomId( .setCustomId("setup:part-sendAs:webhook")
serializers.genericObject.encodeCustomId({
type: "setup:part-sendAs",
data: {
...data,
sendAs: 1,
},
}),
)
.setStyle(ButtonStyle.Primary), .setStyle(ButtonStyle.Primary),
new ButtonBuilder() new ButtonBuilder()
.setLabel("Bot") .setLabel("Bot")
.setCustomId( .setCustomId("setup:part-sendAs:bot")
serializers.genericObject.encodeCustomId({
type: "setup:part-sendAs",
data: {
...data,
sendAs: 2,
},
}),
)
.setStyle(ButtonStyle.Primary), .setStyle(ButtonStyle.Primary),
) )
.toJSON(), .toJSON(),
], ],
}); });
console.log(data);
}, },
}); });

View file

@ -1,5 +1,5 @@
import { MessageFlags } from "discord-api-types/v10"; import { MessageFlags } from "discord-api-types/v10";
import { registerCommand } from "../registers"; import { registerCommand } from "../things";
import { CommandContext } from "./contexts/CommandContext"; import { CommandContext } from "./contexts/CommandContext";
interface CommandOptions { interface CommandOptions {

View file

@ -1,5 +1,5 @@
import { MessageFlags } from "discord-api-types/v10"; import { MessageFlags } from "discord-api-types/v10";
import { registerComponent } from "../registers"; import { registerComponent } from "../things";
import { ComponentContext } from "./contexts/ComponentContext"; import { ComponentContext } from "./contexts/ComponentContext";
interface ComponentOptions { interface ComponentOptions {

View file

@ -1,5 +1,5 @@
import { MessageFlags } from "discord-api-types/v10"; import { MessageFlags } from "discord-api-types/v10";
import { registerModal } from "../registers"; import { registerModal } from "../things";
import { ModalContext } from "./contexts/ModalContext"; import { ModalContext } from "./contexts/ModalContext";
interface ModalOptions { interface ModalOptions {

View file

@ -1,18 +1,13 @@
import { APIMessageComponentInteraction } from "discord-api-types/v10"; import { APIMessageComponentInteraction } from "discord-api-types/v10";
import { DeclaredId, Env } from "../../types"; import { Env } from "../../types";
import { serializers } from "serialize";
import { Context } from "./Context"; import { Context } from "./Context";
export class ComponentContext extends Context { export class ComponentContext extends Context {
public decodedId: DeclaredId;
public interaction: APIMessageComponentInteraction; public interaction: APIMessageComponentInteraction;
constructor(interaction: APIMessageComponentInteraction, env: Env) { constructor(interaction: APIMessageComponentInteraction, env: Env) {
super(interaction, env); super(interaction, env);
this.decodedId = serializers.genericObject.decodeCustomId(
interaction.data.custom_id,
) as DeclaredId;
this.interaction = interaction; this.interaction = interaction;
} }
} }

View file

@ -18,6 +18,10 @@ export class Context {
this.env = env; this.env = env;
} }
get guildId() {
return this.interaction.guild_id;
}
public respond = respond; public respond = respond;
public async editReply(content: APIInteractionResponseCallbackData) { public async editReply(content: APIInteractionResponseCallbackData) {

View file

@ -1,18 +1,13 @@
import { APIModalSubmitInteraction } from "discord-api-types/v10"; import { APIModalSubmitInteraction } from "discord-api-types/v10";
import { DeclaredId, Env } from "../../types";
import { serializers } from "serialize";
import { Context } from "./Context"; import { Context } from "./Context";
import { Env } from "../../types";
export class ModalContext extends Context { export class ModalContext extends Context {
public decodedId: DeclaredId;
public interaction: APIModalSubmitInteraction; public interaction: APIModalSubmitInteraction;
constructor(interaction: APIModalSubmitInteraction, env: Env) { constructor(interaction: APIModalSubmitInteraction, env: Env) {
super(interaction, env); super(interaction, env);
this.decodedId = serializers.genericObject.decodeCustomId(
interaction.data.custom_id,
) as DeclaredId;
this.interaction = interaction; this.interaction = interaction;
} }
} }

View file

@ -1,3 +1,4 @@
import { RedisAPIClient } from "redis-api-client";
import { Command } from "./structs/Command"; import { Command } from "./structs/Command";
import { Component } from "./structs/Component"; import { Component } from "./structs/Component";
import { Modal } from "./structs/Modal"; import { Modal } from "./structs/Modal";
@ -5,6 +6,11 @@ import { Modal } from "./structs/Modal";
export const COMMANDS: Command[] = []; export const COMMANDS: Command[] = [];
export const COMPONENTS: Component[] = []; export const COMPONENTS: Component[] = [];
export const MODALS: Modal[] = []; export const MODALS: Modal[] = [];
export let REDIS: RedisAPIClient;
export const setRedis = (apiKey: string, host: string) => {
REDIS = new RedisAPIClient(apiKey, host);
};
export const registerCommand = (command: Command) => { export const registerCommand = (command: Command) => {
COMMANDS.push(command); COMMANDS.push(command);

View file

@ -18,4 +18,6 @@ declare type DeclaredId = Record<
declare interface Env { declare interface Env {
publicKey: string; publicKey: string;
token: string; token: string;
redisApiClientKey: string;
redisApiClientHost: string;
} }

View file

@ -1,19 +1,33 @@
import { Generic, serializers } from "serialize";
import { Context } from "../structs/contexts/Context"; import { Context } from "../structs/contexts/Context";
import { ActionRowBuilder, TextInputBuilder } from "builders"; import { ActionRowBuilder, TextInputBuilder } from "builders";
import { TextInputStyle } from "discord-api-types/v10"; import {
APIRole,
InteractionResponseType,
MessageFlags,
TextInputStyle,
} from "discord-api-types/v10";
import { REDIS } from "../things";
import { decodeFromString } from "serialize";
export default async function (ctx: Context, rawRole: string) {
const rolesRaw = await REDIS.get(`roles-bot-setup-roles:${ctx.guildId}`);
if (!rolesRaw)
return ctx.respond({
type: InteractionResponseType.ChannelMessageWithSource,
data: {
content:
"Something went wrong. Please try again.\nIf this problem persists, please contact [Support Server](https://discord.gg/kFPKmEKeMS/).",
flags: MessageFlags.Ephemeral,
},
});
const roles = decodeFromString(rolesRaw) as Partial<APIRole>[];
const roleName = roles?.find((r) => r.id === rawRole)?.name;
export default function (
data: Record<string, Generic>,
ctx: Context,
rawRole: string,
) {
return ctx.returnModal({ return ctx.returnModal({
title: `Role Setup ${rawRole}`, title: `${roleName?.slice(0, 39)} Role`,
custom_id: serializers.genericObject.encodeCustomId({ custom_id: "setup:part-roles-lpe",
type: "setup:part-roles-lpe",
data,
}),
components: [ components: [
new ActionRowBuilder<TextInputBuilder>() new ActionRowBuilder<TextInputBuilder>()
.addComponents( .addComponents(

View file

@ -2,6 +2,8 @@
"use strict"; "use strict";
import type { Env } from "../types";
function hex2bin(hex: string) { function hex2bin(hex: string) {
const buf = new Uint8Array(Math.ceil(hex.length / 2)); const buf = new Uint8Array(Math.ceil(hex.length / 2));
for (let i = 0; i < buf.length; i++) { for (let i = 0; i < buf.length; i++) {

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Jozef Steinhübl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1 @@
Client for [Redis API](../../apps/redis-api/)

View file

@ -0,0 +1,14 @@
{
"name": "redis-api-client",
"version": "0.0.1",
"author": "xHyroM",
"main": "dist/index.mjs",
"types": "dist/index.d.ts",
"scripts": {
"build": "node scripts/build.mjs && tsc -p tsconfig.json"
},
"devDependencies": {
"esbuild": "^0.15.11",
"typescript": "^4.8.4"
}
}

View file

@ -0,0 +1,38 @@
import esbuild from "esbuild";
import { rmSync, existsSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = fileURLToPath(new URL(".", import.meta.url));
if (existsSync(join(__dirname, "..", "dist")))
rmSync(join(__dirname, "..", "dist"), { recursive: true });
const watch = process.argv.includes("--watch");
const dev = process.argv.includes("--dev");
Promise.all([
esbuild.build({
bundle: true,
logLevel: "info",
format: "esm",
mainFields: ["browser", "module", "main"],
platform: "neutral",
target: "es2020",
entryPoints: ["./src/index.ts"],
outfile: "./dist/index.mjs",
sourcemap: dev,
charset: "utf8",
minify: !dev,
watch: watch,
}),
])
.catch((err) => {
console.error("Builders failed to build");
console.error(err.message);
})
.then(() => {
console.log(
watch ? "Waiting for your changes..." : "Builders has been built",
);
});

View file

@ -0,0 +1,70 @@
export class RedisAPIClient {
private apiKey: string;
private host: string;
constructor(apiKey: string, host: string) {
this.apiKey = apiKey;
this.host = host;
}
public async get(key: string): Promise<string> {
const url = `${this.host}/get?key=${key}`;
const response = await fetch(url, {
headers: {
Authorization: this.apiKey,
},
});
return response.text();
}
public async set(key: string, value: string): Promise<string> {
const url = `${this.host}/set`;
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: this.apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
key,
value,
}),
});
return response.text();
}
public async setex(
key: string,
value: string,
seconds: number,
): Promise<string> {
const url = `${this.host}/setex`;
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: this.apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
key,
value,
seconds,
}),
});
return response.text();
}
public async del(key: string): Promise<string> {
const url = `${this.host}/del?key=${key}`;
const response = await fetch(url, {
headers: {
Authorization: this.apiKey,
},
});
return response.text();
}
}

View file

@ -0,0 +1,15 @@
{
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"target": "ESNext",
"lib": ["ESNext", "WebWorker"],
"module": "ESNext",
"strict": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"declaration": true,
"emitDeclarationOnly": true
}
}

View file

@ -1,202 +1,21 @@
Apache License MIT License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION Copyright (c) 2023 Jozef Steinhübl
1. Definitions. Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
"License" shall mean the terms and conditions for use, reproduction, The above copyright notice and this permission notice shall be included in all
and distribution as defined by Sections 1 through 9 of this document. copies or substantial portions of the Software.
"Licensor" shall mean the copyright owner or entity authorized by THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
the copyright owner that is granting the License. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
"Legal Entity" shall mean the union of the acting entity and all AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
other entities that control, are controlled by, or are under common LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
control with that entity. For the purposes of this definition, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
"control" means (i) the power, direct or indirect, to cause the SOFTWARE.
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2021-2022 Dave Caruso
Copyright 2021-2022 CRBT Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1 +1 @@
[https://github.com/CRBT-Team/Purplet/blob/main/packages/serialize](https://github.com/CRBT-Team/Purplet/blob/main/packages/serialize) Simple serialization using MessagePack Lite

View file

@ -4,13 +4,17 @@
"main": "dist/index.mjs", "main": "dist/index.mjs",
"types": "dist/index.d.ts", "types": "dist/index.d.ts",
"scripts": { "scripts": {
"build": "node scripts/build.mjs && tsc -p tsconfig.json" "build": "node scripts/build.mjs && tsc -p tsconfig.json",
"test": "ava"
}, },
"devDependencies": { "devDependencies": {
"@types/msgpack-lite": "^0.1.8",
"ava": "^5.2.0",
"esbuild": "^0.15.11", "esbuild": "^0.15.11",
"fast-deep-equal": "^3.1.3",
"typescript": "^4.8.4" "typescript": "^4.8.4"
}, },
"dependencies": { "dependencies": {
"@paperdave/utils": "^1.6.1" "msgpack-lite": "^0.1.26"
} }
} }

View file

@ -28,11 +28,11 @@ Promise.all([
}), }),
]) ])
.catch((err) => { .catch((err) => {
console.error("Builders failed to build"); console.error("Serialize failed to build");
console.error(err.message); console.error(err.message);
}) })
.then(() => { .then(() => {
console.log( console.log(
watch ? "Waiting for your changes..." : "Builders has been built", watch ? "Waiting for your changes..." : "Serialize has been built",
); );
}); });

View file

@ -1,93 +0,0 @@
export class BitBuffer {
private array: Uint8Array;
private byteIndex = 0;
private bitIndex = 0;
get index() {
return this.byteIndex * 8 + this.bitIndex;
}
set index(value: number) {
this.byteIndex = Math.floor(value / 8);
this.bitIndex = value % 8;
}
get buffer() {
return this.array.buffer;
}
set buffer(v: ArrayBufferLike) {
this.array = new Uint8Array(v);
}
constructor(
input: Uint8Array | ArrayBufferLike | ArrayLike<number> | number = 256,
) {
this.array = new Uint8Array(
input instanceof Uint8Array ? input.buffer : (input as ArrayBufferLike),
);
}
seek(index: number) {
this.index = index;
return this;
}
read(length = 1) {
let result = 0;
for (let i = 0; i < length; i++) {
const bit = (this.array[this.byteIndex] >> this.bitIndex) & 1;
result |= bit << i;
this.bitIndex++;
if (this.bitIndex >= 8) {
this.bitIndex = 0;
this.byteIndex++;
}
}
return result;
}
write(value: number, length = 1) {
for (let i = 0; i < length; i++) {
const bit = (value >> i) & 1;
this.array[this.byteIndex] |= bit << this.bitIndex;
this.bitIndex++;
if (this.bitIndex >= 8) {
this.bitIndex = 0;
this.byteIndex++;
}
}
return this;
}
readBI(length = 1) {
let result = 0n;
for (let i = 0n; i < length; i++) {
const bit = (this.array[this.byteIndex] >> this.bitIndex) & 1;
if (bit) {
result |= 1n << i;
}
this.bitIndex++;
if (this.bitIndex >= 8) {
this.bitIndex = 0;
this.byteIndex++;
}
}
return result;
}
writeBI(value: bigint, length = 1) {
for (let i = 0n; i < length; i++) {
const bit = (value >> i) & 1n;
if (bit) {
this.array[this.byteIndex] |= 1 << this.bitIndex;
}
this.bitIndex++;
if (this.bitIndex >= 8) {
this.bitIndex = 0;
this.byteIndex++;
}
}
return this;
}
}

View file

@ -1,42 +0,0 @@
import { BitBuffer } from "./BitBuffer";
import { decodeCustomId, encodeCustomId } from "./custom-id";
export interface BitSerializerOptions<T> {
write(value: T, buffer: BitBuffer): void;
read(buffer: BitBuffer): T;
check?(value: unknown): value is T;
}
export class BitSerializer<T> {
constructor(private options: BitSerializerOptions<T>) {}
write(value: T, buffer: BitBuffer): void {
this.options.write(value, buffer);
}
read(buffer: BitBuffer): T {
return this.options.read(buffer);
}
check(value: unknown): value is T {
return this.options.check?.(value) ?? true;
}
encode(value: T, bufferLength = 256) {
const buffer = new BitBuffer(bufferLength);
this.options.write(value, buffer);
return new Uint8Array(buffer.buffer.slice(0, Math.ceil(buffer.index / 8)));
}
decode(value: Uint8Array): T {
return this.options.read(new BitBuffer(value));
}
encodeCustomId(value: T, bufferLength = 256) {
return encodeCustomId(this.encode(value, bufferLength));
}
decodeCustomId(value: string): T {
return this.decode(decodeCustomId(value));
}
}

View file

@ -1,42 +0,0 @@
// using all unicode characters from range 0 to 0x10FFFF, encode two and a half bytes per character
// This is essentially "base1114111"
export function encodeCustomId(data: Uint8Array) {
let output = "";
for (let i = 0; i < data.length; i += 5) {
const one = data[i];
const two = data[i + 1];
const three = data[i + 2];
const four = data[i + 3];
const five = data[i + 4];
// byte one contains one + two + the least significant bits of three
const codePoint1 = (one << 12) | (two << 4) | (three & 0b1111);
// byte two contains four + five + the most significant bits of three
const codePoint2 = (four << 12) | (five << 4) | (three >> 4);
output +=
String.fromCodePoint(codePoint1) + String.fromCodePoint(codePoint2);
}
return output;
}
export function decodeCustomId(data: string) {
const codePoints = [...data];
const output = new Uint8Array(Math.ceil(codePoints.length * 2.5));
let j = 0;
for (let i = 0; i < codePoints.length; i += 2, j += 5) {
// rome-ignore lint/style/noNonNullAssertion: <explanation>
const codePoint1 = codePoints[i].codePointAt(0)!;
// rome-ignore lint/style/noNonNullAssertion: <explanation>
const codePoint2 = codePoints[i + 1].codePointAt(0)!;
output[j] = (codePoint1 >>> 12) & 0xff;
output[j + 1] = (codePoint1 >>> 4) & 0xff;
output[j + 2] = (codePoint1 & 0xf) | ((codePoint2 & 0xf) << 4);
output[j + 3] = (codePoint2 >>> 12) & 0xff;
output[j + 4] = (codePoint2 >>> 4) & 0xff;
}
return output;
}

View file

@ -1,5 +1,41 @@
export { BitSerializer, type BitSerializerOptions } from "./BitSerializer"; import msgPack from "msgpack-lite";
export * as serializers from "./serializers";
export { BitBuffer } from "./BitBuffer"; export const encode = (data: Generic) => msgPack.encode(data);
export { type Generic } from "./utils"; export const decode = (data: Buffer) => msgPack.decode(data);
export { decodeCustomId, encodeCustomId } from "./custom-id";
export const encodeToHex = (data: Generic) =>
buffer_to_hex(msgPack.encode(data));
export const decodeFromString = (data: string) =>
msgPack.decode(hex_to_buffer(data));
function buffer_to_hex(buffer: Buffer) {
return Array.prototype.map
.call(buffer, function (val) {
let hex = val.toString(16).toUpperCase();
if (val < 16) hex = `0${hex}`;
return hex;
})
.join(" ");
}
function hex_to_buffer(string: string) {
return string
.split(/\s+/)
.filter(function (chr) {
return chr !== "";
})
.map(function (chr) {
return parseInt(chr, 16);
});
}
export type Generic =
| string
| number
| boolean
| bigint
| Date
| null
| undefined
| Generic[]
| { [key: string]: Generic };

View file

@ -1,352 +0,0 @@
import type { Dict } from "@paperdave/utils";
import type { BitBuffer } from "./BitBuffer";
import { BitSerializer } from "./BitSerializer";
import type { Generic } from "./utils";
import { fillArray } from "./utils";
/** Creates a serializer that does not read/write any data, but instead return a predefined constant. */
export function constant<T>(input: T): BitSerializer<T> {
return new BitSerializer({
read: () => input,
write: () => {},
check(value): value is T {
return value === input;
},
});
}
const nullSerializer = constant(null);
/** Serializer for a boolean value. */
export const boolean = new BitSerializer({
read(buffer) {
return buffer.read() === 1;
},
write(value, buffer) {
buffer.write(value ? 1 : 0);
},
check(value): value is boolean {
return typeof value === "boolean";
},
});
/** Creates a serializer for unsigned integers, at the given precision. */
function unsignedInt(bits: number) {
return new BitSerializer({
read(buffer) {
return buffer.read(bits);
},
write(value, buffer) {
buffer.write(value, bits);
},
check(value): value is number {
return (
typeof value === "number" &&
Math.floor(value) === value &&
value >= 0 &&
value < 1 << bits
);
},
});
}
/** Creates a serializer for signed integers, at the given precision. */
function signedInt(bits: number) {
const signBit = -1 << (bits - 1);
return new BitSerializer({
read(buffer) {
const value = buffer.read(bits);
const sign = buffer.read();
return value + (sign ? signBit : 0);
},
write(value, buffer) {
const sign = value < 0;
if (sign) {
value += signBit;
}
buffer.write(value, bits);
buffer.write(sign ? 1 : 0);
},
check(value): value is number {
return (
typeof value === "number" &&
Math.floor(value) === value &&
value >= -(1 << (bits - 1)) &&
value < 1 << (bits - 1)
);
},
});
}
/** Creates a serializer for unsigned BigInts, at the given precision. */
function unsignedBigInt(bits: number) {
return new BitSerializer({
read(buffer) {
return buffer.readBI(bits);
},
write(value, buffer) {
buffer.writeBI(value, bits);
},
check(value): value is bigint {
return typeof value === "bigint" && value >= 0;
},
});
}
/** Creates a serializer for unsigned floats, at the given precision. */
function signedBigInt(bits: number) {
const signBit = -1n << (BigInt(bits) - 1n);
return new BitSerializer({
read(buffer: BitBuffer) {
const value = buffer.readBI(bits);
const sign = buffer.readBI();
return value + (sign ? signBit : 0n);
},
write(value, buffer) {
const sign = value < 0;
if (sign) {
value += signBit;
}
buffer.writeBI(value, bits);
buffer.write(sign ? 1 : 0);
},
check(value): value is bigint {
return typeof value === "bigint";
},
});
}
/* Serializer for 8-bit unsigned integers. 0 <= n <= 255. */
export const u8 = unsignedInt(8);
/* Serializer for 16-bit unsigned integers. 0 <= n <= 65535. */
export const u16 = unsignedInt(16);
/* Serializer for 32-bit unsigned integers. 0 <= n <= 4294967295. */
export const u32 = unsignedInt(32);
/* Serializer for 8-bit signed integers. -128 <= n <= 127. */
export const s8 = signedInt(8);
/* Serializer for 16-bit signed integers. -32768 <= n <= 32767. */
export const s16 = signedInt(16);
/* Serializer for 32-bit signed integers. -2147483648 <= n <= 2147483647. */
export const s32 = signedInt(32);
/* Serializer for 8-bit unsigned BigInts. 0n <= n <= 255n. */
export const u8bi = unsignedBigInt(8);
/* Serializer for 16-bit unsigned BigInts. 0n <= n <= 65535n. */
export const u16bi = unsignedBigInt(16);
/* Serializer for 32-bit unsigned BigInts. 0n <= n <= 4294967295n. */
export const u32bi = unsignedBigInt(32);
/* Serializer for 64-bit unsigned BigInts. 0n <= n <= 18446744073709551615n. */
export const u64bi = unsignedBigInt(64);
/* Serializer for 128-bit unsigned BigInts. 0n <= n <= (39 digits). */
export const u128bi = unsignedBigInt(128);
/* Serializer for 8-bit signed BigInts. -128n <= n <= 127n. */
export const s8bi = signedBigInt(8);
/* Serializer for 16-bit signed BigInts. -32768n <= n <= 32767n. */
export const s16bi = signedBigInt(16);
/* Serializer for 32-bit signed BigInts. -2147483648n <= n <= 2147483647n. */
export const s32bi = signedBigInt(32);
/* Serializer for 64-bit signed BigInts. -9223372036854775808n <= n <= 9223372036854775807n. */
export const s64bi = signedBigInt(64);
/* Serializer for 128-bit signed BigInts. -170141183460469231731687303715884105728n <= n <= 170141183460469231731687303715884105727n. */
export const s128bi = signedBigInt(128);
/* Serializer for Discord snowflakes, which are u64bi strings. If you have a bigint value, use the `u64bi` serializer instead. */
export const snowflake = new BitSerializer({
read(buffer) {
return buffer.readBI(64).toString();
},
write(value, buffer) {
buffer.writeBI(BigInt(value), 64);
},
check(value): value is string {
return typeof value === "string" && /^[0-9]{18,20}$/.test(value);
},
});
/** Serializer for a JavaScript number (IEEE-754/float64) value. */
export const float = new BitSerializer({
read(buffer) {
return new Float64Array(
new Uint8Array(fillArray(8, () => buffer.read(8))).buffer,
)[0];
},
write(value, buffer) {
const view = new Uint8Array(new Float64Array([value]).buffer);
for (let i = 0; i < 8; i++) {
buffer.write(view[i], 8);
}
},
check(value): value is number {
return typeof value === "number";
},
});
/** Serializer for a `Date` value. */
export const date = new BitSerializer({
read(buffer) {
return new Date(Number(buffer.readBI(52)));
},
write(value, buffer) {
buffer.writeBI(BigInt(value.getTime()), 52);
},
check(value): value is Date {
return value instanceof Date;
},
});
/** Serializer for a string value. Uses a length + content approach, so it does not support lengths above 255. */
export const string = new BitSerializer({
read(buffer) {
const length = buffer.read(8);
const bytes = fillArray(length, () => buffer.read(8));
return new TextDecoder().decode(new Uint8Array(bytes));
},
write(value, buffer) {
const bytes = new TextEncoder().encode(value);
if (bytes.length > 255) {
throw new Error(
"String serializer does not support strings over 255 bytes.",
);
}
buffer.write(bytes.length, 8);
bytes.forEach((byte) => buffer.write(byte, 8));
},
check(value): value is string {
return typeof value === "string";
},
});
/**
* Creates a serializer for an array of values. Uses a length + content approach, so it does not
* support lengths above 255.
*/
export function arrayOf<T>(serializer: BitSerializer<T>) {
return new BitSerializer({
read(buffer) {
const length = buffer.read(8);
const array = [];
for (let i = 0; i < length; i++) {
array.push(serializer.read(buffer));
}
return array;
},
write(value, buffer) {
buffer.write(value.length, 8);
value.forEach((item) => serializer.write(item, buffer));
},
// rome-ignore lint/suspicious/noExplicitAny: <explanation>
check(value): value is any[] {
return (
Array.isArray(value) && value.every((item) => serializer.check(item))
);
},
});
}
/** Creates a serializer out of two other serializers. Uses one bit to tell them apart. */
export function or<A, B>(a: BitSerializer<A>, b: BitSerializer<B>) {
return new BitSerializer({
read(buffer) {
return buffer.read() ? a.read(buffer) : b.read(buffer);
},
write(value, buffer) {
const isA = a.check(value);
buffer.write(isA ? 1 : 0, 1);
if (isA) {
a.write(value, buffer);
} else {
b.write(value, buffer);
}
},
check(value): value is A | B {
return a.check(value) || b.check(value);
},
});
}
/** Serializer for numbers, using an extra bit to allow a short s16 when possible, otherwise float64. */
export const number = or(s16, float);
export function nullable<T>(serializer: BitSerializer<T>) {
return or(serializer, nullSerializer);
}
export function object<T extends Record<string, unknown>>(
definition: {
[K in keyof T]: BitSerializer<T[K]>;
},
): BitSerializer<T> {
const keys = Object.keys(definition).sort();
return new BitSerializer({
read(buffer) {
const obj = {} as T;
keys.forEach((key) => {
// rome-ignore lint/suspicious/noExplicitAny: <explanation>
(obj as any)[key] = definition[key].read(buffer) as any;
});
return obj;
},
write(value, buffer) {
keys.forEach((key) => {
// rome-ignore lint/suspicious/noExplicitAny: <explanation>
definition[key].write(value[key] as any, buffer);
});
},
check(value): value is T {
return (
typeof value === "object" &&
// rome-ignore lint/suspicious/noExplicitAny: <explanation>
keys.every((key) => definition[key].check((value as any)[key]))
);
},
});
}
/** Serializer for an object of `generic` values. */
export const genericObject = new BitSerializer<Record<string, Generic>>({
read(buffer) {
const obj: Dict<Generic> = {};
let key: string = string.read(buffer);
while (key !== "") {
obj[key] = generic.read(buffer);
key = string.read(buffer);
}
return obj;
},
write(value, buffer) {
Object.keys(value).forEach((key) => {
string.write(key, buffer);
generic.write(value[key], buffer);
});
string.write("", buffer);
},
check(value): value is Record<string, Generic> {
return (
value != null &&
typeof value === "object" &&
Object.keys(value).every(
// rome-ignore lint/suspicious/noExplicitAny: <explanation>
(key) => string.check(key) && generic.check((value as any)[key]),
)
);
},
});
export const genericArray = {
__proto__: BitSerializer.prototype,
} as unknown as BitSerializer<Generic[]>;
/**
* Serializer for the `generic` type, which is all JSON-compatible types, but also including Dates,
* undefined, and bigints up to 128 bits. Discord snowflakes have special treatment here as well, to
* reduce the number of serialized bytes from ~19 to 4 per snowflake.
*/
export const generic: BitSerializer<Generic> = or(
or(or(snowflake, string), or(constant(null), constant(undefined))),
or(
or(or(or(date, s128bi), boolean), or(genericArray, genericObject)),
number,
),
);
Object.assign(genericArray, arrayOf(generic));

View file

@ -1,18 +0,0 @@
export function fillArray<T>(length: number, cb: (index: number) => T): T[] {
const arr = new Array(length);
for (let i = 0; i < length; i++) {
arr[i] = cb(i);
}
return arr;
}
export type Generic =
| string
| number
| boolean
| bigint
| Date
| null
| undefined
| Generic[]
| { [key: string]: Generic };

File diff suppressed because it is too large Load diff

0
test.txt Normal file
View file