Dough Git

commit

initial commit

commit
b4eced14300f87c8786aea3ce760f5396bd2dc2f
author
Clove <[email protected]>
date
2026-11-25 10:18

diff --git a/.c4d/config.jp b/.c4d/config.jp
new file mode 100644
index 0000000..b3d3efb
--- /dev/null
+++ b/.c4d/config.jp
@@ -0,0 +1,27 @@
+~* Default configuration for code4dyslexia
+   (c) MIT - Clove Twilight 2026
+   https://github.com/doughmination/code4dyslexia
+*~
+
+[terminal]
+color: tritanopia
+
+[formatting]
+~~ Set any of these to 0 to disable them
+indentSize: 4
+newLineSize: 2
+~~ Enable to add a file path comment automatically
+filePathHeader: false
+
+[cases]
+~* Accepted values:
+   flatcase - acoolfunction
+   camelCase - aCoolFunction
+   PascalCase - ACoolFunction
+   snake_case - a_cool_function
+   SCREAMING_SNAKE_CASE - A_COOL_FUNCTION
+   disabled - Disables checks
+*~
+functions: camelCase
+variables: camelCase
+classes: camelCase
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..e45ed54
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,10 @@
+# .env example file
+
+# Bot's own config
+DISCORD_TOKEN=
+DISCORD_CLIENT_ID=
+
+# Server specific config
+SERVER_OWNER_ID=
+GUILD_ID=
+LOGGING_CHANNEL_ID=
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4c3a897
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,13 @@
+.env*
+!.env.example
+node_modules/
+*.jp
+!.c4d/config.jp
+!*.example.jp
+.DS_Store
+.agents/
+.aws/
+.codex/
+.claude/
+.vscode/
+.idea/
\ No newline at end of file
diff --git a/data/invites.example.jp b/data/invites.example.jp
new file mode 100644
index 0000000..0d4e143
--- /dev/null
+++ b/data/invites.example.jp
@@ -0,0 +1,5 @@
+~~ data/invites.example.jp
+
+[INVITE_CODE]
+created_by: "123456789012345678" ~~ Discord ID of the member who requested the link
+used_by: ""                     ~~ Discord ID of the member who joined, once known
diff --git a/deno.json b/deno.json
new file mode 100644
index 0000000..f2dc974
--- /dev/null
+++ b/deno.json
@@ -0,0 +1,17 @@
+{
+    "$schema": "https://raw.githubusercontent.com/denoland/deno/main/cli/schemas/config-file.v1.json",
+    "nodeModulesDir": "auto",
+    "license": "MIT",
+
+    "tasks": {
+        "dev": "deno run --watch --allow-net --allow-env --env-file=.env --allow-read=data --allow-write=data src/main.ts"
+    },
+
+    "minimumDependencyAge": 0,
+
+    "imports": {
+        "@std/assert": "jsr:@std/assert@^1.0.19",
+        "discord.js": "npm:discord.js@^14.28.1",
+        "jpcl-lang": "npm:jpcl-lang@^2.1.0"
+    }
+}
diff --git a/deno.lock b/deno.lock
new file mode 100644
index 0000000..0857e8b
--- /dev/null
+++ b/deno.lock
@@ -0,0 +1,168 @@
+{
+  "version": "5",
+  "specifiers": {
+    "jsr:@std/assert@^1.0.19": "1.0.19",
+    "jsr:@std/internal@^1.0.12": "1.0.14",
+    "npm:discord.js@^14.28.1": "14.28.1",
+    "npm:jpcl-lang@^2.1.0": "2.1.0"
+  },
+  "jsr": {
+    "@std/[email protected]": {
+      "integrity": "eaada96ee120cb980bc47e040f82814d786fe8162ecc53c91d8df60b8755991e",
+      "dependencies": [
+        "jsr:@std/internal"
+      ]
+    },
+    "@std/[email protected]": {
+      "integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
+    }
+  },
+  "npm": {
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-AifaDWTw6WUDhKBn8E6mwwoyjDAcfsYq+ZE0nKSu1dMH1NLR22D3hGkNx+ctEv8NqHEHdAZnP5REteHDmn1lkA==",
+      "dependencies": [
+        "@discordjs/formatters",
+        "@discordjs/util",
+        "@sapphire/shapeshift",
+        "discord-api-types",
+        "fast-deep-equal",
+        "ts-mixer",
+        "tslib"
+      ]
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ=="
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg=="
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==",
+      "dependencies": [
+        "discord-api-types"
+      ]
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==",
+      "dependencies": [
+        "@discordjs/[email protected]",
+        "@discordjs/util",
+        "@sapphire/async-queue",
+        "@sapphire/snowflake",
+        "@vladfrangu/async_event_emitter",
+        "discord-api-types",
+        "magic-bytes.js",
+        "tslib",
+        "undici"
+      ]
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==",
+      "dependencies": [
+        "discord-api-types"
+      ]
+    },
+    "@discordjs/[email protected]": {
+      "integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==",
+      "dependencies": [
+        "@discordjs/[email protected]",
+        "@discordjs/rest",
+        "@discordjs/util",
+        "@sapphire/async-queue",
+        "@types/ws",
+        "@vladfrangu/async_event_emitter",
+        "discord-api-types",
+        "tslib",
+        "ws"
+      ]
+    },
+    "@sapphire/[email protected]": {
+      "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg=="
+    },
+    "@sapphire/[email protected]": {
+      "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==",
+      "dependencies": [
+        "fast-deep-equal",
+        "lodash"
+      ],
+      "deprecated": true
+    },
+    "@sapphire/[email protected]": {
+      "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ=="
+    },
+    "@types/[email protected]": {
+      "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
+      "dependencies": [
+        "undici-types"
+      ]
+    },
+    "@types/[email protected]": {
+      "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==",
+      "dependencies": [
+        "@types/node"
+      ]
+    },
+    "@vladfrangu/[email protected]": {
+      "integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-2xPScuQP3WOf3H4EKWLzvnhlfNl8sBMD+krT8CcjMVJa6o9D/6ssOSgKPTvHyIhQDKUX+gvUJZ43U4HqE+6tsA=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-Je5OcqgurnIUQK4vR+gQnmzOf/lNQsD6d/UkV8ZOj+bFa5zJXPyiGXlbywp2EagwshVT18y7YNQNSRd3FjYkDw==",
+      "dependencies": [
+        "@discordjs/builders",
+        "@discordjs/[email protected]",
+        "@discordjs/formatters",
+        "@discordjs/rest",
+        "@discordjs/util",
+        "@discordjs/ws",
+        "@sapphire/snowflake",
+        "discord-api-types",
+        "fast-deep-equal",
+        "lodash.snakecase",
+        "magic-bytes.js",
+        "tslib",
+        "undici"
+      ]
+    },
+    "[email protected]": {
+      "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-h4gvMgoOtI46NfIleHLOMhOvj/cqWw3KWkqehssDiUgSoLO7wjRgMaW6188DQmArTpoFFMVCD15IWYfq/ltM2g==",
+      "bin": true
+    },
+    "[email protected]": {
+      "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA=="
+    },
+    "[email protected]": {
+      "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ=="
+    }
+  },
+  "workspace": {
+    "dependencies": [
+      "jsr:@std/assert@^1.0.19",
+      "npm:discord.js@^14.28.1",
+      "npm:jpcl-lang@^2.1.0"
+    ]
+  }
+}
diff --git a/src/commands/info.ts b/src/commands/info.ts
new file mode 100644
index 0000000..8f41c60
--- /dev/null
+++ b/src/commands/info.ts
@@ -0,0 +1,32 @@
+/* src/commands/info.ts */
+
+import {
+  type ChatInputCommandInteraction,
+  MessageFlags,
+  SlashCommandBuilder,
+} from "discord.js";
+
+const sourceUrl = "https://git.doughmination.gay/clove/inviteTracker";
+
+export const infoCommand = new SlashCommandBuilder()
+  .setName("info")
+  .setDescription("Show the source, Discord latency, and tracked invite count");
+
+export async function replyWithInfo(
+  interaction: ChatInputCommandInteraction,
+  trackedInvites: number,
+) {
+  const ping = interaction.client.ws.ping;
+  const latency = Number.isFinite(ping) && ping >= 0
+    ? `${Math.round(ping)} ms`
+    : "Unavailable";
+
+  await interaction.reply({
+    content: [
+      `**Source** · <${sourceUrl}>`,
+      `**Discord gateway latency** · ${latency}`,
+      `**Tracked invites (including used)** · ${trackedInvites}`,
+    ].join("\n"),
+    flags: MessageFlags.Ephemeral,
+  });
+}
diff --git a/src/commands/invite.ts b/src/commands/invite.ts
new file mode 100644
index 0000000..4b9b181
--- /dev/null
+++ b/src/commands/invite.ts
@@ -0,0 +1,83 @@
+/* src/commands/invite.ts */
+
+import {
+  ChannelType,
+  type ChatInputCommandInteraction,
+  type Guild,
+  PermissionFlagsBits,
+  SlashCommandBuilder,
+} from "discord.js";
+import { logInvite } from "../utils/logging.ts";
+import { type InviteRecord, saveInvite } from "../utils/storage.ts";
+
+export const inviteCommand = new SlashCommandBuilder()
+  .setName("invite")
+  .setDescription("Create a one-use invite to a server channel")
+  .setDefaultMemberPermissions(PermissionFlagsBits.CreateInstantInvite)
+  .addChannelOption((option) =>
+    option.setName("channel")
+      .setDescription("The channel the invite opens")
+      .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)
+  );
+
+export async function issueInvite(
+  interaction: ChatInputCommandInteraction,
+  guild: Guild,
+  records: Map<string, InviteRecord>,
+  logChannelId: string,
+  rememberInvite: (code: string) => void,
+) {
+  const channelId = interaction.options.getChannel("channel")?.id ??
+    interaction.channelId;
+  const channel = await guild.channels.fetch(channelId);
+  const requester = await guild.members.fetch(interaction.user.id);
+
+  if (
+    !channel ||
+    (channel.type !== ChannelType.GuildText &&
+      channel.type !== ChannelType.GuildAnnouncement) ||
+    !channel.permissionsFor(requester).has([
+      PermissionFlagsBits.ViewChannel,
+      PermissionFlagsBits.CreateInstantInvite,
+    ])
+  ) {
+    await interaction.editReply(
+      "Choose a text channel where you can view the channel and create invites.",
+    );
+    return;
+  }
+
+  const invite = await guild.invites.create(channel, {
+    maxUses: 1,
+    maxAge: 0,
+    unique: true,
+    reason: `One-use invite requested by ${requester.id}`,
+  });
+
+  try {
+    await saveInvite(records, invite.code, {
+      created_by: requester.id,
+      used_by: "",
+    });
+  } catch (error) {
+    await invite.delete("Could not persist the invite").catch(console.error);
+    throw error;
+  }
+
+  rememberInvite(invite.code);
+  const logged = await logInvite(
+    guild,
+    logChannelId,
+    `One-use invite \`${invite.code}\` created by <@${requester.id}> for <#${channel.id}>.`,
+  ).then(() => true).catch((error) => {
+    console.error(error);
+    return false;
+  });
+
+  const reply = `One-use invite: ${invite.url}`;
+  await interaction.editReply(
+    logged
+      ? reply
+      : `${reply}\nThe invite was saved, but the Discord log could not be posted.`,
+  );
+}
diff --git a/src/commands/ping.ts b/src/commands/ping.ts
new file mode 100644
index 0000000..b4d19ed
--- /dev/null
+++ b/src/commands/ping.ts
@@ -0,0 +1,18 @@
+/* src/commands/ping.ts */
+
+import {
+  type ChatInputCommandInteraction,
+  MessageFlags,
+  SlashCommandBuilder,
+} from "discord.js";
+
+export const pingCommand = new SlashCommandBuilder()
+  .setName("ping")
+  .setDescription("Check whether the bot is responding");
+
+export async function replyToPing(interaction: ChatInputCommandInteraction) {
+  await interaction.reply({
+    content: "Pong! The bot is online.",
+    flags: MessageFlags.Ephemeral,
+  });
+}
diff --git a/src/main.ts b/src/main.ts
new file mode 100644
index 0000000..7910e6b
--- /dev/null
+++ b/src/main.ts
@@ -0,0 +1,193 @@
+/* src/main.ts */
+
+import {
+  Client,
+  Events,
+  GatewayIntentBits,
+  MessageFlags,
+  Routes,
+} from "discord.js";
+import { infoCommand, replyWithInfo } from "./commands/info.ts";
+import { inviteCommand, issueInvite } from "./commands/invite.ts";
+import { pingCommand, replyToPing } from "./commands/ping.ts";
+import { logInvite } from "./utils/logging.ts";
+import { loadInvites, saveInvite } from "./utils/storage.ts";
+
+function requiredEnv(name: string): string {
+  const value = Deno.env.get(name)?.trim();
+  if (!value) throw new Error(`Set ${name} in .env`);
+  return value;
+}
+
+const token = requiredEnv("DISCORD_TOKEN");
+const applicationId = requiredEnv("DISCORD_CLIENT_ID");
+const guildId = requiredEnv("GUILD_ID");
+const logChannelId = requiredEnv("LOGGING_CHANNEL_ID");
+const records = await loadInvites();
+
+const client = new Client({
+  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers],
+});
+
+const guild = () => client.guilds.fetch(guildId);
+
+async function snapshotInvites() {
+  const server = await guild();
+  const invites = await server.invites.fetch();
+  const counts = new Map(
+    invites.map((invite) => [invite.code, invite.uses ?? 0]),
+  );
+
+  if (server.vanityURLCode) {
+    const vanity = await server.fetchVanityData();
+    if (vanity.code) counts.set(vanity.code, vanity.uses);
+  }
+
+  return counts;
+}
+
+let previousInvites: Map<string, number> | undefined;
+let pending = Promise.resolve();
+
+function enqueue(operation: () => Promise<void>) {
+  pending = pending.then(operation).catch(console.error);
+}
+
+client.on(Events.Error, console.error);
+
+client.once(Events.ClientReady, () => {
+  enqueue(async () => {
+    for (const command of [inviteCommand, pingCommand, infoCommand]) {
+      await client.rest.post(
+        Routes.applicationGuildCommands(applicationId, guildId),
+        { body: command.toJSON() },
+      );
+    }
+
+    previousInvites = await snapshotInvites();
+    console.log(`Invite tracker ready for guild ${guildId}`);
+  });
+});
+
+client.on(Events.ShardResume, () => {
+  enqueue(async () => {
+    previousInvites = undefined;
+    previousInvites = await snapshotInvites();
+  });
+});
+
+client.on(Events.InteractionCreate, async (interaction) => {
+  if (!interaction.isChatInputCommand() || interaction.guildId !== guildId) {
+    return;
+  }
+
+  try {
+    switch (interaction.commandName) {
+      case pingCommand.name:
+        await replyToPing(interaction);
+        return;
+      case infoCommand.name:
+        await replyWithInfo(interaction, records.size);
+        return;
+      case inviteCommand.name:
+        break;
+      default:
+        return;
+    }
+
+    await interaction.deferReply({ flags: MessageFlags.Ephemeral });
+  } catch (error) {
+    console.error(error);
+    return;
+  }
+
+  enqueue(async () => {
+    try {
+      await issueInvite(
+        interaction,
+        await guild(),
+        records,
+        logChannelId,
+        (code) => previousInvites?.set(code, 0),
+      );
+    } catch (error) {
+      console.error(error);
+      if (!interaction.replied) {
+        await interaction.editReply("Could not create a tracked invite.");
+      }
+    }
+  });
+});
+
+const joiningMembers = new Set<string>();
+let joinTimer: ReturnType<typeof setTimeout> | undefined;
+
+client.on(Events.GuildMemberAdd, (member) => {
+  if (member.guild.id !== guildId || member.user.bot) return;
+
+  joiningMembers.add(member.id);
+  if (joinTimer !== undefined) return;
+
+  joinTimer = setTimeout(() => {
+    joinTimer = undefined;
+    enqueue(async () => {
+      const currentInvites = await snapshotInvites().catch((error) => {
+        previousInvites = undefined;
+        joiningMembers.clear();
+        throw error;
+      });
+
+      // Include joins received while the invite counts were being fetched.
+      const members = [...joiningMembers];
+      joiningMembers.clear();
+      const before = previousInvites;
+      previousInvites = currentInvites;
+
+      if (members.length === 0 || !before) return;
+
+      const changedCodes = new Set<string>();
+
+      for (const [code, uses] of currentInvites) {
+        if (uses > (before.get(code) ?? 0)) changedCodes.add(code);
+      }
+
+      // Discord can remove an exhausted one-use invite from the listing.
+      for (const code of before.keys()) {
+        if (!currentInvites.has(code)) changedCodes.add(code);
+      }
+
+      const [code] = changedCodes;
+      const record = records.get(code);
+
+      if (
+        members.length !== 1 || changedCodes.size !== 1 ||
+        !record || record.used_by
+      ) {
+        if (
+          [...changedCodes].some((code) => records.get(code)?.used_by === "")
+        ) {
+          await logInvite(
+            member.guild,
+            logChannelId,
+            "A tracked invite changed during a join, but its user could not be determined.",
+          );
+        }
+        return;
+      }
+
+      const [joinedUserId] = members;
+      await saveInvite(records, code, {
+        created_by: record.created_by,
+        used_by: joinedUserId,
+      });
+
+      await logInvite(
+        member.guild,
+        logChannelId,
+        `<@${joinedUserId}> joined with one-use invite \`${code}\` created by <@${record.created_by}>.`,
+      );
+    });
+  }, 750);
+});
+
+await client.login(token);
diff --git a/src/utils/logging.ts b/src/utils/logging.ts
new file mode 100644
index 0000000..fd02427
--- /dev/null
+++ b/src/utils/logging.ts
@@ -0,0 +1,22 @@
+/* src/utils/logging.ts */
+
+import type { Guild } from "discord.js";
+
+export async function logInvite(
+  guild: Guild,
+  channelId: string,
+  content: string,
+) {
+  const channel = await guild.channels.fetch(channelId);
+
+  if (!channel?.isSendable()) {
+    throw new Error(
+      "LOGGING_CHANNEL_ID must identify a sendable guild channel",
+    );
+  }
+
+  await channel.send({
+    content,
+    allowedMentions: { parse: [] },
+  });
+}
diff --git a/src/utils/storage.ts b/src/utils/storage.ts
new file mode 100644
index 0000000..9fbc03c
--- /dev/null
+++ b/src/utils/storage.ts
@@ -0,0 +1,58 @@
+/* src/utils/storage.ts */
+
+import { parse, stringify } from "jpcl-lang";
+
+export type InviteRecord = {
+  created_by: string;
+  used_by: string;
+};
+
+const inviteFile = "data/invites.jp";
+
+export async function loadInvites(): Promise<Map<string, InviteRecord>> {
+  let contents: string;
+
+  try {
+    contents = await Deno.readTextFile(inviteFile);
+  } catch (error) {
+    if (error instanceof Deno.errors.NotFound) return new Map();
+    throw error;
+  }
+
+  const records = new Map<string, InviteRecord>();
+
+  for (const [code, record] of Object.entries(parse(contents))) {
+    if (
+      !record || typeof record !== "object" ||
+      !("created_by" in record) || !("used_by" in record) ||
+      typeof record.created_by !== "string" ||
+      (record.used_by != null && typeof record.used_by !== "string")
+    ) {
+      throw new Error(`Invalid invite record for ${code}`);
+    }
+
+    records.set(code, {
+      created_by: record.created_by,
+      used_by: record.used_by ?? "",
+    });
+  }
+
+  return records;
+}
+
+export async function saveInvite(
+  records: Map<string, InviteRecord>,
+  code: string,
+  record: InviteRecord,
+) {
+  const updated = new Map(records);
+  updated.set(code, record);
+
+  const temporaryFile = "data/invites.tmp.jp";
+  await Deno.writeTextFile(
+    temporaryFile,
+    stringify(Object.fromEntries(updated)),
+  );
+  await Deno.rename(temporaryFile, inviteFile);
+  records.set(code, record);
+}